create-mana 0.0.0-stage → 0.1.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 +28 -2
- package/bin/create-mana.mjs +5 -0
- package/kits/auth/files/src/api/auth.ts +100 -0
- package/kits/auth/files/src/api/profile.ts +48 -0
- package/kits/auth/files/src/api/types.ts +28 -0
- package/kits/auth/files/src/components/AppLayout.mana +31 -0
- package/kits/auth/files/src/components/VerifyBanner.mana +47 -0
- package/kits/auth/files/src/router/routes.ts +31 -0
- package/kits/auth/files/src/shared/events.ts +11 -0
- package/kits/auth/files/src/stores/session.ts +99 -0
- package/kits/auth/files/src/views/ForgotPassword.mana +83 -0
- package/kits/auth/files/src/views/Home.mana +15 -0
- package/kits/auth/files/src/views/Profile.mana +172 -0
- package/kits/auth/files/src/views/Register.mana +86 -0
- package/kits/auth/files/src/views/ResetPassword.mana +90 -0
- package/kits/auth/files/src/views/SignIn.mana +84 -0
- package/kits/auth/files/src/views/VerifyEmail.mana +78 -0
- package/kits/auth/files/tests/auth.test.mjs +93 -0
- package/kits/auth/files/tests/home.test.mjs +38 -0
- package/kits/auth/files/tests/profile.test.mjs +68 -0
- package/kits/auth/files/tests/support/users.mjs +2 -0
- package/kits/auth/kit.json +80 -0
- package/kits/base/files/README.md +39 -0
- package/kits/base/kit.json +7 -0
- package/kits/organisations/files/src/api/auth.ts +124 -0
- package/kits/organisations/files/src/api/members.ts +243 -0
- package/kits/organisations/files/src/api/notifications.ts +63 -0
- package/kits/organisations/files/src/api/organisations.ts +41 -0
- package/kits/organisations/files/src/api/scope.ts +98 -0
- package/kits/organisations/files/src/api/types.ts +72 -0
- package/kits/organisations/files/src/assets/styles/organisations.css +46 -0
- package/kits/organisations/files/src/components/AppLayout.mana +90 -0
- package/kits/organisations/files/src/components/NotificationBell.mana +35 -0
- package/kits/organisations/files/src/components/NotificationList.mana +112 -0
- package/kits/organisations/files/src/components/OrganisationSwitcher.mana +171 -0
- package/kits/organisations/files/src/composables/notifications.ts +28 -0
- package/kits/organisations/files/src/router/routes.ts +43 -0
- package/kits/organisations/files/src/shared/roles.ts +10 -0
- package/kits/organisations/files/src/stores/notifications.ts +41 -0
- package/kits/organisations/files/src/stores/session.ts +158 -0
- package/kits/organisations/files/src/utilities/format.ts +15 -0
- package/kits/organisations/files/src/views/Forbidden.mana +28 -0
- package/kits/organisations/files/src/views/Home.mana +15 -0
- package/kits/organisations/files/src/views/Invite.mana +156 -0
- package/kits/organisations/files/src/views/InviteMember.mana +99 -0
- package/kits/organisations/files/src/views/Members.mana +218 -0
- package/kits/organisations/files/src/views/NoOrganisation.mana +184 -0
- package/kits/organisations/files/src/views/Notifications.mana +30 -0
- package/kits/organisations/files/src/views/OrganisationForm.mana +76 -0
- package/kits/organisations/files/src/views/OrganisationSettings.mana +62 -0
- package/kits/organisations/files/src/views/Profile.mana +213 -0
- package/kits/organisations/files/src/views/Register.mana +113 -0
- package/kits/organisations/files/tests/auth.test.mjs +82 -0
- package/kits/organisations/files/tests/home.test.mjs +43 -0
- package/kits/organisations/files/tests/members.test.mjs +89 -0
- package/kits/organisations/files/tests/notifications.test.mjs +49 -0
- package/kits/organisations/files/tests/organisations.test.mjs +70 -0
- package/kits/organisations/files/tests/profile.test.mjs +79 -0
- package/kits/organisations/files/tests/support/users.mjs +3 -0
- package/kits/organisations/kit.json +51 -0
- package/lib/compose.mjs +209 -0
- package/lib/new.mjs +161 -0
- package/lib/prompts.mjs +182 -0
- package/package.json +36 -4
- package/template/.nvmrc +1 -0
- package/template/README.md +23 -0
- package/template/_gitignore +25 -0
- package/template/index.html +17 -0
- package/template/package.json +22 -0
- package/template/public/favicon.svg +1 -0
- package/template/public/icons.svg +24 -0
- package/template/src/App.mana +15 -0
- package/template/src/api/ApiError.ts +17 -0
- package/template/src/api/client.ts +116 -0
- package/template/src/assets/styles/main.css +158 -0
- package/template/src/components/AppLogo.mana +20 -0
- package/template/src/components/Button.mana +25 -0
- package/template/src/components/ConfirmHost.mana +43 -0
- package/template/src/components/TextField.mana +60 -0
- package/template/src/components/ToastHost.mana +40 -0
- package/template/src/composables/media.ts +19 -0
- package/template/src/composables/unsaved.ts +29 -0
- package/template/src/main.ts +25 -0
- package/template/src/router/index.ts +14 -0
- package/template/src/router/routes.ts +11 -0
- package/template/src/stores/confirm.ts +45 -0
- package/template/src/stores/toasts.ts +64 -0
- package/template/src/utilities/query.ts +40 -0
- package/template/src/utilities/timers.ts +12 -0
- package/template/src/views/Home.mana +12 -0
- package/template/src/views/NotFound.mana +13 -0
- package/template/tests/home.test.mjs +29 -0
- package/template/tests/support/api.mjs +44 -0
- package/template/tests/support/check.mjs +15 -0
- package/template/tests/support/dom.mjs +45 -0
- package/template/tests/support/paths.mjs +54 -0
- package/template/tests/support/settle.mjs +15 -0
- package/template/tsconfig.json +35 -0
- package/template/vite.config.ts +29 -0
- package/versions.json +3 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// The profile page: the details and the password, through the real page against a faked API — a new name applies at once; a new email waits for its link, with Resend and Cancel; the API's words about a
|
|
2
|
+
// field show on it; a password is checked before it's sent, and the API has the last word.
|
|
3
|
+
import { check } from "./support/check.mjs";
|
|
4
|
+
import { settle } from "./support/settle.mjs";
|
|
5
|
+
import { useDom } from "./support/dom.mjs";
|
|
6
|
+
import { useFakeApi } from "./support/api.mjs";
|
|
7
|
+
import { apiUser } from "./support/users.mjs";
|
|
8
|
+
|
|
9
|
+
const w = useDom('<main id="app"></main>', { url: "http://app.test/profile" });
|
|
10
|
+
const api = useFakeApi();
|
|
11
|
+
let user = apiUser();
|
|
12
|
+
|
|
13
|
+
api.get("/api/user", () => ({ json: user }));
|
|
14
|
+
api.patch("/api/user", body => body.email == "taken@example.test"
|
|
15
|
+
? { status: 422, json: { message: "Another account uses this email.", errors: { email: ["Another account uses this email."] } } }
|
|
16
|
+
: (user = apiUser({ name: body.name, pending_email: body.email == user.email ? null : body.email }), { json: user }));
|
|
17
|
+
api.post("/api/user/email/resend", () => ({ status: 204 }));
|
|
18
|
+
api.delete("/api/user/email/pending", () => (user = apiUser({ ...user, pending_email: null }), { json: user }));
|
|
19
|
+
api.put("/api/user/password", body => body.current_password == "password" ? { status: 204 } : { status: 422, json: { message: "That isn't your current password.", errors: { current_password: ["That isn't your current password."] } } });
|
|
20
|
+
|
|
21
|
+
const { createApp, createEvents, createStores } = await import("@mana-js/mana");
|
|
22
|
+
const { default: App } = await import("@/App.mana");
|
|
23
|
+
const { default: router } = await import("@/router");
|
|
24
|
+
const { useSession } = await import("@/stores/session");
|
|
25
|
+
let session;
|
|
26
|
+
const Probe = { setup() { session = useSession(); return {}; }, template: `<i></i>` };
|
|
27
|
+
|
|
28
|
+
createApp({ components: { App, Probe }, template: `<div><App /><Probe /></div>` }).use(createStores()).use(createEvents()).use(router).mount("#app");
|
|
29
|
+
await session.load();
|
|
30
|
+
await router.isReady();
|
|
31
|
+
await router.push("/profile");
|
|
32
|
+
await settle();
|
|
33
|
+
|
|
34
|
+
const root = document.getElementById("app");
|
|
35
|
+
const $ = s => root.querySelector(s);
|
|
36
|
+
const text = s => $(s)?.textContent.replace(/\s+/g, " ").trim() ?? null;
|
|
37
|
+
const type = (id, value) => { const input = $(id); input.value = value; input.dispatchEvent(new w.Event("input")); };
|
|
38
|
+
const click = el => el.dispatchEvent(new w.MouseEvent("click", { bubbles: true, cancelable: true }));
|
|
39
|
+
const button = label => [...root.querySelectorAll("button")].find(b => b.textContent.trim() == label);
|
|
40
|
+
const wait = async () => { await new Promise(resolve => setTimeout(resolve, 30)); await settle(); };
|
|
41
|
+
|
|
42
|
+
check("the profile: their name and email in the form, Save changes off until something changes", $("#profile-name").value == "Ama Owusu" && $("#profile-email").value == "ama@example.test" && button("Save changes").disabled);
|
|
43
|
+
|
|
44
|
+
type("#profile-name", "Ama Owusu-Boateng");
|
|
45
|
+
click(button("Save changes")); await wait();
|
|
46
|
+
check("a new name applies at once: the API's asked, the top bar follows, Saved.", api.calls.some(call => call.method == "PATCH" && call.body.name == "Ama Owusu-Boateng" && call.body.email == "ama@example.test") && /Ama Owusu-Boateng/.test(text(".topbar") ?? "") && /Saved\./.test(text(".saved") ?? ""));
|
|
47
|
+
|
|
48
|
+
type("#profile-email", "NEW@example.test");
|
|
49
|
+
click(button("Save changes")); await wait();
|
|
50
|
+
check("a new email waits for its link: said so, with Resend and Cancel; the old one still signs in", /We sent a link to new@example\.test/.test(text(".pending") ?? "") && button("Resend the link") && button("Cancel the change") && session.user.email == "ama@example.test");
|
|
51
|
+
click(button("Resend the link")); await wait();
|
|
52
|
+
check("Resend asks the API", api.calls.some(call => call.path == "/api/user/email/resend"));
|
|
53
|
+
click(button("Cancel the change")); await wait();
|
|
54
|
+
check("Cancel gives it up: nothing's waiting", !$(".pending") && api.calls.some(call => call.method == "DELETE" && call.path == "/api/user/email/pending"));
|
|
55
|
+
|
|
56
|
+
type("#profile-email", "taken@example.test");
|
|
57
|
+
click(button("Save changes")); await wait();
|
|
58
|
+
check("an email another account has: the API's words, on the email", text("#profile-email-error") == "Another account uses this email.");
|
|
59
|
+
|
|
60
|
+
type("#profile-current", "wrong"); type("#profile-password", "short"); type("#profile-confirm", "other");
|
|
61
|
+
click(button("Change password")); await settle();
|
|
62
|
+
check("a password is checked first: too short and unconfirmed, nothing sent", /at least 8/.test(text("#profile-password-error") ?? "") && /don't match/.test(text("#profile-confirm-error") ?? "") && api.calls.every(call => call.method != "PUT"));
|
|
63
|
+
type("#profile-password", "a long new password"); type("#profile-confirm", "a long new password");
|
|
64
|
+
click(button("Change password")); await wait();
|
|
65
|
+
check("the API has the last word: a wrong current password is said on its field", text("#profile-current-error") == "That isn't your current password.");
|
|
66
|
+
type("#profile-current", "password");
|
|
67
|
+
click(button("Change password")); await wait();
|
|
68
|
+
check("the right one: Password changed., the fields empty", /Password changed\./.test(document.body.textContent) && $("#profile-current").value == "");
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// A user as the API answers with them, and the app mounted as main.ts mounts it — the real root component, router and stores — for the suites of the pages that need someone signed in.
|
|
2
|
+
export const apiUser = (more = {}) => ({ id: 1, name: "Ama Owusu", email: "ama@example.test", verified: true, pending_email: null, ...more });
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "auth",
|
|
3
|
+
"type": "kit",
|
|
4
|
+
"title": "Auth",
|
|
5
|
+
"requires": [],
|
|
6
|
+
"description": "Sign in, register, forgot and reset password, confirming an email by its link, a profile, and the guards — the pages for the Coven starter's Auth kit.",
|
|
7
|
+
"patches": [
|
|
8
|
+
{
|
|
9
|
+
"file": "src/main.ts",
|
|
10
|
+
"marker": "imports",
|
|
11
|
+
"insert": [
|
|
12
|
+
"import { useSession } from \"@/stores/session\";",
|
|
13
|
+
"import { useToasts } from \"@/stores/toasts\";",
|
|
14
|
+
"import \"@/shared/events\";"
|
|
15
|
+
]
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"file": "src/main.ts",
|
|
19
|
+
"marker": "setup",
|
|
20
|
+
"insert": [
|
|
21
|
+
" // Who's signed in, asked of the API before the router's first page, so its guard knows. If the API can't be reached, the app starts signed out, saying so — once the router's there, which the",
|
|
22
|
+
" // toasts follow.",
|
|
23
|
+
" const session = app.runWithContext(() => useSession());",
|
|
24
|
+
" let reached = true;",
|
|
25
|
+
"",
|
|
26
|
+
" try {",
|
|
27
|
+
" await session.load();",
|
|
28
|
+
" } catch {",
|
|
29
|
+
" session.$reset();",
|
|
30
|
+
" reached = false;",
|
|
31
|
+
" }",
|
|
32
|
+
""
|
|
33
|
+
]
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"file": "src/main.ts",
|
|
37
|
+
"marker": "ready",
|
|
38
|
+
"insert": [
|
|
39
|
+
" if(!reached)",
|
|
40
|
+
" app.runWithContext(() => useToasts()).error(\"Couldn't reach the server\", \"Check your connection, then reload the page.\");",
|
|
41
|
+
"",
|
|
42
|
+
" // However the session ends, the user lands on the sign-in page.",
|
|
43
|
+
" events.on(\"signedOut\", () => void router.replace({ name: \"login\" }));",
|
|
44
|
+
""
|
|
45
|
+
]
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"file": "src/router/index.ts",
|
|
49
|
+
"marker": "imports",
|
|
50
|
+
"insert": [
|
|
51
|
+
"import { useSession } from \"@/stores/session\";"
|
|
52
|
+
]
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"file": "src/router/index.ts",
|
|
56
|
+
"marker": "middleware",
|
|
57
|
+
"insert": [
|
|
58
|
+
"// Signed-in pages: anyone else signs in first, then comes back (a plain visit to the home page needs no way back: signing in lands there anyway).",
|
|
59
|
+
"router.middleware(\"auth\", to => {",
|
|
60
|
+
" const sessionStore = useSession();",
|
|
61
|
+
"",
|
|
62
|
+
" if(!sessionStore.signedIn)",
|
|
63
|
+
" return to.fullPath == router.url(\"dashboard\") ? { name: \"login\" } : { name: \"login\", query: { redirect: to.fullPath } };",
|
|
64
|
+
"});",
|
|
65
|
+
"",
|
|
66
|
+
"// Signed-out pages: a signed-in user has no use for them.",
|
|
67
|
+
"router.middleware(\"guest\", () => {",
|
|
68
|
+
" const sessionStore = useSession();",
|
|
69
|
+
"",
|
|
70
|
+
" if(sessionStore.signedIn)",
|
|
71
|
+
" return { name: \"dashboard\" };",
|
|
72
|
+
"});",
|
|
73
|
+
""
|
|
74
|
+
]
|
|
75
|
+
}
|
|
76
|
+
],
|
|
77
|
+
"notes": [
|
|
78
|
+
"Sign in as admin@example.test with the password \"password\" once the API has run `npm run coven db:seed`."
|
|
79
|
+
]
|
|
80
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Mana Starter
|
|
2
|
+
|
|
3
|
+
A front end on [Mana](https://github.com/innova-ghx/mana-framework), made by `npm create mana@latest`. Vite serves it, `mana-tsc` checks its types, and its tests run in jsdom: there's nothing else to set up.
|
|
4
|
+
|
|
5
|
+
## First run
|
|
6
|
+
|
|
7
|
+
1. `npm install`, if the installer didn't.
|
|
8
|
+
2. `npm run dev` serves on http://localhost:5173. Anything under `/api` is passed on to the API at `http://localhost:3000` (a Coven starter, from `coven new`); to use another, `API_URL=http://localhost:7777 npm run dev`.
|
|
9
|
+
3. `npm test` runs every test. `npm run build` checks the types and makes the production files in `dist/`.
|
|
10
|
+
|
|
11
|
+
## What's here
|
|
12
|
+
|
|
13
|
+
| | |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `src/main.ts` | Where the app starts: the router, the stores, what's asked of the API before the first page. |
|
|
16
|
+
| `src/router/` | `routes.ts` is the pages and their paths; `index.ts` is the guards that run between them. |
|
|
17
|
+
| `src/views/` | One file for each page (`.mana`). |
|
|
18
|
+
| `src/components/` | What pages are made of: buttons, fields, toasts, confirmations. |
|
|
19
|
+
| `src/stores/`, `src/composables/` | State kept across pages, and the logic pages share. |
|
|
20
|
+
| `src/api/` | Talking to the API: `client.ts` sends the requests (cookie and CSRF token included) and `ApiError.ts` is what a failed one throws. |
|
|
21
|
+
| `src/assets/styles/` | The stylesheets. |
|
|
22
|
+
| `tests/` | Tests that load pages in jsdom against a fake API, to copy the style of. |
|
|
23
|
+
{{#if auth}}
|
|
24
|
+
|
|
25
|
+
## Signing in
|
|
26
|
+
|
|
27
|
+
`src/stores/session.ts` knows who's signed in: it's asked of the API before the first page (`session.load()` in `src/main.ts`), so the router's guards — `auth` for pages that need someone, `guest` for sign-in and register — decide at once.
|
|
28
|
+
Put `meta: { middleware: ["auth"] }` on a route to close it to anyone signed out. The pages for registering, signing in, forgot and reset password, confirming an email and the profile are in `src/views/`.
|
|
29
|
+
{{/if}}
|
|
30
|
+
{{#if organisations}}
|
|
31
|
+
|
|
32
|
+
## Organisations
|
|
33
|
+
|
|
34
|
+
The user works in one organisation at a time, which `OrganisationSwitcher` in the layout changes. `src/api/scope.ts` makes `workIn(organisation)`, which the calls for what belongs to an organisation go through, so each names
|
|
35
|
+
the organisation it's for. Routes with the `organisation` middleware wait for one to be chosen (and send someone with none to the page for it); the `role` middleware is for pages only owners or admins may open. Members,
|
|
36
|
+
invitations, settings and notifications are in `src/views/`.
|
|
37
|
+
{{/if}}
|
|
38
|
+
|
|
39
|
+
Pages are made for an API like the Coven starter's. If yours differs, `src/api/` is where to change what's sent and what's expected.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Signing in, and its kin, from the API (the Coven starter's routes under /api) — its calls:
|
|
3
|
+
* signIn the user, signed in (422 on `email` for wrong credentials, or too many tries)
|
|
4
|
+
* register the user, signed in; a link to confirm their email is mailed
|
|
5
|
+
* signOut the session ended
|
|
6
|
+
* me the signed-in user, or null for no one
|
|
7
|
+
* requestReset asks for a password reset link; the API says the same whether or not the email has an account (204)
|
|
8
|
+
* resetPassword a new password, from the reset link's token and email
|
|
9
|
+
* verifyEmail confirms an email from its signed link
|
|
10
|
+
* resendVerification
|
|
11
|
+
* mails the signed-in user their link again
|
|
12
|
+
* The API answers in its own words (`pending_email`): userOf() makes that the app's User, and the fields' errors are given the form's names (`password_confirmation` is `confirm`).
|
|
13
|
+
*/
|
|
14
|
+
import ApiError from "@/api/ApiError";
|
|
15
|
+
import { request } from "@/api/client";
|
|
16
|
+
import type { Membership, Registration, Role, User } from "@/api/types";
|
|
17
|
+
|
|
18
|
+
// What a confirmation link carries, which the API signed.
|
|
19
|
+
export interface VerificationLink {
|
|
20
|
+
id: string;
|
|
21
|
+
hash: string;
|
|
22
|
+
expires: string;
|
|
23
|
+
signature: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function signIn(email: string, password: string): Promise<User> {
|
|
27
|
+
return userOf(await call(() => request("POST", "/login", { email, password })));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function register(registration: Registration): Promise<User> {
|
|
31
|
+
// From an invitation, the account joins its organisation: it isn't given one of its own.
|
|
32
|
+
const own = registration.invitation ? { invitation: registration.invitation } : { organisation: registration.organisation };
|
|
33
|
+
|
|
34
|
+
return userOf(await call(() => request("POST", "/register", {
|
|
35
|
+
name: registration.name,
|
|
36
|
+
email: registration.email,
|
|
37
|
+
...own,
|
|
38
|
+
password: registration.password,
|
|
39
|
+
password_confirmation: registration.passwordConfirmation,
|
|
40
|
+
})));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function signOut(): Promise<void> {
|
|
44
|
+
await request("POST", "/logout");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The signed-in user, or null when the API says no one is (401).
|
|
48
|
+
export async function me(): Promise<User | null> {
|
|
49
|
+
try {
|
|
50
|
+
return userOf(await request("GET", "/user"));
|
|
51
|
+
} catch(error) {
|
|
52
|
+
if(error instanceof ApiError && error.status == 401)
|
|
53
|
+
return null;
|
|
54
|
+
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function requestReset(email: string): Promise<void> {
|
|
60
|
+
await request("POST", "/forgot-password", { email });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function resetPassword(reset: { token: string; email: string; password: string; confirmation: string }): Promise<void> {
|
|
64
|
+
const { token, email, password, confirmation } = reset;
|
|
65
|
+
|
|
66
|
+
await call(() => request("POST", "/reset-password", { token, email, password, password_confirmation: confirmation }));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function verifyEmail(link: VerificationLink): Promise<void> {
|
|
70
|
+
const query = new URLSearchParams({ expires: link.expires, signature: link.signature });
|
|
71
|
+
|
|
72
|
+
await request("POST", `/verify-email/${encodeURIComponent(link.id)}/${encodeURIComponent(link.hash)}?${query}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function resendVerification(): Promise<void> {
|
|
76
|
+
await request("POST", "/email/verification-notification");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Runs a request, its fields' errors given the form's names.
|
|
80
|
+
async function call(run: () => Promise<unknown>): Promise<unknown> {
|
|
81
|
+
try {
|
|
82
|
+
return await run();
|
|
83
|
+
} catch(error) {
|
|
84
|
+
if(error instanceof ApiError && error.field == "organisation")
|
|
85
|
+
throw new ApiError(error.message, "organisation", error.status);
|
|
86
|
+
|
|
87
|
+
if(error instanceof ApiError && error.field == "password_confirmation")
|
|
88
|
+
throw new ApiError(error.message, "confirm", error.status);
|
|
89
|
+
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// The API's user as the app's User; an answer that isn't one is an ApiError.
|
|
95
|
+
export function userOf(data: unknown): User {
|
|
96
|
+
const read = (name: string): unknown => typeof data == "object" && data !== null ? Reflect.get(data, name) : undefined;
|
|
97
|
+
const id = read("id");
|
|
98
|
+
const name = read("name");
|
|
99
|
+
const email = read("email");
|
|
100
|
+
const verified = read("verified");
|
|
101
|
+
const pending = read("pending_email");
|
|
102
|
+
const current = read("current_organisation_id");
|
|
103
|
+
const organisations = read("organisations");
|
|
104
|
+
|
|
105
|
+
if(typeof id != "number" || typeof name != "string" || typeof email != "string" || typeof verified != "boolean" || (pending !== null && pending !== undefined && typeof pending != "string")
|
|
106
|
+
|| (current !== null && current !== undefined && typeof current != "number") || !Array.isArray(organisations))
|
|
107
|
+
throw new ApiError("The API answered with a user this app can't read.");
|
|
108
|
+
|
|
109
|
+
const list: readonly unknown[] = organisations;
|
|
110
|
+
|
|
111
|
+
return { id, name, email, verified, pendingEmail: pending ?? null, organisationId: current ?? null, organisations: list.map(membershipOf) };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function membershipOf(data: unknown): Membership {
|
|
115
|
+
const read = (name: string): unknown => typeof data == "object" && data !== null ? Reflect.get(data, name) : undefined;
|
|
116
|
+
const id = read("id");
|
|
117
|
+
const name = read("name");
|
|
118
|
+
const role = read("role");
|
|
119
|
+
|
|
120
|
+
if(typeof id != "number" || typeof name != "string" || (role !== "owner" && role !== "admin" && role !== "member"))
|
|
121
|
+
throw new ApiError("The API answered with an organisation this app can't read.");
|
|
122
|
+
|
|
123
|
+
return { id, name, role: role as Role };
|
|
124
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Members and invitations, from the API (coven-project's
|
|
3
|
+
* H26 and its members and invitations).
|
|
4
|
+
*
|
|
5
|
+
* What acts on an organisation has its id in the path
|
|
6
|
+
* (`/organisations/{id}/…`), so each of these takes the id of the one the
|
|
7
|
+
* user is working in (`sessionStore.organisation.id`). The API names members
|
|
8
|
+
* by their user's id and invitations by their own; an invitation's token is
|
|
9
|
+
* only in the link mailed to the invited, which is what the calls at the end
|
|
10
|
+
* take:
|
|
11
|
+
* members everyone in the organisation, and the invitations
|
|
12
|
+
* waiting (two requests), for its owner and admins
|
|
13
|
+
* changeRole, removeMember, invite, resendInvitation, revokeInvitation
|
|
14
|
+
* a change, then the list as it now is
|
|
15
|
+
* transferOwnership the owner hands it to an admin; the user, as the
|
|
16
|
+
* API has them now (their role is admin)
|
|
17
|
+
* leaveOrganisation the user, no longer in it, working in another
|
|
18
|
+
* invitation an invitation by its token, for anyone with the link
|
|
19
|
+
* acceptInvitation the user, with the organisation joined and worked in
|
|
20
|
+
* declineInvitation the invitation turned down
|
|
21
|
+
* userInvitations, acceptUserInvitation, declineUserInvitation
|
|
22
|
+
* the invitations to the signed-in user's own email,
|
|
23
|
+
* by id, for the page for someone in no organisation
|
|
24
|
+
* : the API keeps only a hash of each token, so
|
|
25
|
+
* what names one there is its id, and it's theirs by
|
|
26
|
+
* their email alone
|
|
27
|
+
* A refusal is an ApiError in the API's words: 403 for what the user's role
|
|
28
|
+
* doesn't allow, 404 for an organisation they're not in, 410 for an
|
|
29
|
+
* invitation that has expired.
|
|
30
|
+
*/
|
|
31
|
+
import { userOf } from "@/api/auth";
|
|
32
|
+
import { request } from "@/api/client";
|
|
33
|
+
import ApiError from "@/api/ApiError";
|
|
34
|
+
import type { Role, User } from "@/api/types";
|
|
35
|
+
|
|
36
|
+
// Whoever sent an invitation may have deleted their account since.
|
|
37
|
+
const SOMEONE_GONE = "someone who has since left";
|
|
38
|
+
|
|
39
|
+
// Someone in the organisation: `you` is the signed-in user, and `id` their user's.
|
|
40
|
+
export interface Member {
|
|
41
|
+
id: number;
|
|
42
|
+
email: string;
|
|
43
|
+
name: string;
|
|
44
|
+
role: Role;
|
|
45
|
+
you: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// An invitation waiting: to an email, with a role, from someone, on a day; it expires 7 days later.
|
|
49
|
+
export interface Invitation {
|
|
50
|
+
id: number;
|
|
51
|
+
email: string;
|
|
52
|
+
role: Role;
|
|
53
|
+
invitedBy: string;
|
|
54
|
+
sentAt: string;
|
|
55
|
+
expiresAt: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Settings › Members: everyone, and the invitations waiting.
|
|
59
|
+
export interface MemberList {
|
|
60
|
+
members: readonly Member[];
|
|
61
|
+
invitations: readonly Invitation[];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface InvitationInput {
|
|
65
|
+
email: string;
|
|
66
|
+
role: Role;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// An invitation as /invite?token=… shows it, to anyone with the link.
|
|
70
|
+
export interface InvitationDetails {
|
|
71
|
+
email: string;
|
|
72
|
+
role: Role;
|
|
73
|
+
organisation: string;
|
|
74
|
+
invitedBy: string;
|
|
75
|
+
expired: boolean;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function members(organisationId: number): Promise<MemberList> {
|
|
79
|
+
const [people, invited] = await Promise.all([
|
|
80
|
+
request("GET", `${path(organisationId)}/members`),
|
|
81
|
+
request("GET", `${path(organisationId)}/invitations`),
|
|
82
|
+
]);
|
|
83
|
+
|
|
84
|
+
return { members: list(people).map(memberOf), invitations: list(invited).map(invitationOf) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// A member's new role: never the owner's (that's transferring ownership), nor your own; an admin
|
|
88
|
+
// doesn't change another admin's.
|
|
89
|
+
export async function changeRole(organisationId: number, memberId: number, role: Role): Promise<MemberList> {
|
|
90
|
+
await request("PATCH", `${path(organisationId)}/members/${memberId}`, { role });
|
|
91
|
+
|
|
92
|
+
return members(organisationId);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Takes someone out of the organisation, on the same terms as changing their role. What they
|
|
96
|
+
// recorded stays, with their name.
|
|
97
|
+
export async function removeMember(organisationId: number, memberId: number): Promise<MemberList> {
|
|
98
|
+
await request("DELETE", `${path(organisationId)}/members/${memberId}`);
|
|
99
|
+
|
|
100
|
+
return members(organisationId);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The owner hands ownership to an admin, and becomes an admin.
|
|
104
|
+
export async function transferOwnership(organisationId: number, memberId: number): Promise<User> {
|
|
105
|
+
return userOf(await request("POST", `${path(organisationId)}/members/${memberId}/ownership`));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Leaves an organisation: anyone but its owner, who'd transfer ownership first. The user is working in
|
|
109
|
+
// another one afterwards.
|
|
110
|
+
export async function leaveOrganisation(organisationId: number): Promise<User> {
|
|
111
|
+
return userOf(await request("DELETE", `${path(organisationId)}/membership`));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Invites an email with a role: not someone who's in already, or invited already (422 on `email`).
|
|
115
|
+
export async function invite(organisationId: number, input: InvitationInput): Promise<MemberList> {
|
|
116
|
+
await request("POST", `${path(organisationId)}/invitations`, { email: input.email, role: input.role });
|
|
117
|
+
|
|
118
|
+
return members(organisationId);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Sends an invitation again, for another 7 days; the link it went with before stops working.
|
|
122
|
+
export async function resendInvitation(organisationId: number, invitationId: number): Promise<MemberList> {
|
|
123
|
+
await request("POST", `${path(organisationId)}/invitations/${invitationId}/resend`);
|
|
124
|
+
|
|
125
|
+
return members(organisationId);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function revokeInvitation(organisationId: number, invitationId: number): Promise<MemberList> {
|
|
129
|
+
await request("DELETE", `${path(organisationId)}/invitations/${invitationId}`);
|
|
130
|
+
|
|
131
|
+
return members(organisationId);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// An invitation by its token, for anyone with the link (404 for one that isn't, or isn't any more).
|
|
135
|
+
export async function invitation(token: string): Promise<InvitationDetails> {
|
|
136
|
+
const data = await request("GET", `/invitations/${encodeURIComponent(token)}`);
|
|
137
|
+
const email = read(data, "email");
|
|
138
|
+
const role = read(data, "role");
|
|
139
|
+
const organisation = read(data, "organisation");
|
|
140
|
+
const invitedBy = read(data, "invited_by");
|
|
141
|
+
const expired = read(data, "expired");
|
|
142
|
+
|
|
143
|
+
if(typeof email != "string" || !isRole(role) || typeof organisation != "string" || typeof expired != "boolean")
|
|
144
|
+
throw new ApiError("The API answered with an invitation the app can't read.");
|
|
145
|
+
|
|
146
|
+
return { email, role, organisation, invitedBy: typeof invitedBy == "string" ? invitedBy : SOMEONE_GONE, expired };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Accepts an invitation: signed in, with its email. Its organisation joins the account, with its
|
|
150
|
+
// role, and becomes the one you work in.
|
|
151
|
+
export async function acceptInvitation(token: string): Promise<User> {
|
|
152
|
+
return userOf(await request("POST", `/invitations/${encodeURIComponent(token)}/accept`));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function declineInvitation(token: string): Promise<void> {
|
|
156
|
+
await request("POST", `/invitations/${encodeURIComponent(token)}/decline`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// An invitation to the signed-in user, as the page for someone in no organisation lists it: which organisation,
|
|
160
|
+
// as what, from whom, until when — expired ones too, saying so.
|
|
161
|
+
export interface UserInvitation {
|
|
162
|
+
id: number;
|
|
163
|
+
organisation: string;
|
|
164
|
+
role: Role;
|
|
165
|
+
invitedBy: string;
|
|
166
|
+
sentAt: string;
|
|
167
|
+
expiresAt: string;
|
|
168
|
+
expired: boolean;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export async function userInvitations(): Promise<readonly UserInvitation[]> {
|
|
172
|
+
return list(await request("GET", "/user/invitations")).map(userInvitationOf);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Accepts one by its id: the user, with its organisation joined and worked in (410 if it has expired).
|
|
176
|
+
export async function acceptUserInvitation(id: number): Promise<User> {
|
|
177
|
+
return userOf(await request("POST", `/user/invitations/${id}/accept`));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function declineUserInvitation(id: number): Promise<void> {
|
|
181
|
+
await request("POST", `/user/invitations/${id}/decline`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function userInvitationOf(data: unknown): UserInvitation {
|
|
185
|
+
const id = read(data, "id");
|
|
186
|
+
const organisation = read(data, "organisation");
|
|
187
|
+
const role = read(data, "role");
|
|
188
|
+
const invitedBy = read(data, "invited_by");
|
|
189
|
+
const sentAt = read(data, "sent_at");
|
|
190
|
+
const expiresAt = read(data, "expires_at");
|
|
191
|
+
const expired = read(data, "expired");
|
|
192
|
+
|
|
193
|
+
if(typeof id != "number" || typeof organisation != "string" || !isRole(role) || typeof sentAt != "string" || typeof expiresAt != "string" || typeof expired != "boolean")
|
|
194
|
+
throw new ApiError("The API answered with an invitation the app can't read.");
|
|
195
|
+
|
|
196
|
+
return { id, organisation, role, invitedBy: typeof invitedBy == "string" ? invitedBy : SOMEONE_GONE, sentAt, expiresAt, expired };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function path(organisationId: number) {
|
|
200
|
+
return `/organisations/${organisationId}`;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function memberOf(data: unknown): Member {
|
|
204
|
+
const id = read(data, "id");
|
|
205
|
+
const name = read(data, "name");
|
|
206
|
+
const email = read(data, "email");
|
|
207
|
+
const role = read(data, "role");
|
|
208
|
+
const you = read(data, "you");
|
|
209
|
+
|
|
210
|
+
if(typeof id != "number" || typeof name != "string" || typeof email != "string" || !isRole(role) || typeof you != "boolean")
|
|
211
|
+
throw new ApiError("The API answered with a member the app can't read.");
|
|
212
|
+
|
|
213
|
+
return { id, name, email, role, you };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function invitationOf(data: unknown): Invitation {
|
|
217
|
+
const id = read(data, "id");
|
|
218
|
+
const email = read(data, "email");
|
|
219
|
+
const role = read(data, "role");
|
|
220
|
+
const invitedBy = read(data, "invited_by");
|
|
221
|
+
const sentAt = read(data, "sent_at");
|
|
222
|
+
const expiresAt = read(data, "expires_at");
|
|
223
|
+
|
|
224
|
+
if(typeof id != "number" || typeof email != "string" || !isRole(role) || typeof sentAt != "string" || typeof expiresAt != "string")
|
|
225
|
+
throw new ApiError("The API answered with an invitation the app can't read.");
|
|
226
|
+
|
|
227
|
+
return { id, email, role, invitedBy: typeof invitedBy == "string" ? invitedBy : SOMEONE_GONE, sentAt, expiresAt };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function list(data: unknown): readonly unknown[] {
|
|
231
|
+
if(!Array.isArray(data))
|
|
232
|
+
throw new ApiError("The API answered with a list the app can't read.");
|
|
233
|
+
|
|
234
|
+
return data;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function isRole(value: unknown): value is Role {
|
|
238
|
+
return value == "owner" || value == "admin" || value == "member";
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function read(data: unknown, name: string): unknown {
|
|
242
|
+
return typeof data == "object" && data !== null ? Reflect.get(data, name) : undefined;
|
|
243
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* What the app has told the signed-in user, from the API (coven-project's NotificationController): theirs wherever they
|
|
3
|
+
* work, so these aren't about an organisation and take no id.
|
|
4
|
+
* notifications a page of them, newest first — or only the unread — with how many there are in all and how many are unread
|
|
5
|
+
* unreadCount how many are unread: a page of one, for the bell
|
|
6
|
+
* markRead, markAllRead, remove
|
|
7
|
+
* one read, all read, one deleted
|
|
8
|
+
* A notification's words are the `message` of its data; one without any, whatever the app may add later, is shown by what it was.
|
|
9
|
+
*/
|
|
10
|
+
import { request } from "@/api/client";
|
|
11
|
+
import { readNames } from "@/api/scope";
|
|
12
|
+
import type { AppNotification, NotificationPage } from "@/api/types";
|
|
13
|
+
|
|
14
|
+
export async function notifications(options: { page?: number; perPage?: number; unread?: boolean } = {}): Promise<NotificationPage> {
|
|
15
|
+
const asked = new URLSearchParams();
|
|
16
|
+
|
|
17
|
+
if(options.page && options.page > 1)
|
|
18
|
+
asked.set("page", String(options.page));
|
|
19
|
+
|
|
20
|
+
if(options.perPage)
|
|
21
|
+
asked.set("per_page", String(options.perPage));
|
|
22
|
+
|
|
23
|
+
if(options.unread)
|
|
24
|
+
asked.set("unread", "1");
|
|
25
|
+
|
|
26
|
+
const read = readNames(await request("GET", `/user/notifications${asked.size ? `?${asked}` : ""}`));
|
|
27
|
+
|
|
28
|
+
if(typeof read != "object" || read === null || !("notifications" in read) || !Array.isArray(read.notifications))
|
|
29
|
+
throw new Error("The server's answer about notifications isn't one.");
|
|
30
|
+
|
|
31
|
+
const { notifications: items, total, unread, page, pageSize } = read as { notifications: readonly Record<string, unknown>[]; total: number; unread: number; page: number; pageSize: number };
|
|
32
|
+
|
|
33
|
+
return { notifications: items.map(notificationOf), total, unread, page, pageSize };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function unreadCount(): Promise<number> {
|
|
37
|
+
return (await notifications({ perPage: 1 })).unread;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function markRead(id: string): Promise<void> {
|
|
41
|
+
await request("POST", `/user/notifications/${id}/read`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function markAllRead(): Promise<void> {
|
|
45
|
+
await request("POST", "/user/notifications/read");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function remove(id: string): Promise<void> {
|
|
49
|
+
await request("DELETE", `/user/notifications/${id}`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function notificationOf(item: Record<string, unknown>): AppNotification {
|
|
53
|
+
const data = typeof item.data == "object" && item.data !== null ? item.data as Record<string, unknown> : {};
|
|
54
|
+
const type = String(item.type ?? "");
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
id: String(item.id ?? ""),
|
|
58
|
+
type,
|
|
59
|
+
message: typeof data.message == "string" && data.message ? data.message : type.replace(/([a-z])([A-Z])/g, "$1 $2"),
|
|
60
|
+
readAt: typeof item.readAt == "string" ? item.readAt : null,
|
|
61
|
+
createdAt: String(item.createdAt ?? ""),
|
|
62
|
+
};
|
|
63
|
+
}
|