103 Commits
Author SHA1 Message Date
lil-koneko afad275408 Merge pull request 'Release v0.5.0' (#43) from release/v0.5.0 into production
Reviewed-on: iriks-it/laravel-manager#43
2026-12-04 08:53:09 +00:00
deploy-bot 2063f52698 Merge pull request 'Patch-release voor de nachtelijke renovate-update' (#46) from feature/renovate-patch-release into release/v0.5.0 2026-12-04 08:50:23 +00:00
Matthijs Iriks 45f4ed2660 Make a patch release of a merged renovate pull request 2026-12-04 09:49:11 +01:00
deploy-bot fc51dd5bdb Merge pull request 'Niets meer wekelijks: nachtelijke scan en updates, Trivy na een release' (#45) from feature/nightly-not-weekly into release/v0.5.0 2026-12-04 08:42:57 +00:00
Matthijs Iriks a5e640b31b Nothing runs weekly: nightly scan and updates from the homelab, Trivy after a release 2026-12-04 09:41:19 +01:00
deploy-bot 3e8a73d3da Merge pull request 'Trivy uit de PR-jobs, composer audit blijft' (#44) from feature/trivy-off-the-runners into release/v0.5.0 2026-12-04 08:07:21 +00:00
Matthijs Iriks bb1f4e1292 Take Trivy out of the PR jobs; composer audit stays, Trivy runs from the homelab 2026-12-04 09:04:10 +01:00
deploy-bot 41d82a969a Merge pull request 'A doctor check for shared names, and the docs of 0.5.0' (#42) from feature/v0.5.0-finish into release/v0.5.0 2026-12-04 04:43:12 +00:00
Matthijs Iriks 541d1ee690 Check for names the site already uses, and bring the docs up to 0.5.0 2026-12-04 05:42:12 +01:00
deploy-bot a921f14d85 Merge pull request 'Roles of the host next to the groups' (#41) from feature/permission-sources into release/v0.5.0 2026-12-04 04:41:03 +00:00
Matthijs Iriks 69ed8c742a Let the roles of the host decide next to the groups 2026-12-04 05:40:02 +01:00
deploy-bot 258c25efe1 Merge pull request 'Checks on the login, with Cloudflare Turnstile' (#40) from feature/login-hooks into release/v0.5.0 2026-12-04 04:39:01 +00:00
Matthijs Iriks a378fdf345 Add checks on the login, with Turnstile built in 2026-12-04 05:38:00 +01:00
deploy-bot 96e3fead0a Merge pull request 'The counting script and a component for the public pages' (#39) from feature/pulse-script into release/v0.5.0 2026-12-04 04:36:28 +00:00
Matthijs Iriks 5c0a94f167 Add the pulse script and the component for the public pages 2026-12-04 05:35:30 +01:00
deploy-bot 1e002ed0c5 Merge pull request 'Editor: toolbar, photos, preview and a focus point' (#38) from feature/editor into release/v0.5.0 2026-12-04 04:34:25 +00:00
Matthijs Iriks 6a51b0e649 Add the editor: toolbar, photos in the text, a server preview and a focus point 2026-12-04 05:33:26 +01:00
deploy-bot 6b41bfddd3 Merge pull request 'History of posts and pages, with restore' (#37) from feature/revisions into release/v0.5.0 2026-12-04 04:30:36 +00:00
Matthijs Iriks 6fdb02040b Add a history of posts and pages with restore 2026-12-04 05:29:34 +01:00
deploy-bot eb37a7c6fb Merge pull request 'Resources from config and screens of the site's own' (#36) from feature/resources into release/v0.5.0 2026-12-04 04:27:36 +00:00
Matthijs Iriks 3345797141 Add resources defined in config and a bundle of the site's own screens 2026-12-04 05:26:37 +01:00
deploy-bot 37a29d9195 Merge pull request 'Pages with fields, a shared field schema and the screens' (#35) from feature/pages into release/v0.5.0 2026-12-04 04:21:18 +00:00
Matthijs Iriks 517039b625 Add pages with fields, a field schema and the screens to edit them 2026-12-04 05:20:18 +01:00
deploy-bot ce1a8a1370 Merge pull request 'Menu sections, icons and order, and a simple view' (#34) from feature/menu into release/v0.5.0 2026-12-04 04:17:49 +00:00
Matthijs Iriks c7d0971813 Run the checks again 2026-12-04 05:16:52 +01:00
Matthijs Iriks 6f31a54818 Add menu sections, icons and order, and the simple view 2026-12-04 05:16:06 +01:00
deploy-bot 362a5bce2e Merge pull request 'Translatable server texts and a Dutch language file' (#33) from feature/translations into release/v0.5.0 2026-12-04 04:12:52 +00:00
Matthijs Iriks e39ca4ba0a Run the checks again 2026-12-04 05:11:55 +01:00
Matthijs Iriks a34965d4b7 Make the texts of the server translatable, with a Dutch file 2026-12-04 05:10:50 +01:00
deploy-bot 56de8ee76a Merge pull request 'Route names and tables that can move, and manager:import' (#32) from feature/configurable-names into release/v0.5.0 2026-12-04 04:09:12 +00:00
Matthijs Iriks 60ad85a621 Let route names and tables move, and add manager:import 2026-12-04 05:08:08 +01:00
deploy-bot 984024eb85 Merge pull request 'Bring v0.4.1 into v0.5.0' (#31) from feature/bring-in-v0.4.1 into release/v0.5.0 2026-12-04 04:05:52 +00:00
deploy-bot c49c1e3909 Merge pull request 'Hold TypeScript at 5 in the weekly npm update' (#30) from fix/hold-typescript into release/v0.4.1 2026-12-04 03:46:00 +00:00
deploy-bot 60f836088b Merge pull request 'Update the dependencies of the screens: typescript, vite' (#29) from renovate/ui-deps-20261204 into release/v0.4.1 2026-12-04 03:45:45 +00:00
Matthijs Iriks b23b0c1c53 Hold TypeScript at 5 in the weekly npm update 2026-12-04 04:44:59 +01:00
Matthijs Iriks f2dad190c0 Keep TypeScript at 5: vue-tsc does not work with TypeScript 7 yet 2026-12-04 04:44:46 +01:00
deploy-bot ef9a83496c Update the dependencies of the screens: typescript, vite 2026-12-04 03:44:04 +00:00
deploy-bot c05950c0e3 Merge pull request 'Weekly updates for the npm packages of the screens' (#28) from feature/ui-dependency-updates into release/v0.4.1 2026-12-04 03:38:24 +00:00
Matthijs Iriks 6df410c37b Fix the token row 2026-12-04 04:37:24 +01:00
Matthijs Iriks a25a421028 Update the npm packages of the screens in the weekly dependency workflow 2026-12-04 04:37:15 +01:00
lil-koneko 8bc583bd19 Merge pull request 'Release v0.4.0' (#27) from release/v0.4.0 into production
Reviewed-on: iriks-it/laravel-manager#27
2026-12-04 03:27:18 +00:00
deploy-bot 65f6ac91ac Merge pull request 'Changelog for v0.4.0' (#26) from feature/changelog-v0.4.0 into release/v0.4.0 2026-12-04 03:21:32 +00:00
Matthijs Iriks 548bb66d0e Run the checks again 2026-12-04 04:20:37 +01:00
Matthijs Iriks 775f8ef789 Fix the token row of the changelog change 2026-12-04 04:13:31 +01:00
Matthijs Iriks e593274b19 Changelog for v0.4.0 2026-12-04 04:13:24 +01:00
deploy-bot 9a98f633ab Merge pull request 'Fix the integration guide and installer after a fresh-agent test' (#25) from feature/ai-guide-fixes into release/v0.4.0 2026-12-04 03:11:27 +00:00
Matthijs Iriks 441d76ef96 Fix the integration guide and installer after a test with a fresh agent 2026-12-04 04:10:25 +01:00
deploy-bot 9ff162460d Merge pull request 'Screens for media, the audit log and statistics' (#24) from feature/screens-media into release/v0.4.0 2026-12-04 03:08:00 +00:00
Matthijs Iriks 4934d18f2a Record tokens for the media, audit and statistics screens 2026-12-04 04:06:53 +01:00
Matthijs Iriks 1c9ccadf4e Add screens for media, the audit log and statistics 2026-12-04 04:06:39 +01:00
deploy-bot 0caa196908 Merge pull request 'Screens for accounts, groups, labels, pages and reviews' (#23) from feature/screens-users-labels-pages into release/v0.4.0 2026-12-04 03:04:10 +00:00
Matthijs Iriks d14de1d44d Add screens for accounts, groups, categories and tags, pages and reviews 2026-12-04 04:03:07 +01:00
deploy-bot 6993ad3557 Merge pull request 'Built-in screens with per-user and site themes' (#22) from feature/frontend-shell into release/v0.4.0 2026-12-04 02:59:35 +00:00
Matthijs Iriks 351667abaf Add built-in screens (login, profile, menu, posts), per-user and site themes 2026-12-04 03:58:19 +01:00
deploy-bot 4bf0a8bbb0 Merge pull request 'Install and health check commands for AI agents' (#21) from feature/ai-integration into release/v0.4.0 2026-12-04 02:45:28 +00:00
Matthijs Iriks 6f4d9b44f2 Add manager:install, manager:doctor and an integration guide for AI agents 2026-12-04 03:44:10 +01:00
lil-koneko ebb5063ed1 Merge pull request 'Release v0.3.0' (#20) from release/v0.3.0 into production
Reviewed-on: iriks-it/laravel-manager#20
2026-12-04 02:21:40 +00:00
deploy-bot a8055c69f8 Merge pull request 'Packagist-stap meldt het pakket zelf aan' (#19) from feature/packagist-create into release/v0.3.0 2026-12-04 02:19:17 +00:00
Matthijs Iriks e0299bf77b Packagist step submits the package when Packagist does not know it 2026-12-04 03:18:21 +01:00
lil-koneko f7cbd6c621 Merge pull request 'Release v0.2.0' (#15) from release/v0.2.0 into production
Reviewed-on: iriks-it/laravel-manager#15
2026-12-04 02:13:35 +00:00
deploy-bot e570b849f2 Merge pull request 'docs: de centrale scans lopen elke nacht' (#18) from fix/central-scans-wording into release/v0.2.0 2026-12-04 02:12:18 +00:00
Matthijs Iriks 81ea30f038 docs: the central Trivy and Renovate run nightly over this repo too 2026-12-04 03:11:22 +01:00
deploy-bot cebb66b7d6 Merge pull request 'Wekelijkse update van versiebereiken (Renovate-vervanger)' (#17) from feature/dependency-updates into release/v0.2.0 2026-12-04 02:00:20 +00:00
Matthijs Iriks 2f6789147e Weekly workflow that widens dependency constraints 2026-12-04 02:59:20 +01:00
deploy-bot 3d6b92497c Merge pull request 'Hermes-tokenscript met een rij per model' (#16) from feature/hermes-token-script into release/v0.2.0 2026-12-04 01:56:30 +00:00
Matthijs Iriks 556dfce585 Hermes token script, with a row per model like the main script 2026-12-04 02:55:35 +01:00
deploy-bot f0cb58d7e5 Merge pull request 'Statistics module: bezoekersstatistieken zonder cookies' (#14) from feature/statistics into release/v0.2.0 2026-12-04 01:48:07 +00:00
Matthijs Iriks 4e77e4b427 Merge release/v0.2.0 into feature/statistics 2026-12-04 02:47:20 +01:00
Matthijs Iriks 7482ee489b Statistics module: visitor statistics without cookies 2026-12-04 02:37:08 +01:00
deploy-bot 2c00fa8f07 Merge pull request 'Token-script telt de adviseur als eigen rij mee' (#13) from fix/token-usage-advisor into release/v0.2.0 2026-12-04 01:36:07 +00:00
Matthijs Iriks 594e69c0cf Token script: count advisor calls as their own row per model 2026-12-04 02:35:10 +01:00
deploy-bot acb8620621 Merge pull request 'Audit module: auditlog en banbeheer' (#12) from feature/audit-and-bans into release/v0.2.0 2026-12-04 01:33:30 +00:00
Matthijs Iriks d2ea1bacac Audit module: audit log and address bans 2026-12-04 02:32:22 +01:00
deploy-bot b75403e5ea Merge pull request 'CI: composer-cache en herhaalpogingen in alle jobs' (#11) from feature/ci-cache-and-retry into release/v0.2.0 2026-12-04 01:21:32 +00:00
Matthijs Iriks b863f9a346 CI: composer-cache en herhaalpogingen in alle jobs 2026-12-04 02:20:25 +01:00
lil-koneko 2539dfcc3e Merge pull request 'Release v0.1.0' (#9) from release/v0.1.0 into production
Reviewed-on: iriks-it/laravel-manager#9
2026-12-04 01:07:49 +00:00
deploy-bot 98d12db241 Merge pull request 'Changelog-kop van v0.1.0 herstellen' (#10) from fix/changelog-heading into release/v0.1.0 2026-12-04 01:04:46 +00:00
Matthijs Iriks 498ffd4462 Fix the changelog heading of v0.1.0 2026-12-04 02:01:01 +01:00
deploy-bot 5a0b53025b Merge pull request 'Changelog voor v0.1.0' (#8) from feature/changelog-v0.1.0 into release/v0.1.0 2026-12-04 00:58:19 +00:00
Matthijs Iriks da5bace656 TOKENS: row with real numbers 2026-12-04 01:57:29 +01:00
Matthijs Iriks 5c0eec9477 Changelog for v0.1.0 2026-12-04 01:57:22 +01:00
deploy-bot 22cbe043f1 Merge pull request 'LICENSE toevoegen' (#7) from feature/license into release/v0.1.0 2026-12-04 00:57:06 +00:00
Matthijs Iriks a0d7840158 TOKENS: row with real numbers 2026-12-04 01:56:16 +01:00
Matthijs Iriks 16fdfc887c Add the MIT license file 2026-12-04 01:56:05 +01:00
lil-koneko 02f0ec5149 Merge pull request 'Checkout zonder git repareren en oude branches opruimen' (#6) from fix/checkout-without-git into develop
Reviewed-on: iriks-it/laravel-manager#6
2026-12-04 00:54:35 +00:00
Matthijs Iriks eb93e890d6 Fix checkout in jobs without git (export-ignore); prune quiet feature branches after 30 days 2026-12-04 01:53:20 +01:00
lil-koneko 86ecde31ea Merge pull request 'CI en releasecyclus' (#5) from feature/ci-release-flow into develop
Reviewed-on: iriks-it/laravel-manager#5
2026-12-04 00:51:08 +00:00
Matthijs Iriks 476311544f README: what Composer installs 2026-12-04 01:49:01 +01:00
Matthijs Iriks fb0caac84e Keep repository-only files out of the Composer package (export-ignore) 2026-12-04 01:48:55 +01:00
Matthijs Iriks ee29c41363 Merge develop into feature/ci-release-flow 2026-12-04 01:46:08 +01:00
Matthijs Iriks 302a1c699d CI and release cycle: release branches, tag, Packagist, sync, tests, audit, Trivy 2026-12-04 01:45:44 +01:00
lil-koneko 7a979bb081 Merge pull request 'Posts in develop brengen' (#4) from feature/users-and-media into develop
Reviewed-on: iriks-it/laravel-manager#4
2026-12-04 00:42:02 +00:00
Matthijs Iriks f34e3d312e Merge develop into feature/users-and-media 2026-12-04 01:40:26 +01:00
lil-koneko f74ab3a94b Merge pull request 'Token-script: helper-agents meetellen' (#3) from fix/token-usage-helper-agents into develop
Reviewed-on: iriks-it/laravel-manager#3
2026-12-04 00:38:18 +00:00
Matthijs Iriks 2768234739 Token script: count helper agents in the row, one row per model 2026-12-04 01:37:13 +01:00
lil-koneko bf8201059f Merge pull request 'Posts overzetten' (#2) from feature/posts into feature/users-and-media
Reviewed-on: iriks-it/laravel-manager#2
2026-12-04 00:35:58 +00:00
lil-koneko 7105cfc239 Merge pull request 'Gebruikers en media overzetten' (#1) from feature/users-and-media into develop
Reviewed-on: iriks-it/laravel-manager#1
2026-12-04 00:35:51 +00:00
Matthijs Iriks e093614169 Posts module: posts, drafts and scheduling, categories and tags 2026-12-04 01:33:59 +01:00
Matthijs Iriks a9a1625241 Style fix 2026-12-04 01:27:13 +01:00
Matthijs Iriks 9f2a21fa1f Media module, users hardening, README and token ledger 2026-12-04 01:27:04 +01:00
Matthijs Iriks f86f5aea28 Users module: accounts, groups, permissions with needs, manager:create-user 2026-12-04 01:25:29 +01:00
Matthijs Iriks 08289db744 Eerste opzet: modulair beheer met aan/uit-schakelaars per onderdeel 2026-12-04 01:18:23 +01:00
Matthijs Iriks 936c794597 First setup: module registry, switchable modules, permissions 2026-12-04 01:18:14 +01:00
103 changed files with 8391 additions and 18 deletions

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
# Normalise line endings in the repository.
* text=auto eol=lf
# What stays in the repository but is not part of the package that Composer installs (Packagist builds
# the dist archive from `git archive`, which leaves these out).
# Because of that, every CI job that checks out must run in an image with git (webdevops/php has it):
# without git, actions/checkout downloads that same archive and the .gitea/ scripts are missing.
/.gitattributes export-ignore
/.gitea export-ignore
/.gitignore export-ignore
/dev export-ignore
/scripts export-ignore
/TOKENS.md export-ignore
/AGENTS.md export-ignore
/CLAUDE.md export-ignore
/tests export-ignore
/ui export-ignore
/phpunit.xml export-ignore
/pint.json export-ignore
+26
View File
@@ -0,0 +1,26 @@
## Vraag
<!-- Wat was de vraag of de opdracht? Eén of twee zinnen, in de woorden van wie het vroeg. -->
## Wat is er gedaan
<!-- Beknopte lijst: per punt één regel. -->
-
## Zo test je het
<!-- Een checklist die af te vinken is: waar klik je, wat moet je zien. -->
- [ ]
## Zelf getest
<!-- Wat is er al gecontroleerd, en hoe (tests, handmatig, op welke omgeving). Ook wat niet getest is. -->
-
## Tijd en tokens
<!-- De regel(s) uit TOKENS.md van deze PR: uren, tokens, model. -->
## Onderhoud
<!-- Is er onderhoud meegenomen (updates, opruimen, documentatie)? Anders: Niets. -->
## Met de hand te doen
<!-- Wat moet er na het mergen nog met de hand gebeuren (secrets, .env, instellingen)? Anders: Niets. -->
## Vervolgstappen
<!-- Wat ligt er nog, wat is bewust niet gedaan? Anders: Geen. -->
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Turns on auto-merge for a pull request to a release branch (`release/vX.Y.Z`).
Run by the `release-automerge` job whenever such a pull request is opened or updated. Gitea then
merges it by itself once the required check is green, so features flow into the release branch
without anyone pressing the button. A pull request to anything else is left alone: `production`
is merged by hand.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (a token that may edit pull requests),
PULL_REQUEST_NUMBER. Optional: AUTO_MERGE_PREFIX (default "release/"), MERGE_STYLE (default "merge").
Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.request
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
NUMBER = os.environ.get("PULL_REQUEST_NUMBER", "").lstrip("#")
PREFIX = os.environ.get("AUTO_MERGE_PREFIX") or "release/"
MERGE_STYLE = os.environ.get("MERGE_STYLE") or "merge"
ALREADY_ON = object()
def api(method, path, body=None):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
detail = e.read().decode()
# A second push runs this job again while auto-merge is still on: that is what was wanted.
if e.code == 409 and "already scheduled to auto merge" in detail:
return ALREADY_ON
sys.exit(f"Gitea API {method} {path} failed: {e.code} {detail}")
return json.loads(text) if text else None
def main():
if not (URL and OWNER and REPO and TOKEN and NUMBER.isdigit()):
sys.exit("GT_URL, GT_OWNER, GT_REPO, GT_TOKEN and PULL_REQUEST_NUMBER are required.")
pull = api("GET", f"pulls/{NUMBER}") or {}
base_ref = (pull.get("base") or {}).get("ref", "")
if not base_ref.startswith(PREFIX):
print(f"Pull request #{NUMBER} targets {base_ref}, not {PREFIX}*: left alone.")
return
if pull.get("state") != "open" or pull.get("merged"):
print(f"Pull request #{NUMBER} is not open: nothing to do.")
return
answer = api("POST", f"pulls/{NUMBER}/merge", {
"do": MERGE_STYLE,
"merge_when_checks_succeed": True,
"delete_branch_after_merge": False,
})
if answer is ALREADY_ON:
print(f"Auto-merge was already on for pull request #{NUMBER}.")
return
print(f"Auto-merge is on for pull request #{NUMBER}: it merges once the required check is green.")
if __name__ == "__main__":
main()
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""PR CI: does this pull request follow the development cycle?
develop -> feature/*, fix/*, ... -> release/vX.Y.Z -> production
(collects features) (release: tag + Packagist)
production -> develop (the sync after a release, by the pipeline)
Pull requests go to a release branch or to production, never to develop.
- to `release/vX.Y.Z`: the release must not be out yet (its version is above the latest tag),
and the pull request does not come from production, develop or another release branch.
- to `production`: only from `release/vX.Y.Z`, with a version above the latest tag, a section
for it in CHANGELOG.md, and no "version" in composer.json (Packagist reads the tag).
The one other way in is `renovate/*`: the nightly dependency update of the homelab (release.py makes a
patch release of it, unless a release branch is open).
Environment: BASE_REF, HEAD_REF. Run in a checkout with the tags (fetch-depth 0).
Standard library + git only.
"""
import json
import os
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
def tags():
result = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True)
return result.stdout.split()
def problems(base, head, existing_tags, changelog, composer):
found = []
newest = semver.latest(existing_tags)
if base == "production":
if head.startswith("renovate/"):
return []
version = semver.release_version(head)
if version is None:
return [f"A pull request to production comes from a branch named release/vX.Y.Z, not from {head or '?'}."]
found += above_latest(version, newest)
if changelog is None or semver.changelog_section(changelog, version) is None:
found.append(f"CHANGELOG.md has no section '## v{semver.text(version)}' for this release.")
if isinstance(composer, dict) and "version" in composer:
found.append("composer.json must not have a \"version\": Packagist takes the version from the tag.")
return found
if base.startswith("release/"):
version = semver.release_version(base)
if version is None:
return [f"{base} is not a release branch name: use release/vX.Y.Z."]
found += above_latest(version, newest, "That release is already out: start the next one.")
if head in ("production", "develop") or head.startswith("release/"):
found.append(f"A release branch takes features (feature/*, fix/*), not {head}.")
return found
return [f"Pull requests go to release/vX.Y.Z or to production, not to {base or '?'}: develop only takes the sync after a release."]
def above_latest(version, newest, hint="The version of a release must be above the latest tag."):
if newest is not None and version <= newest:
return [f"v{semver.text(version)} is not above the latest tag v{semver.text(newest)}. {hint}"]
return []
def main():
base = os.environ.get("BASE_REF", "").strip()
head = os.environ.get("HEAD_REF", "").strip()
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else None
try:
composer = json.load(open("composer.json", encoding="utf-8"))
except (OSError, ValueError):
composer = None
found = problems(base, head, tags(), changelog, composer)
for line in found:
print(f"::error::{line}")
if found:
return 1
print(f"{head} -> {base}: follows the development cycle.")
return 0
if __name__ == "__main__":
sys.exit(main())
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""PR CI: a pull request must add its row to TOKENS.md.
TOKENS.md holds one row per piece of work: the tokens of the AI model that
went into it and the hours that were worked on it. This check compares the
rows of the pull request with the rows on the branch it goes to, and fails
when the pull request brings no new row. The new rows are printed, so every
pull request shows in its log what it cost.
Exempt, because nobody worked on them: the release pull request of the
pipeline (release/*), the dependency updates (renovate/*), and a pull
request that only carries one long-lived branch into another (production
into staging, staging into production, develop).
Environment (set by the workflow):
BASE_REF the branch the pull request goes to
HEAD_REF the branch the pull request comes from
PR_AUTHOR who opened it
Standard library only.
"""
import os
import subprocess
import sys
LEDGER = "TOKENS.md"
EXEMPT_PREFIXES = ("release/", "renovate/")
EXEMPT_BRANCHES = ("production", "staging", "develop")
EXEMPT_AUTHORS = ("deploy-bot", "renovate-bot")
def rows(text):
"""The rows of the table: the lines that start with a date."""
return [line.strip() for line in text.splitlines() if line.startswith("| 20")]
def git(*args):
return subprocess.run(["git", *args], capture_output=True, text=True)
def main():
base = os.environ.get("BASE_REF", "").strip()
head = os.environ.get("HEAD_REF", "").strip()
author = os.environ.get("PR_AUTHOR", "").strip()
if head.startswith(EXEMPT_PREFIXES) or head in EXEMPT_BRANCHES or author in EXEMPT_AUTHORS:
print(f"No row needed: {head or 'this pull request'} by {author or 'unknown'} is not a piece of work.")
return 0
if not base:
print("BASE_REF is not set: cannot tell which branch this pull request goes to.")
return 1
if not os.path.exists(LEDGER):
print(f"{LEDGER} is missing. See AGENTS.md, 'Token usage and hours'.")
return 1
fetch = git("fetch", "--quiet", "--no-tags", "--depth=1", "origin", base)
if fetch.returncode != 0:
print(f"Could not fetch {base}: {fetch.stderr.strip()}")
return 1
shown = git("show", f"FETCH_HEAD:{LEDGER}")
before = set(rows(shown.stdout)) if shown.returncode == 0 else set()
with open(LEDGER, encoding="utf-8") as handle:
new = [row for row in rows(handle.read()) if row not in before]
if not new:
print(f"This pull request adds no row to {LEDGER}.")
print("Every pull request records what went into it: the tokens of the AI model and the hours.")
print("Add the row with dev/token-usage.py (see AGENTS.md, 'Token usage and hours') and push again.")
return 1
print(f"{len(new)} new row(s) in {LEDGER}:")
for row in new:
print(" " + row)
return 0
if __name__ == "__main__":
sys.exit(main())
+65
View File
@@ -0,0 +1,65 @@
"""Tells Packagist that the package has a new version, and submits the package when it is not there yet.
Packagist reads the tags of the repository; this asks it to do that now, instead of waiting for its
own poll. The first time Packagist answers 404 (it does not know the package): then the package is
submitted through the create-package API, and Packagist reads every tag that is already there.
While PACKAGIST_USERNAME and PACKAGIST_TOKEN are not set, this only says so and succeeds.
Environment: PACKAGIST_USERNAME, PACKAGIST_TOKEN (the API token of the Packagist account, a secret
of the repository), PACKAGE_URL (the public address of the repository).
The token goes in the request and never in the log. Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
USER = os.environ.get("PACKAGIST_USERNAME", "").strip()
TOKEN = os.environ.get("PACKAGIST_TOKEN", "").strip()
PACKAGE_URL = os.environ.get("PACKAGE_URL", "").strip()
def call(endpoint, user, token, url):
"""POST to the API of Packagist; returns the HTTP status. Raises HTTPError with the answer on a refusal."""
query = urllib.parse.urlencode({"username": user, "apiToken": token})
request = urllib.request.Request(
f"https://packagist.org/api/{endpoint}?{query}",
data=json.dumps({"repository": {"url": url}}).encode(),
method="POST",
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=30) as response:
return response.status
def notify(user, token, url):
"""Tells Packagist about the package; submits it first when Packagist does not know it. Returns what happened."""
try:
return f"Packagist answered {call('update-package', user, token, url)}: it will read the new tag."
except urllib.error.HTTPError as e:
# Never echo the request (it holds the token); the answer of Packagist says enough.
if e.code != 404:
sys.exit(f"Packagist refused: {e.code} {e.read().decode()[:300]}")
try:
return f"Packagist did not know the package: submitted it (answer {call('create-package', user, token, url)}). It reads every tag that is there."
except urllib.error.HTTPError as e:
sys.exit(f"Packagist did not know the package, and refused to submit it: {e.code} {e.read().decode()[:300]}")
def main():
if not (USER and TOKEN):
print("PACKAGIST_USERNAME / PACKAGIST_TOKEN are not set: Packagist was not told. "
"Set both as secrets of the repository.")
return
if not PACKAGE_URL.startswith("https://"):
sys.exit("PACKAGE_URL must be the public https address of the repository.")
print(notify(USER, TOKEN, PACKAGE_URL))
if __name__ == "__main__":
main()
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Removes feature branches that nobody has touched for 30 days.
A branch is removed when all of this is true:
- its name starts with one of PRUNE_PREFIXES (default `feature/,fix/`): production, develop and the
release branches are never touched;
- its last commit is older than PRUNE_DAYS (default 30);
- no pull request from it is open (an open pull request is work in progress, however quiet).
A branch that had a pull request can be brought back from that pull request in Gitea ("Restore branch"),
and a merged one is in its target anyway. DRY_RUN=1 only says what would be removed.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may delete branches), and optionally PRUNE_DAYS,
PRUNE_PREFIXES, DRY_RUN. Standard library only.
"""
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
DAYS = int(os.environ.get("PRUNE_DAYS") or 30)
PREFIXES = tuple(p.strip() for p in (os.environ.get("PRUNE_PREFIXES") or "feature/,fix/").split(",") if p.strip())
DRY_RUN = os.environ.get("DRY_RUN", "").strip().lower() in ("1", "true", "yes")
NEVER = ("production", "develop")
def api(method, path):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
method=method,
headers={"Authorization": f"token {TOKEN}"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def pages(path):
"""Every item of a paged list."""
page, found = 1, []
while True:
items = api("GET", f"{path}{'&' if '?' in path else '?'}page={page}&limit=50") or []
found += items
if len(items) < 50:
return found
page += 1
def stale(branches, open_heads, now):
"""The names to remove, with how many days they were quiet."""
limit = now - timedelta(days=DAYS)
names = []
for branch in branches:
name = branch["name"]
if name in NEVER or name.startswith("release/") or not name.startswith(PREFIXES) or name in open_heads:
continue
moment = datetime.fromisoformat(branch["commit"]["timestamp"].replace("Z", "+00:00"))
if moment < limit:
names.append((name, (now - moment).days))
return names
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
open_heads = {(pull.get("head") or {}).get("ref") for pull in pages("pulls?state=open")}
old = stale(pages("branches"), open_heads, datetime.now(timezone.utc))
if not old:
print(f"No {'/'.join(p.rstrip('/') for p in PREFIXES)} branch has been quiet for {DAYS} days.")
return
for name, days in old:
if DRY_RUN:
print(f"Would remove {name} (quiet for {days} days).")
else:
api("DELETE", "branches/" + urllib.parse.quote(name, safe=""))
print(f"Removed {name} (quiet for {days} days).")
if __name__ == "__main__":
main()
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""Release step of the `Release` workflow: tag what was just merged into production.
A push to production is a release when it is the merge of a `release/vX.Y.Z` pull request. This
finds that version (from the pull request Gitea knows for the commit, or from the merge message),
and makes the release `vX.Y.Z` on that commit, with the changelog section as its text. Gitea
makes the tag; Packagist picks the tag up in the next step.
The other way into production is the nightly dependency update of the homelab, a pull request from
`renovate/*`. That makes a patch release too: the version above the latest tag with the patch raised by
one (v0.5.0 -> v0.5.1), its text the title and description of the pull request. Renovate makes one pull
request per night, so that is at most one patch release a night. When a release branch is open (a version
above the latest tag) it makes none: the update goes out with that release.
Runs again on the same commit without harm: a tag that is already there on that commit is fine.
A push that is neither (a hotfix pushed by an admin, say) makes no release and says so.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create releases), COMMIT_HASH.
Standard library + git only.
"""
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
COMMIT = os.environ.get("COMMIT_HASH", "").strip()
def api(method, path, body=None, allow=()):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
if e.code in allow:
return None
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def pull_of(commit):
"""The pull request that made this commit, or None."""
return api("GET", f"commits/{commit}/pull", allow=(404,))
def release_branch_of(commit, pull=None):
"""The release branch whose pull request made this commit, or None."""
head = ((pull or {}).get("head") or {}).get("ref", "")
if semver.release_version(head):
return head
# Gitea's own merge message: "Merge pull request 'title' (#7) from release/v1.2.0 into production".
message = subprocess.run(["git", "log", "-1", "--pretty=%s", commit], capture_output=True, text=True).stdout
found = re.search(r"from (release/v\d+\.\d+\.\d+) into production", message)
return found.group(1) if found else None
def next_patch(newest):
"""v0.5.0 -> (0, 5, 1); None without a tag to count from."""
return None if newest is None else (newest[0], newest[1], newest[2] + 1)
def release_is_open(branches, newest):
"""True when one of the branches is a release/vX.Y.Z above the latest tag."""
return any((v := semver.release_version(b)) and (newest is None or v > newest) for b in branches)
def dependency_release(commit, pull):
"""Makes the patch release for a merged renovate/* pull request; says why when it makes none."""
tags = subprocess.run(["git", "tag", "--list", "v*"], capture_output=True, text=True).stdout.split()
already = subprocess.run(["git", "tag", "--points-at", commit], capture_output=True, text=True).stdout.split()
if any(semver.tag_version(tag) for tag in already):
print(f"{commit[:8]} is already tagged ({' '.join(already)}): nothing to do.")
return
newest = semver.latest(tags)
version = next_patch(newest)
if version is None:
print("No tag to count from: no release made.")
return
branches = [b["name"] for b in api("GET", "branches?limit=100") or []]
if release_is_open(branches, newest):
print("A release branch is open: this update goes out with it, no patch release made.")
return
tag = f"v{semver.text(version)}"
title = (pull.get("title") or "Dependency update").strip()
body = (pull.get("body") or "").strip()
notes = f"- {title}" + (f"\n\n{body}" if body else "")
publish(tag, commit, notes)
def publish(tag, commit, notes):
api("POST", "releases", {
"tag_name": tag,
"target_commitish": commit,
"name": tag,
"body": notes,
"draft": False,
"prerelease": False,
})
print(f"Released {tag} on {commit[:8]}.")
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
if not re.fullmatch(r"[0-9a-f]{40}", COMMIT):
sys.exit("COMMIT_HASH must be the full commit hash.")
pull = pull_of(COMMIT)
branch = release_branch_of(COMMIT, pull)
if branch is None:
if ((pull or {}).get("head") or {}).get("ref", "").startswith("renovate/"):
dependency_release(COMMIT, pull)
else:
print(f"{COMMIT[:8]} is not the merge of a release/vX.Y.Z or renovate/* pull request: no release made.")
return
version = semver.release_version(branch)
tag = f"v{semver.text(version)}"
existing = api("GET", f"releases/tags/{tag}", allow=(404,))
if existing:
print(f"{tag} already exists: nothing to do.")
return
changelog = open("CHANGELOG.md", encoding="utf-8").read() if os.path.exists("CHANGELOG.md") else ""
notes = semver.changelog_section(changelog, version)
if notes is None:
sys.exit(f"CHANGELOG.md has no section for {tag}: the release pull request should have been stopped by PR CI.")
publish(tag, COMMIT, notes)
if __name__ == "__main__":
main()
+44
View File
@@ -0,0 +1,44 @@
"""Version helpers shared by the release scripts. Standard library only."""
import re
# A version is always three numbers: 1.4.0. The tag has a v in front (v1.4.0), the branch is release/v1.4.0.
VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)")
RELEASE_BRANCH = re.compile(r"release/v(\d+)\.(\d+)\.(\d+)")
TAG = re.compile(r"v(\d+)\.(\d+)\.(\d+)")
def release_version(branch):
"""The version of a `release/vX.Y.Z` branch as a tuple, or None when it is not one."""
match = RELEASE_BRANCH.fullmatch(branch or "")
return tuple(int(part) for part in match.groups()) if match else None
def tag_version(tag):
match = TAG.fullmatch(tag or "")
return tuple(int(part) for part in match.groups()) if match else None
def latest(tags):
"""The highest version among the tags that are versions, or None."""
versions = [version for version in (tag_version(tag) for tag in tags) if version]
return max(versions) if versions else None
def text(version):
return ".".join(str(part) for part in version)
def changelog_section(changelog, version):
"""The body under `## vX.Y.Z` of the changelog, up to the next `## `; None when there is no such heading."""
heading = re.compile(rf"^##\s+v?{re.escape(text(version))}(\s|$)")
lines = changelog.splitlines()
for index, line in enumerate(lines):
if heading.match(line):
body = []
for following in lines[index + 1:]:
if following.startswith("## "):
break
body.append(following)
return "\n".join(body).strip()
return None
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Starts a release: makes the branch release/vX.Y.Z from develop.
Features are pull requests to that branch (they merge by themselves when CI is green). When the release
is ready, a pull request from it to production makes the release.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create branches), VERSION (1.4.0, or v1.4.0).
Standard library only.
"""
import json
import os
import re
import sys
import urllib.error
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import semver # noqa: E402
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
def api(method, path, body=None, allow=()):
request = urllib.request.Request(
f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}",
data=json.dumps(body).encode() if body is not None else None,
method=method,
headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(request, timeout=30) as response:
text = response.read().decode()
except urllib.error.HTTPError as e:
if e.code in allow:
return None
sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}")
return json.loads(text) if text else None
def main():
if not (URL and OWNER and REPO and TOKEN):
sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.")
given = os.environ.get("VERSION", "").strip().lstrip("v")
if not semver.VERSION.fullmatch(given):
sys.exit(f"'{given}' is not a version: use three numbers, like 1.4.0.")
version = tuple(int(part) for part in given.split("."))
tags = [tag["name"] for tag in api("GET", "tags?limit=50") or []]
newest = semver.latest(tags)
if newest is not None and version <= newest:
sys.exit(f"v{given} is not above the latest tag v{semver.text(newest)}.")
name = f"release/v{given}"
if api("GET", f"branches/{name}", allow=(404,)):
sys.exit(f"{name} already exists.")
api("POST", "branches", {"new_branch_name": name, "old_branch_name": "develop"})
print(f"{name} made from develop. Make features as pull requests to it; when it is ready, open one to production.")
if __name__ == "__main__":
main()
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Sync step of the `Release` workflow: merge production into develop.
Runs after a release, so `develop` always contains what is live. Features are made from develop, so
it must be on the latest production before the next release is started.
`develop` takes direct pushes (only `production` and the release branches are protected),
so this is a plain merge and push: fast-forward when possible, otherwise a
merge commit `chore: sync production into develop`.
A conflict fails the step on purpose. The release itself is done by then; the
red build is the signal that `develop` holds something production does not
and needs a merge by hand.
Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (an access token
that may push to develop), COMMIT_HASH (the commit this job released; defaults
to the tip of production). SYNC_REMOTE overrides the clone URL (local testing).
Standard library + git only.
"""
import json
import os
import re
import subprocess
import tempfile
import urllib.request
URL = os.environ.get("GT_URL", "").rstrip("/")
OWNER = os.environ.get("GT_OWNER", "")
REPO = os.environ.get("GT_REPO", "")
TOKEN = os.environ.get("GT_TOKEN", "")
REMOTE = os.environ.get("SYNC_REMOTE", "")
MESSAGE = "chore: sync production into develop"
def git(repo, *args, check=True):
result = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True)
if check and result.returncode != 0:
raise SystemExit(f"git {' '.join(args[:2])} failed: {result.stderr.strip()}")
return result
def main():
user = os.environ.get("GT_BOT_USER") or "sync"
remote = REMOTE
if not remote:
if not (URL and OWNER and REPO and TOKEN):
raise SystemExit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required")
remote = f"https://{user}:{TOKEN}@{URL.split('://', 1)[1]}/{OWNER}/{REPO}.git"
repo = os.path.join(tempfile.mkdtemp(), "repo")
result = subprocess.run(["git", "clone", "--quiet", "--branch", "develop", remote, repo],
capture_output=True, text=True)
if result.returncode != 0:
raise SystemExit(f"Could not clone develop: {result.stderr.strip()}")
git(repo, "config", "user.name", user)
git(repo, "config", "user.email", f"{user}@iriks-it.nl")
commit = os.environ.get("COMMIT_HASH", "").strip()
source = commit if re.fullmatch(r"[0-9a-f]{40}", commit) else "origin/production"
short = git(repo, "rev-parse", "--short", source).stdout.strip()
if git(repo, "merge-base", "--is-ancestor", source, "HEAD", check=False).returncode == 0:
print(f"develop already contains production ({short}) — nothing to do.")
return
merge = git(repo, "merge", "--no-edit", "-m", MESSAGE, source, check=False)
if merge.returncode != 0:
conflicts = git(repo, "diff", "--name-only", "--diff-filter=U", check=False).stdout.strip()
raise SystemExit(
f"production ({short}) does not merge cleanly into develop — merge it by hand.\n"
f"Conflicting files:\n{conflicts or merge.stdout.strip() or merge.stderr.strip()}"
)
push = git(repo, "push", "--quiet", "origin", "HEAD:refs/heads/develop", check=False)
if push.returncode != 0:
raise SystemExit(f"Could not push develop: {push.stderr.strip()}")
print(f"develop now contains production ({short}).")
if __name__ == "__main__":
main()
+198
View File
@@ -0,0 +1,198 @@
"""Tests of the release scripts: `python3 -m unittest discover -s .gitea/scripts` (run by the `flow` job)."""
import importlib.util
import os
import sqlite3
import sys
import unittest
from datetime import datetime, timezone
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import check_flow # noqa: E402
import packagist # noqa: E402
import prune_branches # noqa: E402
import release # noqa: E402
import semver # noqa: E402
TAGS = ["v0.1.0", "v0.2.0", "v0.10.0", "not-a-version"]
CHANGELOG = "# Changelog\n\n## v0.11.0 - 2026-12-10\n\n- A feature\n- Another\n\n## v0.10.0 - 2026-12-01\n\n- Older\n"
class Versions(unittest.TestCase):
def test_release_branch(self):
self.assertEqual(semver.release_version("release/v1.2.3"), (1, 2, 3))
for wrong in ("release/1.2.3", "release/v1.2", "feature/x", "release/v1.2.3-rc1", "", None):
self.assertIsNone(semver.release_version(wrong))
def test_latest_is_numeric_not_alphabetical(self):
self.assertEqual(semver.latest(TAGS), (0, 10, 0))
self.assertIsNone(semver.latest(["x"]))
def test_changelog_section(self):
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 11, 0)), "- A feature\n- Another")
self.assertEqual(semver.changelog_section(CHANGELOG, (0, 10, 0)), "- Older")
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 0)))
self.assertIsNone(semver.changelog_section(CHANGELOG, (0, 1, 1)))
class Flow(unittest.TestCase):
def check(self, base, head, tags=TAGS, changelog=CHANGELOG, composer=None):
return check_flow.problems(base, head, tags, changelog, composer or {"name": "x/y"})
def test_release_to_production(self):
self.assertEqual(self.check("production", "release/v0.11.0"), [])
def test_production_also_takes_the_nightly_renovate_branch(self):
self.assertEqual(self.check("production", "renovate/deps-20261205"), [])
self.assertTrue(self.check("production", "renovate"))
def test_production_only_from_a_release_branch(self):
self.assertTrue(self.check("production", "feature/x"))
self.assertTrue(self.check("production", "develop"))
def test_release_must_be_above_the_latest_tag(self):
self.assertTrue(self.check("production", "release/v0.10.0"))
self.assertTrue(self.check("production", "release/v0.9.0"))
def test_release_needs_its_changelog_section(self):
self.assertTrue(self.check("production", "release/v0.12.0"))
self.assertTrue(self.check("production", "release/v0.11.0", changelog=None))
def test_composer_json_has_no_version(self):
self.assertTrue(self.check("production", "release/v0.11.0", composer={"version": "0.11.0"}))
def test_features_into_an_open_release_branch(self):
self.assertEqual(self.check("release/v0.11.0", "feature/x"), [])
self.assertEqual(self.check("release/v0.11.0", "fix/y"), [])
def test_nothing_into_a_release_that_is_out(self):
self.assertTrue(self.check("release/v0.10.0", "feature/x"))
def test_a_release_branch_takes_no_long_lived_branch(self):
for head in ("production", "develop", "release/v0.12.0"):
self.assertTrue(self.check("release/v0.11.0", head))
def test_nothing_goes_to_develop_or_anything_else(self):
self.assertTrue(self.check("develop", "feature/x"))
self.assertTrue(self.check("main", "feature/x"))
def test_first_release_without_tags(self):
self.assertEqual(self.check("production", "release/v0.1.0", tags=[], changelog="## v0.1.0 - x\n\n- a\n"), [])
class Prune(unittest.TestCase):
NOW = datetime(2026, 12, 4, tzinfo=timezone.utc)
def branch(self, name, day):
return {"name": name, "commit": {"timestamp": f"{day}T10:00:00Z"}}
def names(self, branches, open_heads=()):
return [name for name, _ in prune_branches.stale(branches, set(open_heads), self.NOW)]
def test_removes_only_quiet_feature_and_fix_branches(self):
branches = [
self.branch("feature/old", "2026-10-01"), self.branch("fix/old", "2026-11-01"),
self.branch("feature/new", "2026-11-20"), self.branch("feature/edge", "2026-11-05"),
]
self.assertEqual(self.names(branches), ["feature/old", "fix/old"])
def test_never_removes_the_long_lived_branches(self):
old = "2025-01-01"
branches = [self.branch(n, old) for n in ("production", "develop", "release/v0.1.0", "renovate/x", "other")]
self.assertEqual(self.names(branches), [])
def test_keeps_a_branch_with_an_open_pull_request(self):
self.assertEqual(self.names([self.branch("feature/old", "2026-01-01")], open_heads=["feature/old"]), [])
def load_hermes():
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "dev", "token-usage-hermes.py")
spec = importlib.util.spec_from_file_location("token_usage_hermes", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class HermesTokens(unittest.TestCase):
def setUp(self):
self.hermes = load_hermes()
self.con = sqlite3.connect(":memory:")
self.con.execute("CREATE TABLE sessions (id TEXT, parent_session_id TEXT, model TEXT, api_call_count INT, output_tokens INT, input_tokens INT, cache_write_tokens INT, cache_read_tokens INT)")
self.con.executemany("INSERT INTO sessions VALUES (?,?,?,?,?,?,?,?)", [
("main", None, "model-a", 10, 1000, 20, 300, 4000),
("helper", "main", "model-b", 3, 200, 5, 0, 50),
("grandchild", "helper", "model-b", 2, 100, 1, 0, 10),
("other", None, "model-a", 99, 9, 9, 9, 9),
])
def test_children_through_every_level(self):
self.assertEqual(self.hermes.expand_children(self.con, ["main"]), ["grandchild", "helper", "main"])
def test_one_row_per_model_with_the_hours_on_the_first_only(self):
_, per_model, missing = self.hermes.totals(self.con, ["main", "helper", "grandchild", "nope"])
self.assertEqual(missing, {"nope"})
rows = self.hermes.lines(per_model, "Work", "2026-12-04", "", 1.5)
self.assertEqual(rows[0], "| 2026-12-04 | Work | | model-a | 10 | 1.000 | 20 | 300 | 4.000 | 1,50 |")
self.assertEqual(rows[1], "| 2026-12-04 | Work | | model-b | 5 | 300 | 6 | 0 | 60 | 0,00 |")
def test_hours_are_never_invented(self):
_, per_model, _ = self.hermes.totals(self.con, ["main"])
self.assertTrue(self.hermes.lines(per_model, "Work", "2026-12-04", "", None)[0].endswith("| 4.000 | |"))
class DependencyRelease(unittest.TestCase):
def test_the_next_patch(self):
self.assertEqual(release.next_patch((0, 5, 0)), (0, 5, 1))
self.assertEqual(release.next_patch((1, 2, 9)), (1, 2, 10))
self.assertIsNone(release.next_patch(None))
def test_an_open_release_takes_the_update_with_it(self):
branches = ["production", "develop", "release/v0.4.0", "release/v0.5.0", "renovate/deps-1"]
self.assertFalse(release.release_is_open(branches, (0, 5, 0)))
self.assertTrue(release.release_is_open(branches, (0, 4, 0)))
self.assertTrue(release.release_is_open(branches + ["release/v0.5.1"], (0, 5, 0)))
class PackagistNotice(unittest.TestCase):
def run_notice(self, answers):
"""Runs notify() with fake answers per endpoint (a status number, or an HTTP error code as a string)."""
import io
import urllib.error
calls = []
def fake(endpoint, user, token, url):
calls.append(endpoint)
answer = answers[endpoint]
if isinstance(answer, str):
raise urllib.error.HTTPError("x", int(answer), "refused", {}, io.BytesIO(b"nope"))
return answer
original = packagist.call
packagist.call = fake
try:
return packagist.notify("u", "t", "https://example.org/r"), calls
finally:
packagist.call = original
def test_a_known_package_is_only_updated(self):
message, calls = self.run_notice({"update-package": 202})
self.assertEqual(calls, ["update-package"])
self.assertIn("202", message)
def test_an_unknown_package_is_submitted(self):
message, calls = self.run_notice({"update-package": "404", "create-package": 202})
self.assertEqual(calls, ["update-package", "create-package"])
self.assertIn("submitted", message)
def test_another_refusal_is_not_submitted(self):
with self.assertRaises(SystemExit):
self.run_notice({"update-package": "403", "create-package": 202})
def test_a_refused_submission_fails(self):
with self.assertRaises(SystemExit):
self.run_notice({"update-package": "404", "create-package": "400"})
if __name__ == "__main__":
unittest.main()
+188
View File
@@ -0,0 +1,188 @@
name: PR CI
# Pull requests go to a release branch (features) or to production (the release). develop only takes
# the sync after a release. See README.md, "Development cycle".
on:
pull_request:
branches: ['release/**', production]
env:
COMPOSER_NO_INTERACTION: '1'
jobs:
# Does the pull request follow the cycle: right branches, a version above the latest tag, a changelog
# section for a release.
flow:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: tests of the release scripts
run: python3 -m unittest discover -s .gitea/scripts
- name: development cycle
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/check_flow.py
env:
BASE_REF: ${{ github.base_ref }}
HEAD_REF: ${{ github.head_ref }}
# Every piece of work records its tokens and hours (TOKENS.md). Exempt: release/*, renovate/*, bots.
ledger:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: token ledger updated
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/check_tokens.py
env:
BASE_REF: ${{ github.base_ref }}
HEAD_REF: ${{ github.head_ref }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
# Style and tests, with the newest dependencies the constraints allow and with the oldest: a package
# has to work for everyone in between.
test:
runs-on: docker
container:
image: webdevops/php:8.4
strategy:
fail-fast: false
matrix:
dependencies: [stable, lowest]
steps:
- name: checkout
uses: actions/checkout@v4
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-${{ matrix.dependencies }}-${{ hashFiles('composer.json') }}
restore-keys: |
composer-${{ matrix.dependencies }}-
- name: composer validate
run: composer validate --strict --no-check-lock
- name: install dependencies (${{ matrix.dependencies }})
env:
COMPOSER_MAX_PARALLEL_HTTP: '4'
run: |
flags="--prefer-stable --prefer-dist"
[ "${{ matrix.dependencies }}" = "lowest" ] && flags="--prefer-lowest $flags"
for attempt in 1 2 3; do
composer update $flags && exit 0
echo "composer failed (attempt $attempt of 3), trying again" >&2
sleep $((attempt * 10))
done
exit 1
- name: lint (pint)
if: matrix.dependencies == 'stable'
run: vendor/bin/pint --test
- name: pest tests
run: vendor/bin/pest
# The screens (ui/) are built into resources/dist, which is committed so a site needs no Node. Check that the
# sources type-check and that the committed bundle is what the sources build to. The node image has git (see below).
ui:
runs-on: docker
container:
image: node:22-bookworm
steps:
- name: checkout
uses: actions/checkout@v4
- name: install
run: cd ui && npm ci --no-audit --no-fund
- name: type check
run: cd ui && npm run typecheck
- name: build
run: cd ui && npm run build
- name: the committed bundle is up to date
run: |
git config --global --add safe.directory "$(pwd)"
git diff --exit-code -- resources/dist || { echo "resources/dist is out of date: run 'npm run build' in ui/ and commit it" >&2; exit 1; }
# Known vulnerabilities in the dependencies, and secrets or bad settings in the repository.
security:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-security-${{ hashFiles('composer.json') }}
restore-keys: |
composer-security-
- name: install dependencies
env:
COMPOSER_MAX_PARALLEL_HTTP: '4'
run: |
for attempt in 1 2 3; do
composer update --prefer-stable --prefer-dist --no-scripts && exit 0
echo "composer failed (attempt $attempt of 3), trying again" >&2
sleep $((attempt * 10))
done
exit 1
- name: composer audit
run: composer audit
# Pull requests to a release branch merge by themselves when the check below is green.
# Every job that checks out runs in an image with git: without git the checkout is the archive of the
# repository, which leaves out what .gitattributes export-ignores (.gitea/ with these scripts).
release-automerge:
runs-on: docker
needs: pr-ci
if: startsWith(github.base_ref, 'release/') && needs.pr-ci.result == 'success'
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: enable auto-merge
run: python3 .gitea/scripts/auto_merge.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }}
# The one check the branch protection asks for (`PR CI / pr-ci (pull_request)`): green only when
# every job above is. Do not rename it without changing the protection rule.
pr-ci:
runs-on: docker
needs: [flow, ledger, test, ui, security]
if: always()
container:
image: alpine:3.20
steps:
- name: all checks green
run: |
echo "flow=${{ needs.flow.result }} ledger=${{ needs.ledger.result }} test=${{ needs.test.result }} ui=${{ needs.ui.result }} security=${{ needs.security.result }}"
[ "${{ needs.flow.result }}" = "success" ] && [ "${{ needs.ledger.result }}" = "success" ] && [ "${{ needs.test.result }}" = "success" ] && [ "${{ needs.ui.result }}" = "success" ] && [ "${{ needs.security.result }}" = "success" ]
+30
View File
@@ -0,0 +1,30 @@
name: Prune branches
# Every night: remove feature/* and fix/* branches that nobody touched for 30 days and that have no
# open pull request. production, develop and the release branches are never removed.
on:
schedule:
- cron: '15 4 * * *'
workflow_dispatch:
inputs:
dry_run:
description: 'Only say what would be removed (1) or remove it (0)'
default: '1'
jobs:
prune:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: remove quiet branches
run: python3 .gitea/scripts/prune_branches.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
DRY_RUN: ${{ inputs.dry_run }}
+106
View File
@@ -0,0 +1,106 @@
name: Release
# A push to production is the merge of a release pull request. Check it once more, tag it, tell
# Packagist, and bring develop up to date, so the next features start from what was released.
on:
push:
branches: [production]
concurrency:
group: release
cancel-in-progress: false
jobs:
verify:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: cache composer downloads
uses: actions/cache@v4
with:
path: ~/.composer/cache
key: composer-release-${{ hashFiles('composer.json') }}
restore-keys: |
composer-release-
- name: install dependencies
env:
COMPOSER_MAX_PARALLEL_HTTP: '4'
run: |
for attempt in 1 2 3; do
composer update --prefer-stable --prefer-dist && exit 0
echo "composer failed (attempt $attempt of 3), trying again" >&2
sleep $((attempt * 10))
done
exit 1
- name: pest tests
run: vendor/bin/pest
- name: composer audit
run: composer audit
tag:
runs-on: docker
needs: verify
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: release
run: |
git config --global --add safe.directory "$(pwd)"
python3 .gitea/scripts/release.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
COMMIT_HASH: ${{ github.sha }}
# Needs the secrets PACKAGIST_USERNAME and PACKAGIST_TOKEN on the repository, and the package
# submitted on packagist.org once. Without them this step only says so.
packagist:
runs-on: docker
needs: tag
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: tell Packagist
run: python3 .gitea/scripts/packagist.py
env:
PACKAGIST_USERNAME: ${{ secrets.PACKAGIST_USERNAME }}
PACKAGIST_TOKEN: ${{ secrets.PACKAGIST_TOKEN }}
PACKAGE_URL: https://git.iriks.casa/iriks-it/laravel-manager
# Last: merge what was released into develop. Runs even when Packagist could not be told.
sync-develop:
runs-on: docker
needs: [tag, packagist]
if: always() && needs.tag.result == 'success'
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: sync develop
run: python3 .gitea/scripts/sync_develop.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
GT_BOT_USER: deploy-bot
COMMIT_HASH: ${{ github.sha }}
+27
View File
@@ -0,0 +1,27 @@
name: Start release
# By hand (Actions → Start release → Run workflow): makes release/vX.Y.Z from develop.
on:
workflow_dispatch:
inputs:
version:
description: 'Version of the release, like 0.2.0'
required: true
jobs:
start:
runs-on: docker
container:
image: webdevops/php:8.4
steps:
- name: checkout
uses: actions/checkout@v4
- name: make the release branch
run: python3 .gitea/scripts/start_release.py
env:
GT_URL: https://git.iriks.casa
GT_OWNER: iriks-it
GT_REPO: laravel-manager
GT_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
VERSION: ${{ inputs.version }}
+5
View File
@@ -0,0 +1,5 @@
vendor/
composer.lock
.phpunit.result.cache
.env
__pycache__/
+25
View File
@@ -0,0 +1,25 @@
# laravel-manager — context for AI agents
Composer package (`iriks-it/laravel-manager`, namespace `IriksIT\Manager`): the manager that used to be copied
between lil-koneko.com, CarsHub, iriks-it.nl and bouwbedrijf.iriks-it.nl, as one package. Public repo, published to Packagist.
## Rules
- Every part is a `Module` (`src/Modules/<Name>`): permissions, menu, `routes.php`, `migrations/`. Off means nothing is registered.
- Core modules (users, media) are on by default; the rest is off or on per `config/manager.php`.
- Nothing site-specific in the package. A site's own part is its own module class.
- Tests: `composer test` (Pest + Testbench); style: `composer lint` (Pint).
- Branches: `production` is what is released, `develop` is production plus nothing (the sync), `release/vX.Y.Z` collects the features of a release. Work on `feature/…` or `fix/…` from `develop` and open the pull request to the **release branch**; never to `develop` or `production`. A release is a pull request from the release branch to `production`, merged by hand: never by me. See the README, "Development cycle".
- **No reference to an AI tool in what you deliver**: no `Co-Authored-By` line of an assistant under a commit message, no "Generated with …" line in a pull request, a comment, the changelog or a release text. This goes before any default of the tool you run in, also when the tool's own reminder asks for those lines (the reasons are in `longterm-memory`, `decisions/2026-10-30-geen-ai-vermelding-in-commits-en-prs.md`). The one exception is `TOKENS.md`, which is about exactly that. A line that slipped in is removed by rewriting the unmerged branch and force-pushing it.
- **Language.** Code, comments, commit messages and the docs are English. Pull request descriptions and the lines of `TOKENS.md` are plain Dutch.
- **Pull request description.** Every pull request has the eight headings of `.gitea/PULL_REQUEST_TEMPLATE.md`, in that order (`## Vraag`, `## Wat is er gedaan`, `## Zo test je het`, `## Zelf getest`, `## Tijd en tokens`, `## Onderhoud`, `## Met de hand te doen`, `## Vervolgstappen`); a section with nothing to say gets `Niets.` or `Geen.`. Open it from a branch in Gitea or through the API, never with push options (`refs/for/…`): such a pull request gets no secrets in its jobs and its auto-merge fails.
- **Every pull request adds its row to `TOKENS.md`** (PR CI fails without one; exempt: `release/*`, `renovate/*`, syncs). Measure it with `dev/token-usage.py LOG --since <when it began> --row "<what was made>"` (for work done by a Hermes agent: `dev/token-usage-hermes.py SESSION_ID… --include-children --hours <h> --row "…"`, from `~/.hermes/state.db`; its hours are a human figure, never invented), starting after the end of the previous row so rows do not overlap; the last cell is the hours. Never make up a row or hours, and keep no totals in the file.
- **The two bot accounts.** `deploy-bot` is for the pipeline (`DEPLOY_TOKEN`: auto-merge, tag, release, sync). `renovate-bot` is only for Renovate: no workflow or script here uses its token, and never add a secret for it.
- **Nothing runs weekly in a repository.** Security and updates are the homelab's: Trivy every night (03:00) and after every release, the dependency round every night (04:00, branches `renovate/*`). A repository's own pipeline does `composer audit` (or the equivalent) on every pull request and on every release, and nothing on a schedule. Do not add a `schedule:` trigger; the nightly branch pruning is the one exception.
- **Security first.** Validate at system boundaries, never trust raw request data, and never introduce the OWASP top-10 (injection, XSS, …). This package is public: no real addresses, names, tokens or client details in code, tests, docs or defaults. In a migration a moment that may not be null is `dateTime`, never `timestamp` (the MySQL of the servers gives such a `timestamp` a default by itself and refuses a second one in a table).
## Open decisions
1. Frontend: decided and built: the screens are in the package (`ui/`, built into `resources/dist`, committed; PR CI checks it is up to date). Still open: a theme editor in the manager, and a `host` mode that publishes the sources for a site to build itself.
2. Moving the rest from bouwbedrijf.iriks-it.nl: reviews (still a read-only list). Users, media, posts, pages with fields, resources, revisions, audit log and statistics are done, with their screens. Leave out what is site-specific (the IriksIT API disk, client names): this repo is public. Still open: two-factor login, cropping pictures, automated tests of the screens in CI.
3. Decided in 0.5.0: groups stay the default and the host's roles are added next to them (`manager.permissions`: `mode` groups, host or merge; `roles` or a `PermissionResolver`). A host that wants to replace the groups screens entirely is not planned.
-10
View File
@@ -4,16 +4,6 @@ Every release has a section here, named after its version (for example `v0.1.0 -
heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of
the section is the text of the release in Gitea. the section is the text of the release in Gitea.
## v0.5.2 - 2026-12-04
- The mirror for Packagist gets a clean tree per release (no tests, `ui/`, `dev/`, `TOKENS.md`, `.gitea/` or agent files), with no history and no
branch, so `composer require` installs less and this repository can be private. `mirror_tags.sh`, with tests; `out/` is export-ignored too.
## v0.5.1 - 2026-12-04
- Packagist shows only the releases: the Release workflow pushes the tags to a mirror (`iriks-it/laravel-manager-packagist`) that has only a `production` branch with a note (no `composer.json`, so no version),
and Packagist reads that, so the `dev-…` versions of every branch are gone.
## v0.5.0 - 2026-12-04 ## v0.5.0 - 2026-12-04
- Names that can move: `route_name` for the route-name prefix, `tables` for a table of its own per short name (on top of `table_prefix`), - Names that can move: `route_name` for the route-name prefix, `tables` for a table of its own per short name (on top of `table_prefix`),
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+1 -8
View File
@@ -261,7 +261,7 @@ Nobody opens a pull request to `develop`, and `production` and the release branc
| When | What runs | | When | What runs |
|---|---| |---|---|
| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`: the job fails on any advisory). The check `PR CI / pr-ci` is green when all are. | | Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`: the job fails on any advisory). The check `PR CI / pr-ci` is green when all are. |
| Push to production | verify (Pest, `composer audit`), tag and release, the tags to the mirror `laravel-manager-packagist`, Packagist, sync develop; then the homelab scans production with Trivy | | Push to production | verify (Pest, `composer audit`), tag and release, Packagist, sync develop; then the homelab scans production with Trivy |
| Every night | the homelab scans every repository with Trivy (03:00) and updates its dependencies (04:00): nothing runs weekly in this repository | | Every night | the homelab scans every repository with Trivy (03:00) and updates its dependencies (04:00): nothing runs weekly in this repository |
| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) | | Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) |
@@ -277,13 +277,6 @@ Nothing here runs on a weekly schedule; the checks hang on the moments that matt
merged the Release workflow makes a patch release of it (v0.5.0 → v0.5.1, text from the pull request), tells Packagist and syncs `develop`: merged the Release workflow makes a patch release of it (v0.5.0 → v0.5.1, text from the pull request), tells Packagist and syncs `develop`:
one a night at most. While a release branch is open there is no patch release; the update goes out with that release. A critical advisory on the installed version skips the 48 hours. one a night at most. While a release branch is open there is no patch release; the update goes out with that release. A critical advisory on the installed version skips the 48 hours.
Packagist reads the mirror `iriks-it/laravel-manager-packagist`, not this repository, because it shows every branch of the
repository it reads as a `dev-…` version. For every release the Release workflow (`.gitea/scripts/mirror_tags.sh`) puts a clean
tree on the mirror: what `git archive` of the tag gives, so without what `.gitattributes` marks `export-ignore` (tests, `ui/`,
`dev/`, `TOKENS.md`, `.gitea/`, the agent files), as a commit with no history and no branch, and pushes only its tag. The mirror
has one branch, `production`, that only holds a note (no `composer.json`, so no version); nothing else is ever pushed there. Packagist
and `composer require` only see the mirror, so this repository can be private. (Versions up to v0.5.1 on the mirror are the full tree.)
Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and
`PACKAGIST_TOKEN` (until they are set that step only says so). When Packagist does not know the package yet, that step `PACKAGIST_TOKEN` (until they are set that step only says so). When Packagist does not know the package yet, that step
submits it through the create-package API; after that it only tells Packagist about each new tag. submits it through the create-package API; after that it only tells Packagist about each new tag.
+49
View File
@@ -0,0 +1,49 @@
# Tokenverbruik en uren van dit project
Per stuk werk een rij; zie `dev/token-usage.py`.
| Datum | Onderdeel | Versie | Model | Stappen | Uitvoer | Invoer | Cache geschreven | Cache gelezen | Uren |
|---|---|---|---|---:|---:|---:|---:|---:|---:|
| 2026-12-04 | Eerste opzet van het pakket: modules, schakelaars, rechten. Gebruikers en media uit bouwbedrijf overgezet | - | claude-sonnet-5-5 | 34 | 57.433 | 76 | 131.194 | 3.225.205 | 0,18 |
| 2026-12-04 | Posts overgezet: berichten met concepten, inplannen, categorieën en tags | - | claude-sonnet-5-5 | 9 | 19.897 | 20 | 35.420 | 1.584.858 | 0,03 |
| 2026-12-04 | Token-script telt de tokens van helper-agents mee in de rij, per model | - | claude-sonnet-5-5 | 16 | 27.013 | 36 | 45.155 | 2.982.056 | 0,06 |
| 2026-12-04 | CI en releaseproces opgezet: releasebranch, tag, Packagist, sync naar develop, tests, audit en Trivy | - | claude-sonnet-5-5 | 14 | 31.242 | 30 | 48.735 | 3.520.606 | 0,09 |
| 2026-12-04 | Opstart van de release gerepareerd en oude featurebranches na 30 dagen automatisch opruimen | - | claude-sonnet-5-5 | 14 | 14.499 | 32 | 14.175 | 4.138.947 | 0,08 |
| 2026-12-04 | De eerste release gestart en het LICENSE-bestand (MIT) toegevoegd voor Packagist | - | claude-sonnet-5-5 | 13 | 14.884 | 32 | 14.810 | 3.953.265 | 0,07 |
| 2026-12-04 | Changelog van de eerste release ingevuld en de release klaargezet | - | claude-sonnet-5-5 | 8 | 7.421 | 16 | 15.226 | 2.534.041 | 0,02 |
| 2026-12-04 | De changelog van de eerste release hersteld, de kop stond verkeerd | - | claude-sonnet-5-5 | 5 | 3.535 | 10 | 6.917 | 1.656.465 | 0,03 |
| 2026-12-04 | Composer-cache en herhaalpogingen in alle CI-jobs, zodat haperende downloads de pipeline niet meer breken | - | claude-sonnet-5-5 | 74 | 80.637 | 164 | 167.489 | 21.208.458 | 0,65 |
| 2026-12-04 | Auditlog en banbeheer als module 'audit' overgenomen uit bouwbedrijf, met tests, en de gedeelde regels van de andere repo's in AGENTS.md | - | claude-sonnet-5-5 | 38 | 49.634 | 82 | 92.591 | 5.342.800 | 0,18 |
| 2026-12-04 | Bezoekersstatistieken als module 'statistics' overgenomen uit bouwbedrijf: paginaweergaven zonder cookies, bronnen, bots en export | - | claude-sonnet-5-5 | 12 | 16.807 | 24 | 20.717 | 2.545.198 | 0,03 |
| 2026-12-04 | Token-script telt de aanroepen van de adviseur (een ander model) mee, als eigen rij met het eigen model | - | claude-sonnet-5-5 | 29 | 22.281 | 64 | 55.197 | 5.142.066 | 0,07 |
| 2026-12-01 | Adviseur-aanroep bij het eerdere werk (CI, release en eerste modules), die in de rijen erboven nog niet meetelde | - | claude-fable-5-2 | 1 | 10.012 | 115.261 | 0 | 0 | 0,00 |
| 2026-12-04 | Adviseur-aanroepen bij de auditmodule en het banbeheer, die in de rij erboven nog niet meetelden | - | claude-fable-5-2 | 2 | 25.967 | 246.202 | 0 | 0 | 0,00 |
| 2026-12-04 | Het Hermes-tokenscript uit bouwbedrijf overgenomen, met dezelfde rijen per model als het hoofdscript | - | claude-sonnet-5-5 | 9 | 7.044 | 20 | 15.263 | 2.258.010 | 0,01 |
| 2026-12-04 | Wekelijkse update van de versiebereiken van afhankelijkheden, als pull request naar de open release | - | claude-sonnet-5-5 | 6 | 7.611 | 12 | 10.963 | 1.632.350 | 0,01 |
| 2026-12-04 | De commit zonder AI-vermelding hersteld in de release, de uitleg over de nachtelijke scans gecorrigeerd en de notities in longterm-memory gemaakt | - | claude-sonnet-5-5 | 29 | 16.997 | 72 | 21.381 | 8.975.420 | 0,11 |
| 2026-12-04 | De Packagist-stap meldt het pakket zelf aan als Packagist het nog niet kent | - | claude-sonnet-5-5 | 13 | 7.095 | 30 | 11.993 | 4.256.820 | 0,06 |
| 2026-12-04 | Installatie en gezondheidscheck voor AI (manager:install en manager:doctor) met een stappengids voor agents | - | claude-sonnet-5-5 | 12 | 12.112 | 28 | 64.789 | 2.344.181 | 0,04 |
| 2026-12-04 | Installatie en gezondheidscheck voor AI (manager:install en manager:doctor) met een stappengids voor agents | - | claude-fable-5-2 | 1 | 17.440 | 362.597 | 0 | 0 | 0,00 |
| 2026-12-04 | Schermen in het pakket: eigen login, profiel, menu en berichten, thema's per gebruiker en voor de huisstijl van de site | - | claude-sonnet-5-5 | 51 | 60.198 | 102 | 94.747 | 7.947.787 | 0,19 |
| 2026-12-04 | Schermen voor gebruikers, groepen, categorieën en tags, pagina's en reviews | - | claude-sonnet-5-5 | 11 | 13.236 | 24 | 21.715 | 2.310.933 | 0,06 |
| 2026-12-04 | Schermen voor media (met kiezer voor de omslag), de auditlog met blokkades en de statistieken | - | claude-sonnet-5-5 | 23 | 23.335 | 46 | 42.961 | 5.678.787 | 0,06 |
| 2026-12-04 | De stappengids en de installatie verbeterd na de proef met een verse agent | - | claude-sonnet-5-5 | 25 | 21.844 | 50 | 35.997 | 6.551.164 | 0,10 |
| 2026-12-04 | De stappengids en de installatie verbeterd na de proef met een verse agent | - | claude-haiku-5-5 | 11 | 8.233 | 22 | 51.184 | 444.805 | 0,00 |
| 2026-12-04 | Changelog van v0.4.0, wiki en notitie in longterm-memory | - | claude-sonnet-5-5 | 7 | 3.891 | 14 | 5.215 | 1.999.583 | 0,01 |
| 2026-12-04 | De wekelijkse workflow werkt ook de npm-pakketten van de schermen bij, met 48 uur wachttijd en een nieuwe bundel | - | claude-sonnet-5-5 | 9 | 9.971 | 22 | 15.191 | 3.032.384 | 0,05 |
| 2026-12-04 | TypeScript 7 niet voorstellen zolang vue-tsc het niet draait, en de PR van de eerste run rechtgezet | - | claude-sonnet-5-5 | 10 | 4.340 | 26 | 4.489 | 3.503.406 | 0,05 |
| 2026-12-04 | Namen die kunnen verhuizen (route_name, tables) en manager:import voor bestaande gegevens | - | claude-sonnet-5-5 | 25 | 17.827 | 54 | 72.997 | 2.216.503 | 0,09 |
| 2026-12-04 | Namen die kunnen verhuizen (route_name, tables) en manager:import voor bestaande gegevens | - | claude-fable-5-2 | 1 | 5.062 | 61.001 | 0 | 0 | 0,00 |
| 2026-12-04 | Teksten van de server vertaalbaar met lang-bestanden en een Nederlandse vertaling | - | claude-sonnet-5-5 | 14 | 11.377 | 28 | 23.146 | 1.520.289 | 0,02 |
| 2026-12-04 | Menu met secties, iconen en volgorde, en de simpele weergave naast de volledige | - | claude-sonnet-5-5 | 23 | 20.663 | 46 | 31.486 | 3.202.624 | 0,05 |
| 2026-12-04 | Echte pagina's met velden, een veldenschema en het formulier in de schermen | - | claude-sonnet-5-5 | 17 | 20.944 | 34 | 31.958 | 2.886.715 | 0,07 |
| 2026-12-04 | Lijsten zonder code (resources) en een eigen bundel met schermen van de site | - | claude-sonnet-5-5 | 27 | 29.948 | 54 | 45.009 | 5.852.776 | 0,08 |
| 2026-12-04 | Revisies: geschiedenis van berichten en pagina's, met terugzetten | - | claude-sonnet-5-5 | 6 | 12.423 | 12 | 14.609 | 1.461.419 | 0,03 |
| 2026-12-04 | De editor: opmaakknoppen, foto's in de tekst, voorbeeld en een scherpstelpunt in de bibliotheek | - | claude-sonnet-5-5 | 15 | 18.397 | 30 | 28.742 | 3.931.230 | 0,07 |
| 2026-12-04 | Het telscript en de Blade-component voor de publieke pagina's van de statistieken | - | claude-sonnet-5-5 | 8 | 9.037 | 16 | 15.948 | 2.254.948 | 0,04 |
| 2026-12-04 | Loginhaken: eigen velden en controles, en Turnstile | - | claude-sonnet-5-5 | 4 | 9.009 | 8 | 9.515 | 1.178.544 | 0,02 |
| 2026-12-04 | Rollen van de site naast de groepen van het pakket | - | claude-sonnet-5-5 | 3 | 5.308 | 6 | 8.235 | 921.246 | 0,01 |
| 2026-12-04 | Controle op namen die de site al gebruikt, en de documenten van 0.5.0 rechtgezet | - | claude-sonnet-5-5 | 9 | 7.281 | 18 | 12.115 | 2.881.457 | 0,03 |
| 2026-12-04 | Trivy uit de PR-jobs (schijf van de runners vol), opruimen en wekelijkse prune | - | claude-sonnet-5-5 | 20 | 9.723 | 44 | 94.863 | 1.460.150 | 0,15 |
| 2026-12-04 | Niets meer wekelijks: nachtelijke scan en updates, Trivy na een release, docs | - | claude-sonnet-5-5 | 27 | 19.377 | 58 | 41.226 | 2.879.048 | 0,63 |
| 2026-12-04 | Patch-release voor de nachtelijke renovate-update | - | claude-sonnet-5-5 | 24 | 17.609 | 54 | 35.165 | 3.038.359 | 0,16 |
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""Adds up the exact tokens of one or more Hermes sessions, for TOKENS.md.
Companion to `dev/token-usage.py` (which reads a Claude Code session log). This script is for work
done by a Hermes agent (any of the Aristocats): Hermes keeps its sessions in its own SQLite file,
`~/.hermes/state.db`, and has no `.jsonl` log, so a TOKENS.md row for Hermes work comes from this
script, never from a guess.
Usage: dev/token-usage-hermes.py SESSION_ID [SESSION_ID ...] [--include-children]
[--state-db PATH] [--date 2026-12-04]
[--row "Wat er is gemaakt" [--version v0.2.0]] [--hours 1.5]
Pass every session that did the work: the session of the agent itself and, with --include-children,
every session it started (a helper agent has `parent_session_id` set, also through several levels).
Helper agents are part of the work: their tokens are added to the row.
Like `dev/token-usage.py`, the row is made per model, because the price differs per model: when the
helper sessions ran on another model than the main session there is one row for each, the model with
the most steps first, and the hours are on the first row only.
There is no reliable signal for the time worked in state.db, so this script never invents the hours:
give them with --hours (a plain human figure: how long did the work take), or leave the cell empty and
fill it in by hand.
Standard library only.
"""
import argparse
import os
import sqlite3
import sys
from datetime import datetime, timezone
DEFAULT_STATE_DB = "~/.hermes/state.db"
def expand_children(con, seed_ids):
"""The given sessions plus every session whose parent is, through any number of levels, one of them."""
seen = set(seed_ids)
frontier = list(seed_ids)
while frontier:
placeholders = ",".join("?" for _ in frontier)
found = con.execute(f"SELECT id FROM sessions WHERE parent_session_id IN ({placeholders})", frontier).fetchall()
frontier = [row[0] for row in found if row[0] not in seen]
seen.update(frontier)
return sorted(seen)
def totals(con, session_ids):
"""Steps, output, input, written to the cache, read from the cache: in all and per model; and the ids not found."""
placeholders = ",".join("?" for _ in session_ids)
rows = con.execute(
f"""SELECT id, model, api_call_count, output_tokens, input_tokens, cache_write_tokens, cache_read_tokens
FROM sessions WHERE id IN ({placeholders})""",
list(session_ids),
).fetchall()
row = [0, 0, 0, 0, 0]
per_model = {}
for _id, model, *counts in rows:
add = [count or 0 for count in counts]
mine = per_model.setdefault(model or "?", [0, 0, 0, 0, 0])
for index, value in enumerate(add):
row[index] += value
mine[index] += value
return row, per_model, set(session_ids) - {row[0] for row in rows}
def number(value):
return f"{value:,}".replace(",", ".")
def show(name, row):
steps, out, new, written, read = row
print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}")
def lines(per_model, text, day, version, hours):
"""The rows for the table: one per model, the model with the most steps first, the hours on that row only."""
result = []
for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
if position > 0:
cell = "0,00"
else:
cell = "" if hours is None else f"{hours:.2f}".replace(".", ",")
cells = [day, text, version or "", model] + [number(value) for value in per_model[model]] + [cell]
result.append("| " + " | ".join(cells) + " |")
return result
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("session_ids", nargs="+")
parser.add_argument("--state-db", default=DEFAULT_STATE_DB)
parser.add_argument("--include-children", action="store_true")
parser.add_argument("--row")
parser.add_argument("--version", default="")
parser.add_argument("--date", default=datetime.now(timezone.utc).strftime("%Y-%m-%d"))
parser.add_argument("--hours", type=float, default=None)
args = parser.parse_args(argv)
path = os.path.expanduser(args.state_db)
if not os.path.exists(path):
sys.exit(f"No Hermes state file at {path} (use --state-db).")
con = sqlite3.connect(path)
session_ids = expand_children(con, args.session_ids) if args.include_children else args.session_ids
if args.include_children:
print(f"sessions counted (given + children): {', '.join(session_ids)}", file=sys.stderr)
row, per_model, missing = totals(con, session_ids)
if missing:
print(f"WARNING: not found in state.db, not counted: {', '.join(sorted(missing))}", file=sys.stderr)
show("sessions", row)
if args.row:
if not per_model:
per_model = {"?": [0, 0, 0, 0, 0]}
if args.hours is None:
print("NOTE: no --hours given: fill in the Uren cell by hand, do not invent a figure.", file=sys.stderr)
print("\n".join(lines(per_model, args.row, args.date, args.version, args.hours)))
if __name__ == "__main__":
main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Adds up the tokens of a Claude Code session log, for TOKENS.md.
Usage: dev/token-usage.py LOG.jsonl [--since 2026-12-02T07:00] [--until 2026-12-02T12:00]
[--row "Wat er is gemaakt" [--version v0.2.0]]
With --row it also prints the line(s) for the table of TOKENS.md, with the hours as the last cell.
Helper agents (subagents) are part of the work: their tokens are added to the row. The row is made
per model, because the price differs per model: when helper agents ran on another model than the
session, there is one row for each, and the hours are on the first row only.
The hours are the time that was worked in the period: from one entry of the log to the next,
the time between an answer and the next request included, pauses of more than half an hour
left out.
LOG.jsonl is the log of the session (~/.claude/projects/<folder>/<session>.jsonl); the logs of
helper agents in the folder `<session>/subagents` next to it are shown separately and also counted in the row. The moments
are UTC, as in the log. An answer of the model can be in the log more than once; it is counted
once, by its message id.
Standard library only.
"""
import glob
import json
import os
import sys
def answers(path):
"""The usage of every answer in a log, by message id, with its moment."""
found = {}
with open(path, encoding="utf-8") as log:
for line in log:
try:
entry = json.loads(line)
except ValueError:
continue
message = entry.get("message") or {}
if entry.get("type") == "assistant" and message.get("usage") and message.get("id"):
found[message["id"]] = (message["usage"], entry.get("timestamp", ""), message.get("model"))
# The advisor (another, stronger model) runs inside an answer: its tokens are in the
# iterations of that answer and are not part of the usage of the answer itself.
for number, iteration in enumerate(message["usage"].get("iterations") or []):
if iteration.get("type") == "advisor_message":
found[f'{message["id"]}:advisor:{number}'] = (iteration, entry.get("timestamp", ""), iteration.get("model"))
return found
PAUSE = 30 * 60
def hours(path, since, until):
"""The hours worked in the period, by the moments in the main log; pauses longer than PAUSE are left out."""
from datetime import datetime
moments = []
with open(path, encoding="utf-8", errors="replace") as log:
for line in log:
try:
entry = json.loads(line)
except ValueError:
continue
if entry.get("isSidechain") or entry.get("type") not in ("user", "assistant") or not entry.get("timestamp"):
continue
moments.append(entry["timestamp"])
moments.sort()
seconds = 0.0
for start, end in zip(moments, moments[1:]):
# A step counts for the period it starts in.
if (since and start[:16] < since) or (until and start[:16] >= until):
continue
gap = (datetime.fromisoformat(end.replace("Z", "+00:00")) - datetime.fromisoformat(start.replace("Z", "+00:00"))).total_seconds()
if gap <= PAUSE:
seconds += gap
return seconds / 3600
def total(found, since, until):
"""Steps, output, input, written to the cache, read from the cache; and the same per model."""
row = [0, 0, 0, 0, 0]
per_model = {}
for usage, moment, model in found.values():
if (since and moment[:16] < since) or (until and moment[:16] >= until):
continue
# Entries the client made itself (model "<synthetic>") hold no tokens and no work.
if model and model.startswith("<"):
continue
add = [
1,
usage.get("output_tokens", 0),
usage.get("input_tokens", 0),
usage.get("cache_creation_input_tokens", 0),
usage.get("cache_read_input_tokens", 0),
]
model = model or "?"
mine = per_model.setdefault(model, [0, 0, 0, 0, 0])
for index, value in enumerate(add):
row[index] += value
mine[index] += value
return row, per_model
def number(value):
return f"{value:,}".replace(",", ".")
def show(name, row):
steps, out, new, written, read = row
print(f"{name}: {steps} steps | output {number(out)} | input {number(new)} | cache written {number(written)} | cache read {number(read)} | together {number(out + new + written + read)}")
def main():
args = sys.argv[1:]
names = ("--since", "--until", "--row", "--version")
option = lambda name: args[args.index(name) + 1] if name in args else None
since, until = option("--since"), option("--until")
paths = [arg for index, arg in enumerate(args) if arg not in names and (index == 0 or args[index - 1] not in names)]
if len(paths) != 1:
sys.exit(__doc__)
session = answers(paths[0])
row, _ = total(session, since, until)
show("session", row)
worked_hours = hours(paths[0], since, until)
print(f"hours worked: {worked_hours:.2f}")
helpers = {}
for path in glob.glob(os.path.join(os.path.splitext(paths[0])[0], "subagents", "*.jsonl")):
helpers.update(answers(path))
if helpers:
show("helper agents", total(helpers, since, until)[0])
if option("--row"):
# Session and helper agents together, one row per model.
everything = {**session, **{"helper:" + key: value for key, value in helpers.items()}}
_, per_model = total(everything, since, until)
if not per_model:
per_model = {"?": [0, 0, 0, 0, 0]}
day = (since or "")[:10] or "JJJJ-MM-DD"
# The model with the most steps first; the hours go on that row only.
for position, model in enumerate(sorted(per_model, key=lambda name: -per_model[name][0])):
worked = f"{worked_hours:.2f}" if position == 0 else "0.00"
cells = [day, option("--row"), option("--version") or "", model] + [number(value) for value in per_model[model]] + [worked.replace(".", ",")]
print("| " + " | ".join(cells) + " |")
if __name__ == "__main__":
main()
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="vendor/autoload.php" colors="true">
<testsuites>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site with every module switched on. */
abstract class AllModulesTestCase extends TestCase
{
protected array $modules = ['reviews' => true, 'audit' => true, 'statistics' => true, 'pages' => true, 'posts' => true];
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site that switched the optional audit log on (and reviews, so every module is on). */
abstract class AuditOnTestCase extends TestCase
{
protected array $modules = ['audit' => true, 'reviews' => true, 'statistics' => true];
protected function defineEnvironment($app): void
{
parent::defineEnvironment($app);
$app['config']->set('manager.audit.never_ban', ['10.9.9.9']);
$app['config']->set('manager.audit.whole_site_bans', true);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
use Illuminate\Auth\Events\Failed;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
it('has no audit log, bans, tables or rights unless the site switched it on', function () {
expect(Route::has('manager.audit.index'))->toBeFalse()
->and(Schema::hasTable('manager_audit_logs'))->toBeFalse()
->and(Schema::hasTable('manager_ip_bans'))->toBeFalse()
->and(Manager::permissionValues())->not->toContain('audit.view', 'audit.manage');
// A failed login goes by without a trace, and without a table to write to.
event(new Failed('web', null, ['email' => '[email protected]']));
});
it('does not schedule the prune command when the audit log is off', function () {
$commands = collect(app(Schedule::class)->events())->map(fn ($event) => $event->command)->implode(' ');
expect($commands)->not->toContain('manager:audit-prune');
});
+298
View File
@@ -0,0 +1,298 @@
<?php
use Illuminate\Auth\Events\Failed;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Models\AuditLog;
use IriksIT\Manager\Models\AuditSetting;
use IriksIT\Manager\Models\IpBan;
use IriksIT\Manager\Models\IpNote;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Modules\Audit\IpBans;
use IriksIT\Manager\Tests\AuditOnTestCase;
uses(AuditOnTestCase::class);
function fromAddress(string $ip): array
{
return ['REMOTE_ADDR' => $ip];
}
function failLogin(string $ip, int $times = 1): void
{
for ($i = 0; $i < $times; $i++) {
request()->server->set('REMOTE_ADDR', $ip);
event(new Failed('web', null, ['email' => '[email protected]']));
}
}
describe('what is switched on', function () {
it('has the tables, routes and rights of the audit log', function () {
expect(Route::has('manager.audit.index'))->toBeTrue()
->and(Schema::hasTable('manager_audit_logs'))->toBeTrue()
->and(Schema::hasTable('manager_ip_bans'))->toBeTrue()
->and(Manager::permissionValues())->toContain('audit.view', 'audit.manage');
});
it('gives every route of the manager a name in the log', function () {
$labelled = [...array_keys(Manager::actions()), ...array_keys(Manager::views())];
$missing = collect(Route::getRoutes()->getRoutes())
->filter(fn ($route) => str_starts_with($route->uri(), config('manager.path').'/') || $route->uri() === config('manager.path'))
->map(fn ($route) => $route->getName())
->filter(fn ($name) => is_string($name) && str_starts_with($name, 'manager.'))
->map(fn ($name) => substr($name, 8))
// The login and the built files are outside `auth` (nobody is known there); a logout is logged by Laravel's Logout event.
->reject(fn ($name) => $name === '' || in_array($name, [...$labelled, 'assets', 'login', 'login.store', 'logout', 'markdown.preview'], true))
->values()->all();
expect($missing)->toBe([]);
});
});
describe('logins', function () {
it('writes down a login, a logout and a failed login', function () {
$user = makeUser(name: 'Ada');
event(new Login('web', $user, false));
event(new Logout('web', $user));
event(new Failed('web', $user, ['email' => $user->email]));
expect(AuditLog::orderBy('id')->pluck('event')->all())->toBe(['login', 'logout', 'login_failed']);
expect(AuditLog::where('event', 'login')->sole()->user_name)->toBe('Ada');
expect(AuditLog::where('event', 'login_failed')->sole()->email)->toBe($user->email);
});
it('bans an address after too many failed logins, and not one that is never banned', function () {
failLogin('10.0.0.5', 9);
expect(IpBan::count())->toBe(0);
failLogin('10.0.0.5');
$ban = IpBan::sole();
expect($ban->ip)->toBe('10.0.0.5')->and($ban->automatic)->toBeTrue()->and($ban->whole_site)->toBeFalse();
failLogin('10.9.9.9', 30);
expect(IpBan::where('ip', '10.9.9.9')->exists())->toBeFalse();
});
it('does not ban by itself when the rule is off', function () {
AuditSetting::current()->forceFill(['id' => 1, 'auto_ban' => false])->save();
failLogin('10.0.0.6', 30);
expect(IpBan::count())->toBe(0);
});
});
describe('what an account does', function () {
beforeEach(fn () => $this->actingAs(makeUser(['posts.view', 'posts.write'], name: 'Writer')));
it('writes down a change with what it made', function () {
$this->postJson('/manager/posts', ['title' => 'Hello', 'body' => 'Text', 'is_published' => false])->assertCreated();
$line = AuditLog::where('event', 'action')->sole();
expect($line->summary)->toBe('Created a post')
->and($line->user_name)->toBe('Writer')
->and($line->subject_type)->toBe('post')
->and($line->subject_label)->toBe('Hello')
->and($line->ip)->not->toBeNull();
});
it('writes down a page that is opened once within five minutes', function () {
$this->getJson('/manager/posts')->assertOk();
$this->getJson('/manager/posts')->assertOk();
expect(AuditLog::where('event', 'viewed')->sole()->summary)->toBe('Opened the posts');
});
it('writes down what the account was not allowed to do, and not a form with a mistake', function () {
$this->deleteJson('/manager/posts/1')->assertForbidden();
$this->postJson('/manager/posts', [])->assertStatus(422);
expect(AuditLog::where('event', 'refused')->sole()->summary)->toBe('Was not allowed: deleted a post')
->and(AuditLog::where('event', 'action')->count())->toBe(0);
});
it('never keeps what was typed, only the fields a module listed', function () {
$this->actingAs(makeUser(['posts.view', 'posts.labels']));
$this->postJson('/manager/labels', ['type' => 'tag', 'name' => 'secret-ish', 'password' => 'hunter2'])->assertCreated();
$line = AuditLog::where('action', 'labels.store')->sole();
expect($line->details)->toBe(['input' => ['type' => 'tag', 'name' => 'secret-ish']]);
expect(json_encode(AuditLog::all()))->not->toContain('hunter2');
});
});
describe('subjects of changes and deletes', function () {
it('names what was changed and what was deleted', function () {
$this->actingAs(makeUser(['posts.view', 'posts.write', 'posts.delete'], name: 'Editor'));
$post = Post::create(['title' => 'Old title', 'slug' => 'old', 'body' => 'x']);
$this->putJson("/manager/posts/{$post->id}", ['title' => 'New title', 'body' => 'x', 'is_published' => false])->assertOk();
$this->deleteJson("/manager/posts/{$post->id}")->assertOk();
expect(AuditLog::where('action', 'posts.update')->sole()->subject_label)->toBe('New title')
->and(AuditLog::where('action', 'posts.destroy')->sole()->subject_label)->toBe('New title');
});
});
describe('the prune schedule', function () {
it('runs daily when the audit log is on', function () {
$commands = collect(app(Schedule::class)->events())->map(fn ($event) => $event->command)->implode(' ');
expect($commands)->toContain('manager:audit-prune');
});
});
describe('seeing the log', function () {
it('needs audit.view', function () {
$this->actingAs(makeUser());
$this->getJson('/manager/audit')->assertForbidden();
$this->actingAs(makeUser(['audit.view']));
$this->getJson('/manager/audit')->assertOk()->assertJsonPath('can_manage', false);
});
it('filters the lines and pages through them', function () {
$user = makeUser(['audit.view'], name: 'Viewer');
event(new Failed('web', null, ['email' => '[email protected]']));
event(new Login('web', $user, false));
$this->actingAs($user);
$this->getJson('/manager/audit?show=failed')->assertOk()
->assertJsonCount(1, 'entries')->assertJsonPath('entries.0.event', 'login_failed')
->assertJsonPath('summary.logins', 1)->assertJsonPath('summary.failed', 1);
});
it('links a line to its post only while the post exists', function () {
$post = Post::create(['title' => 'Linked', 'slug' => 'linked', 'body' => 'x']);
$this->actingAs(makeUser(['audit.view', 'posts.write']));
$this->postJson('/manager/posts', ['title' => 'Another', 'body' => 'x', 'is_published' => false])->assertCreated();
$url = $this->getJson('/manager/audit?show=actions')->json('entries.0.subject.url');
expect($url)->toBe('/manager/posts/'.Post::where('title', 'Another')->value('id').'/edit')->and($post->exists)->toBeTrue();
});
});
describe('bans', function () {
beforeEach(fn () => $this->actingAs(makeUser(['audit.view', 'audit.manage'], name: 'Boss')));
it('bans by hand, writes it down, and lifts it again', function () {
$this->postJson('/manager/audit/bans', ['ip' => '10.1.1.1', 'reason' => 'Scraper', 'minutes' => 0])->assertCreated();
$ban = IpBan::sole();
expect($ban->automatic)->toBeFalse()->and($ban->expires_at)->toBeNull()->and($ban->user_name)->toBe('Boss');
expect(AuditLog::where('action', 'audit.bans.store')->sole()->subject_label)->toBe('10.1.1.1');
$this->deleteJson("/manager/audit/bans/{$ban->id}")->assertOk();
expect(IpBan::count())->toBe(0);
});
it('needs audit.manage to ban', function () {
$this->actingAs(makeUser(['audit.view']));
$this->postJson('/manager/audit/bans', ['ip' => '10.1.1.1', 'minutes' => 0])->assertForbidden();
});
it('refuses to ban yourself or an address that is never banned', function () {
$this->postJson('/manager/audit/bans', ['ip' => '127.0.0.1', 'minutes' => 0])->assertStatus(422)->assertJsonValidationErrors('ip');
$this->postJson('/manager/audit/bans', ['ip' => '10.9.9.9', 'minutes' => 0])->assertStatus(422)->assertJsonValidationErrors('ip');
expect(IpBan::count())->toBe(0);
});
it('bans and lifts a whole group of addresses', function () {
foreach (['10.2.0.1', '10.2.0.2', '127.0.0.1'] as $ip) {
$this->putJson('/manager/audit/notes', ['ip' => $ip, 'note' => 'farm', 'group' => 'Farm'])->assertOk();
}
$this->postJson('/manager/audit/groups/ban', ['group' => 'Farm', 'minutes' => 60])->assertCreated()
->assertJsonPath('banned', 2)->assertJsonPath('skipped', 1);
expect(IpBan::count())->toBe(2);
$this->postJson('/manager/audit/groups/unban', ['group' => 'Farm'])->assertOk()->assertJsonPath('lifted', 2);
expect(IpBan::count())->toBe(0);
});
it('writes and removes the note about an address', function () {
$this->putJson('/manager/audit/notes', ['ip' => '::1', 'note' => 'home'])->assertOk();
expect(IpNote::sole()->note)->toBe('home');
$this->putJson('/manager/audit/notes', ['ip' => '::1', 'note' => '', 'group' => ''])->assertOk();
expect(IpNote::count())->toBe(0);
});
it('keeps the log no longer than the site promises', function () {
$rules = ['auto_ban' => true, 'max_failures' => 5, 'window_minutes' => 10, 'ban_minutes' => 0];
$this->putJson('/manager/audit/settings', [...$rules, 'keep_days' => 91])->assertStatus(422)->assertJsonValidationErrors('keep_days');
$this->putJson('/manager/audit/settings', [...$rules, 'keep_days' => 30])->assertOk();
expect(AuditSetting::current()->rules()['keep_days'])->toBe(30);
});
});
describe('a banned address', function () {
it('is kept out of the manager with a 403, or a 429 when it was banned by itself', function () {
app(IpBans::class)->ban('10.3.0.1', 'Scraper', 0, null);
failLogin('10.3.0.2', 10);
$this->actingAs(makeUser(superAdmin: true));
$this->getJson('/manager/posts', fromAddress('10.3.0.1'))->assertForbidden();
$this->getJson('/manager/posts', fromAddress('10.3.0.2'))->assertStatus(429)->assertHeader('Retry-After');
$this->get('/manager/posts', fromAddress('10.3.0.1'))->assertForbidden()->assertSee('blocked from the manager');
$this->getJson('/manager/posts', fromAddress('10.3.0.9'))->assertOk();
expect(IpBan::where('ip', '10.3.0.1')->value('hits'))->toBe(2);
});
it('gets the banned answer, not the login page, as a guest', function () {
app(IpBans::class)->ban('10.3.2.1', null, 0, null);
$this->getJson('/manager/posts', fromAddress('10.3.2.1'))->assertForbidden();
$this->getJson('/manager/posts', fromAddress('10.3.2.2'))->assertUnauthorized();
});
it('is let back in when the ban ends or is lifted on the server', function () {
app(IpBans::class)->ban('10.3.1.1', null, 10, null);
$this->actingAs(makeUser(superAdmin: true));
$this->travel(11)->minutes();
$this->getJson('/manager/posts', fromAddress('10.3.1.1'))->assertOk();
app(IpBans::class)->ban('10.3.1.2', null, 0, null);
$this->artisan('manager:unban', ['ip' => '10.3.1.2'])->assertSuccessful();
$this->getJson('/manager/posts', fromAddress('10.3.1.2'))->assertOk();
});
it('is kept off the whole site by a ban for the whole site, and no other address', function () {
Route::get('/hello', fn () => 'hello');
app(IpBans::class)->ban('10.4.0.1', null, 0, null, wholeSite: true);
app(IpBans::class)->ban('10.4.0.2', null, 0, null);
$this->get('/hello', fromAddress('10.4.0.1'))->assertForbidden();
$this->get('/hello', fromAddress('10.4.0.2'))->assertOk();
$this->get('/hello', fromAddress('10.4.0.3'))->assertOk();
});
});
describe('pruning', function () {
it('deletes old lines and ended bans, and keeps the notes', function () {
AuditLog::create(['event' => 'login', 'summary' => 'old', 'created_at' => now()->subDays(120)]);
AuditLog::create(['event' => 'login', 'summary' => 'new', 'created_at' => now()->subDays(10)]);
IpBan::create(['ip' => '10.5.0.1', 'expires_at' => now()->subDays(100), 'created_at' => now()->subDays(101)]);
IpBan::create(['ip' => '10.5.0.2', 'expires_at' => null, 'created_at' => now()->subDays(101)]);
IpNote::create(['ip' => '10.5.0.1', 'note' => 'stays']);
$this->artisan('manager:audit-prune')->assertSuccessful();
expect(AuditLog::pluck('summary')->all())->toBe(['new'])
->and(IpBan::pluck('ip')->all())->toBe(['10.5.0.2'])
->and(IpNote::count())->toBe(1);
});
});
+96
View File
@@ -0,0 +1,96 @@
<?php
use Illuminate\Support\Facades\Artisan;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
// The installer publishes the config into the app, here the skeleton in vendor/: leave it as it was.
beforeEach(function () {
$this->hadConfig = file_exists(config_path('manager.php'));
$this->env = file_exists(base_path('.env')) ? file_get_contents(base_path('.env')) : null;
});
afterEach(function () {
$this->hadConfig || @unlink(config_path('manager.php'));
$this->env === null ? @unlink(base_path('.env')) : file_put_contents(base_path('.env'), $this->env);
});
function doctorReport(): array
{
Artisan::call('manager:doctor', ['--json' => true]);
return json_decode(Artisan::output(), true);
}
it('reports a healthy setup as JSON with exit code 0', function () {
$report = doctorReport();
$status = collect($report['checks'])->pluck('status', 'check');
expect($status['user_trait'])->toBe('ok')
->and($status['tables'])->toBe('ok')
->and($status['routes'])->toBe('ok')
->and($report['ok'])->toBeTrue();
});
it('fails with a fix when the user model is not a class', function () {
config(['manager.user_model' => 'Nope\\User']);
$check = collect(doctorReport()['checks'])->firstWhere('check', 'user_model');
expect($check['status'])->toBe('fail')->and($check['fix'])->toContain('MANAGER_USER_MODEL');
expect(Artisan::call('manager:doctor'))->toBe(1);
});
it('warns when there is no super admin yet', function () {
$check = collect(doctorReport()['checks'])->firstWhere('check', 'super_admin');
expect($check['status'])->toBe('warn')->and($check['fix'])->toContain('manager:create-user');
});
it('lists the tables of the active modules', function () {
$tables = collect(app(ModuleRegistry::class)->active())->flatMap->tables();
expect($tables)->toContain('media', 'posts');
});
it('refuses an unknown module in the installer', function () {
expect(Artisan::call('manager:install', ['--modules' => 'users,nonsense']))->toBe(1);
});
it('writes the switches to .env', function () {
$env = base_path('.env');
Artisan::call('manager:install', ['--modules' => 'users,media,posts', '--path' => 'admin']);
$written = file_get_contents($env);
expect($written)->toContain('MANAGER_PATH=admin')->toContain('MANAGER_AUDIT=false')->toContain('MANAGER_POSTS=true');
});
it('leaves the check to a new process after it changed the switches', function () {
Artisan::call('manager:install', ['--path' => 'admin']);
expect(Artisan::output())->toContain('manager:doctor')->not->toContain('[OK]');
});
it('finds no shared names in a clean setup', function () {
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
expect($check['message'])->toBe('No route name or address is shared with the site.');
});
it('warns when the site uses a route name of the manager, and says what to set', function () {
Route::get('/home', fn () => 'x')->name('manager.dashboard');
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
expect($check['status'])->toBe('warn')->and($check['message'])->toContain('manager.dashboard')->and($check['fix'])->toContain('route_name');
});
it('warns when the site has routes under the address of the manager', function () {
Route::get('/manager/reports', fn () => 'x');
$check = collect(doctorReport()['checks'])->firstWhere('check', 'names');
expect($check['status'])->toBe('warn')->and($check['message'])->toContain('manager/reports');
});
+25
View File
@@ -0,0 +1,25 @@
<?php
use IriksIT\Manager\Models\AuditLog;
use IriksIT\Manager\Tests\AuditOnTestCase;
uses(AuditOnTestCase::class);
it('renders the preview the way the site does, with raw HTML escaped', function () {
$this->actingAs(makeUser(['posts.view']));
$html = $this->postJson('/manager/markdown', ['text' => "## Hi\n\n**bold** ![alt](/media/a.jpg)\n\n<script>alert(1)</script>"])->assertOk()->json('html');
expect($html)->toContain('<h2>Hi</h2>', '<strong>bold</strong>', '<img src="/media/a.jpg" alt="alt"')
->and($html)->not->toContain('<script>');
});
it('answers only to those who are logged in, and is not written in the audit log', function () {
$this->postJson('/manager/markdown', ['text' => 'x'])->assertUnauthorized();
$this->actingAs(makeUser(['posts.view']));
$this->postJson('/manager/markdown', ['text' => 'x'])->assertOk();
$this->postJson('/manager/markdown', ['text' => str_repeat('a', 200001)])->assertJsonValidationErrors(['text']);
expect(AuditLog::query()->where('action', 'markdown.preview')->count())->toBe(0);
});
+28
View File
@@ -0,0 +1,28 @@
<?php
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
it('loads the bundle of the site next to its own, and maps vue to the Vue of the screens', function () {
config(['manager.extensions' => ['/build/manager-extra.js', 'https://cdn.example.com/x.js', 'javascript:alert(1)', '//evil.example/x.js', 'http://plain.example/x.js', '/a b.js']]);
$this->actingAs(makeUser(superAdmin: true));
$html = $this->get('/manager')->assertOk()->getContent();
expect($html)->toContain('"extensions":["/build/manager-extra.js","https://cdn.example.com/x.js"]');
expect($html)->toContain('type="importmap"')->and($html)->toContain('/manager/_assets/vue.js')
->and($html)->not->toContain('javascript:alert')->and($html)->not->toContain('evil.example')->and($html)->not->toContain('plain.example');
});
it('has no import map when the site has no bundle', function () {
$this->actingAs(makeUser(superAdmin: true));
expect($this->get('/manager')->getContent())->not->toContain('importmap');
});
it('serves the vue shim and the screens', function () {
$this->get('/manager/_assets/vue.js')->assertOk()->assertHeader('Content-Type', 'application/javascript');
$this->get('/manager/_assets/manager.js')->assertOk();
$this->get('/manager/_assets/other.js')->assertNotFound();
});
+74
View File
@@ -0,0 +1,74 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Models\Review;
use IriksIT\Manager\Tests\ReviewsOnTestCase;
uses(ReviewsOnTestCase::class);
beforeEach(function () {
Schema::create('articles', function ($table) {
$table->id();
$table->string('headline')->nullable();
$table->string('url_name')->nullable();
$table->text('content')->nullable();
$table->string('labels')->nullable();
$table->string('published')->nullable();
});
DB::table('articles')->insert([
['headline' => 'First news', 'url_name' => null, 'content' => 'Hello', 'labels' => 'a, b', 'published' => '2026-01-02 10:00:00'],
['headline' => 'Draft', 'url_name' => 'my-draft', 'content' => 'Later', 'labels' => '["x"]', 'published' => null],
['headline' => 'No text', 'url_name' => 'no-text', 'content' => '', 'labels' => null, 'published' => null],
]);
$this->map = ['--map' => ['title=headline', 'slug=url_name', 'body=content', 'tags=labels', 'published_at=published']];
});
it('copies rows into the package and repeats without duplicating', function () {
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles'] + $this->map)
->expectsOutputToContain('2 created, 0 updated, 1 skipped')->assertSuccessful();
expect(Post::query()->count())->toBe(2)
->and(Post::query()->where('slug', 'first-news')->first()->tags)->toBe(['a', 'b'])
->and(Post::query()->where('slug', 'my-draft')->first()->tags)->toBe(['x'])
->and(Post::query()->where('slug', 'my-draft')->first()->published_at)->toBeNull();
DB::table('articles')->where('url_name', 'my-draft')->update(['content' => 'Changed']);
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles'] + $this->map)
->expectsOutputToContain('0 created, 2 updated, 1 skipped');
expect(Post::query()->count())->toBe(2)
->and(Post::query()->where('slug', 'my-draft')->value('body'))->toBe('Changed');
});
it('writes nothing on a dry run and never touches the source', function () {
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles', '--dry-run' => true] + $this->map)
->expectsOutputToContain('Dry run: 2 created');
expect(Post::query()->count())->toBe(0)->and(DB::table('articles')->count())->toBe(3);
});
it('refuses what it does not know', function () {
$this->artisan('manager:import', ['target' => 'cars', '--table' => 'articles'])->assertFailed();
$this->artisan('manager:import', ['target' => 'posts', '--table' => 'articles', '--map' => ['colour=x']])->assertFailed();
$this->artisan('manager:import', ['target' => 'posts'])->assertFailed();
});
it('reads its settings from the config and imports reviews', function () {
Schema::create('quotes', function ($table) {
$table->id();
$table->string('who');
$table->text('said');
$table->integer('stars')->nullable();
});
DB::table('quotes')->insert([['who' => 'A', 'said' => 'Fine', 'stars' => 9]]);
config(['manager.import.reviews' => ['table' => 'quotes', 'map' => ['author' => 'who', 'body' => 'said', 'rating' => 'stars']]]);
$this->artisan('manager:import', ['target' => 'reviews'])->assertSuccessful();
expect(Review::query()->first()->rating)->toBe(5);
});
+89
View File
@@ -0,0 +1,89 @@
<?php
use Illuminate\Auth\Events\Failed;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Validation\ValidationException;
use IriksIT\Manager\Support\Login\BaseLoginCheck;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
class NeedsCode extends BaseLoginCheck
{
public function fields(): array
{
return [['name' => 'code', 'type' => 'text', 'label' => 'Code', 'autocomplete' => 'one-time-code']];
}
public function after(Request $request, Authenticatable $user): void
{
if ($request->input('code') !== '123456') {
throw ValidationException::withMessages(['code' => 'The code is not right.']);
}
}
}
beforeEach(function () {
$this->user = makeUser(superAdmin: true);
$this->user->forceFill(['password' => Hash::make('a-long-enough-password')])->save();
$this->login = fn (array $extra = []) => $this->postJson('/manager/login', ['email' => $this->user->email, 'password' => 'a-long-enough-password'] + $extra);
});
it('logs in as before when no check is set', function () {
($this->login)()->assertOk()->assertJsonPath('redirect', '/manager');
$this->assertAuthenticated();
});
it('asks a second factor of the site after the password, and counts a refusal as a failed login', function () {
config(['manager.login.checks' => [NeedsCode::class]]);
$failed = 0;
Event::listen(Failed::class, function () use (&$failed) {
$failed++;
});
($this->login)(['code' => '000000'])->assertJsonValidationErrors(['code']);
$this->assertGuest();
expect($failed)->toBe(1);
($this->login)(['code' => '123456'])->assertOk();
$this->assertAuthenticated();
});
it('shows the fields of the checks on the form', function () {
config(['manager.login.checks' => [NeedsCode::class, 'Not\\A\\Check']]);
$this->get('/manager/login')->assertOk()->assertSee('"login_fields":[{"name":"code"', false);
});
describe('turnstile', function () {
beforeEach(fn () => config(['manager.login.turnstile' => ['site_key' => 'site-key', 'secret' => 'secret-key']]));
it('needs a token that Cloudflare accepts, and checks before the password', function () {
Http::fake(['challenges.cloudflare.com/*' => Http::response(['success' => true])]);
($this->login)()->assertJsonValidationErrors(['turnstile']);
($this->login)(['turnstile' => 'token'])->assertOk();
Http::assertSent(fn ($request) => $request['secret'] === 'secret-key' && $request['response'] === 'token');
});
it('refuses a token Cloudflare does not accept, and everything when Cloudflare is unreachable', function () {
Http::fake(['challenges.cloudflare.com/*' => Http::response(['success' => false])]);
($this->login)(['turnstile' => 'bad'])->assertJsonValidationErrors(['turnstile']);
Http::fake(['challenges.cloudflare.com/*' => Http::response('', 500)]);
($this->login)(['turnstile' => 'token'])->assertJsonValidationErrors(['turnstile']);
Http::fake(fn () => throw new ConnectionException('down'));
($this->login)(['turnstile' => 'token'])->assertJsonValidationErrors(['turnstile']);
$this->assertGuest();
});
it('puts the widget on the form', function () {
$this->get('/manager/login')->assertSee('"type":"turnstile","site_key":"site-key"', false);
});
});
+14
View File
@@ -0,0 +1,14 @@
<?php
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Tests\MediaOffTestCase;
uses(MediaOffTestCase::class);
it('has no routes, no public file route and no table for a site without media', function () {
expect(Route::has('manager.media.index'))->toBeFalse()
->and(Route::has('manager.media.file'))->toBeFalse()
->and(Schema::hasTable('manager_media'))->toBeFalse();
$this->get('/media-files/1/x.png/view')->assertNotFound();
});
+128
View File
@@ -0,0 +1,128 @@
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use IriksIT\Manager\Models\Media;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
function png(string $name = 'My Photo.png'): UploadedFile
{
return UploadedFile::fake()->createWithContent($name, file_get_contents(__DIR__.'/../Fixtures/pixel.png'));
}
beforeEach(function () {
Storage::fake('public');
$this->actingAs(makeUser(['media.delete', 'media.edit', 'media.upload']));
});
describe('uploading', function () {
it('stores a file on the disk and records it', function () {
$item = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.3, 'focus_y' => 0.65])->assertCreated()->json('item');
$media = Media::sole();
Storage::disk('public')->assertExists($media->location);
expect($item['url'])->toBe("/media-files/{$media->id}/my-photo.png/view")
->and($item)->not->toHaveKeys(['disk', 'location'])
->and($media->name)->toBe('My Photo')
->and($media->width)->toBe(1)
->and($media->checksum)->toBe(hash_file('sha256', __DIR__.'/../Fixtures/pixel.png'))
->and($media->focus_x)->toBe(0.3)
->and(Media::focusFor($item['url']))->toBe('30% 65%')
->and(Media::focusFor('/somewhere/else'))->toBeNull();
});
it('refuses what is not allowed: svg, too big, no room', function () {
$svg = UploadedFile::fake()->createWithContent('x.svg', '<svg xmlns="http://www.w3.org/2000/svg"/>');
$this->postJson('/manager/media', ['file' => $svg])->assertJsonValidationErrors('file');
config(['manager.media.max_file_mb' => 1]);
$this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('big.pdf', 2048, 'application/pdf')])->assertJsonValidationErrors('file');
config(['manager.media.max_total_gb' => 0.000001]);
$this->postJson('/manager/media', ['file' => UploadedFile::fake()->create('a.pdf', 5, 'application/pdf')])->assertStatus(422)->assertJsonPath('storage.limit', 1000);
expect(Media::count())->toBe(0);
});
it('needs the permission', function () {
$this->actingAs(makeUser(['media.view']));
$this->postJson('/manager/media', ['file' => png()])->assertForbidden();
$this->getJson('/manager/media/items')->assertOk();
});
});
describe('changing and deleting', function () {
it('renames and keeps the focus point unless one is sent', function () {
$id = $this->postJson('/manager/media', ['file' => png(), 'focus_x' => 0.1, 'focus_y' => 0.2])->json('item.id');
$this->putJson("/manager/media/{$id}", ['name' => 'New', 'alt' => ' A cat '])->assertOk()->assertJsonPath('item.alt', 'A cat');
expect(Media::find($id)->focus_y)->toBe(0.2);
$this->putJson("/manager/media/{$id}", ['name' => 'New', 'focus_x' => 0.5])->assertJsonValidationErrors('focus_y');
});
it('deletes the file and the row', function () {
$this->postJson('/manager/media', ['file' => png()]);
$media = Media::sole();
$this->deleteJson("/manager/media/{$media->id}")->assertOk();
Storage::disk('public')->assertMissing($media->location);
expect(Media::count())->toBe(0);
});
});
describe('usage', function () {
it('counts where a file is used, through the registered sources of the modules that are on', function () {
$id = $this->postJson('/manager/media', ['file' => png()])->json('item.id');
Post::create(['slug' => 'a', 'title' => 'A', 'body' => "See ![x](/media-files/{$id}/my-photo.png/view)"]);
expect(collect($this->getJson('/manager/media/items')->json('items'))->firstWhere('id', $id)['usage_count'])->toBe(1);
});
});
describe('the file for visitors', function () {
beforeEach(function () {
$this->postJson('/manager/media', ['file' => png()]);
$this->media = Media::sole();
auth()->logout();
$this->app['auth']->forgetGuards();
});
it('is served without logging in, with caching headers', function () {
$response = $this->get($this->media->url())->assertOk()->assertHeader('Content-Type', 'image/png');
expect($response->headers->get('Cache-Control'))->toContain('immutable')
->and($response->headers->get('X-Content-Type-Options'))->toBe('nosniff')
->and($response->headers->has('Set-Cookie'))->toBeFalse()
->and($response->streamedContent())->toBe(file_get_contents(__DIR__.'/../Fixtures/pixel.png'));
});
it('answers 304 for a known ETag and a part for a range', function () {
$etag = '"'.$this->media->checksum.'"';
$this->get($this->media->url(), ['If-None-Match' => $etag])->assertStatus(304);
$part = $this->get($this->media->url(), ['Range' => 'bytes=0-9'])->assertStatus(206)->assertHeader('Content-Range', "bytes 0-9/{$this->media->size}");
expect($part->streamedContent())->toBe(substr(file_get_contents(__DIR__.'/../Fixtures/pixel.png'), 0, 10));
$this->get($this->media->url(), ['Range' => 'bytes=9999-'])->assertStatus(416);
});
it('offers anything that is not a safe type as a download', function () {
$this->media->update(['mime_type' => 'text/html']);
$this->get($this->media->url())->assertHeader('Content-Type', 'application/octet-stream')
->assertHeader('Content-Disposition', 'attachment; filename="my-photo.png"');
});
it('is 404 when the row or the file is gone', function () {
$this->get('/media-files/9999/x.png/view')->assertNotFound();
Storage::disk('public')->delete($this->media->location);
$this->get($this->media->url())->assertNotFound();
});
});
+68
View File
@@ -0,0 +1,68 @@
<?php
use IriksIT\Manager\Models\UserSetting;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Tests\SimpleViewTestCase;
uses(SimpleViewTestCase::class);
function menuOf($test, $user): array
{
return $test->actingAs($user)->getJson('/manager')->assertOk()->json('navigation');
}
it('puts sections, icons and order on the menu, and adds links of the site', function () {
config(['manager.menu.links' => [['label' => 'Leads', 'url' => '/manager/leads', 'section' => 'Content', 'order' => 6, 'new_tab' => true]]]);
config(['manager.menu.items' => [...config('manager.menu.items'), 'labels.index' => ['hidden' => true]]]);
$items = collect(app(ModuleRegistry::class)->navigation());
expect($items->first())->toMatchArray(['label' => 'Posts', 'section' => 'Content', 'icon' => 'file', 'order' => 5, 'simple' => true])
->and($items->pluck('label')->slice(0, 2)->values()->all())->toBe(['Posts', 'Leads'])
->and($items->pluck('label'))->not->toContain('Categories and tags')
->and($items->firstWhere('label', 'Leads'))->toMatchArray(['url' => '/manager/leads', 'new_tab' => true]);
});
it('keeps the old shape of a menu item working', function () {
$item = collect(app(ModuleRegistry::class)->navigation())->firstWhere('label', 'Media');
expect($item)->toMatchArray(['label' => 'Media', 'permission' => 'media.view', 'simple' => false, 'order' => 100])
->and($item['route'])->toBe('manager.media.index');
});
it('shows an account with only the switch permission the simple face first, and lets it change', function () {
$user = makeUser(['posts.view', 'media.view', 'manager.switch']);
expect(collect(menuOf($this, $user))->pluck('label')->all())->toBe(['Posts']);
$this->putJson('/manager/profile/view', ['view' => 'full'])->assertOk();
expect(collect(menuOf($this, $user))->pluck('label')->all())->toBe(['Posts', 'Media'])
->and(UserSetting::query()->where('user_id', $user->id)->value('view'))->toBe('full');
$this->putJson('/manager/profile/view', ['view' => 'nonsense'])->assertUnprocessable();
});
it('gives the full face to an account with the full permission, and the simple face to all others for good', function () {
$full = makeUser(['posts.view', 'media.view', 'manager.full']);
$plain = makeUser(['posts.view', 'media.view']);
expect(collect(menuOf($this, $full))->pluck('label')->all())->toBe(['Posts', 'Media']);
expect(collect(menuOf($this, $plain))->pluck('label')->all())->toBe(['Posts']);
$this->putJson('/manager/profile/view', ['view' => 'full'])->assertForbidden();
});
it('lets a super admin see everything and switch', function () {
$admin = makeUser(superAdmin: true);
expect(collect(menuOf($this, $admin))->pluck('label'))->toContain('Posts', 'Media');
$this->putJson('/manager/profile/view', ['view' => 'simple'])->assertOk();
expect(collect(menuOf($this, $admin))->pluck('label')->all())->toBe(['Posts']);
});
it('offers the two permissions in the group form only when the simple face is on', function () {
expect(collect(app(ModuleRegistry::class)->permissionValues()))->toContain('manager.full', 'manager.switch');
});
+51
View File
@@ -0,0 +1,51 @@
<?php
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
it('has users and media on and reviews off by default', function () {
expect(Manager::enabled('users'))->toBeTrue()
->and(Manager::enabled('media'))->toBeTrue()
->and(Manager::enabled('reviews'))->toBeFalse();
});
it('adds no routes, tables or permissions for a module that is off', function () {
expect(Route::has('manager.reviews.index'))->toBeFalse()
->and(Schema::hasTable('manager_reviews'))->toBeFalse()
->and(Manager::permissions())->not->toHaveKey('reviews.manage')
->and(collect(Manager::navigation())->pluck('label'))->not->toContain('Reviews');
});
it('adds all of it for a module that is on', function () {
expect(Route::has('manager.posts.index'))->toBeTrue()
->and(Schema::hasTable('manager_posts'))->toBeTrue()
->and(Manager::permissions())->toHaveKey('posts.publish');
});
it('lets a super admin in and keeps others out without the permission', function () {
$this->actingAs(makeUser(superAdmin: true))->getJson('/manager/posts')->assertOk();
$this->actingAs(makeUser())->getJson('/manager/posts')->assertForbidden();
});
it('gives a group member the permissions of the group, with what they need', function () {
$user = makeUser(['posts.publish']);
expect($user->managerPermissions())->toBe(['posts.view', 'posts.write', 'posts.publish']);
$this->actingAs($user)->getJson('/manager/posts')->assertOk();
$this->actingAs($user)->getJson('/manager/pages')->assertForbidden();
});
it('forgets what a switched-off module allowed', function () {
$group = Group::create(['name' => 'Old', 'permissions' => ['posts.view', 'reviews.manage']]);
expect($group->allowed())->toBe(['posts.view']);
});
it('does not answer for abilities of the host app', function () {
expect(Gate::forUser(makeUser(superAdmin: true))->allows('host.something'))->toBeFalse();
});
+17
View File
@@ -0,0 +1,17 @@
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\Names;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
it('keeps the names of every earlier version by default', function () {
expect(Names::route('posts.index'))->toBe('manager.posts.index')
->and(Names::table('posts'))->toBe('manager_posts')
->and(Route::has('manager.dashboard'))->toBeTrue()
->and(Route::has('manager.media.file'))->toBeTrue()
->and(Schema::hasTable('manager_posts'))->toBeTrue()
->and(Schema::hasTable('manager_media'))->toBeTrue();
});
+82
View File
@@ -0,0 +1,82 @@
<?php
use IriksIT\Manager\Models\Page;
use IriksIT\Manager\Support\Fields;
use IriksIT\Manager\Tests\AllModulesTestCase;
uses(AllModulesTestCase::class);
beforeEach(function () {
config(['manager.pages.definitions' => ['home' => ['title' => 'Home', 'fields' => [
'hero_title' => ['label' => 'Title', 'type' => 'text', 'default' => 'Welcome', 'required' => true, 'max' => 20],
'intro' => ['type' => 'markdown'],
'photo' => ['type' => 'media'],
'show_news' => ['type' => 'toggle'],
'columns' => ['type' => 'select', 'options' => ['2' => 'Two', '3' => 'Three']],
'years' => ['type' => 'number'],
'Bad Key' => ['type' => 'text'],
]]]]);
$this->actingAs(makeUser(['pages.edit']));
});
it('lists defined pages next to saved ones, and gives defaults before a page is saved', function () {
Page::create(['slug' => 'privacy', 'title' => 'Privacy', 'body' => 'Text']);
$pages = collect($this->getJson('/manager/pages')->assertOk()->json('pages'));
expect($pages->pluck('slug')->all())->toBe(['home', 'privacy'])
->and($pages->firstWhere('slug', 'home'))->toMatchArray(['defined' => true, 'saved' => false]);
$page = $this->getJson('/manager/pages/home')->assertOk()->json('page');
expect($page['content']['hero_title'])->toBe('Welcome')
->and(collect($page['fields'])->pluck('key')->all())->toBe(['hero_title', 'intro', 'photo', 'show_news', 'columns', 'years'])
->and(Page::contentFor('home')['hero_title'])->toBe('Welcome');
});
it('saves the fields of a defined page, the first time too', function () {
$this->putJson('/manager/pages/home', ['title' => 'Home', 'content' => ['hero_title' => 'Hello', 'intro' => '**Hi**', 'show_news' => true, 'columns' => '3', 'years' => '12', 'unknown' => 'x']])->assertOk();
$page = Page::query()->where('slug', 'home')->sole();
expect($page->content)->toMatchArray(['hero_title' => 'Hello', 'intro' => '**Hi**', 'show_news' => true, 'columns' => '3', 'years' => 12])
->and($page->content)->not->toHaveKey('unknown')
->and(Page::contentFor('home')['photo'])->toBe('');
});
it('validates the values by the type of the field', function () {
$this->putJson('/manager/pages/home', ['title' => 'Home', 'content' => ['hero_title' => '']])->assertJsonValidationErrors(['content.hero_title']);
$this->putJson('/manager/pages/home', ['title' => 'Home', 'content' => ['hero_title' => str_repeat('a', 21)]])->assertJsonValidationErrors(['content.hero_title']);
$this->putJson('/manager/pages/home', ['title' => 'Home', 'content' => ['hero_title' => 'a', 'columns' => '9']])->assertJsonValidationErrors(['content.columns']);
$this->putJson('/manager/pages/home', ['title' => 'Home', 'content' => ['hero_title' => 'a', 'photo' => 'javascript:alert(1)']])->assertJsonValidationErrors(['content.photo']);
$this->putJson('/manager/pages/home', ['title' => 'Home', 'content' => ['hero_title' => 'a', 'photo' => '/media/a.jpg']])->assertOk();
});
it('makes, changes and removes a free page, and keeps defined pages', function () {
$this->postJson('/manager/pages', ['slug' => 'privacy', 'title' => 'Privacy'])->assertCreated();
$this->postJson('/manager/pages', ['slug' => 'privacy', 'title' => 'Again'])->assertJsonValidationErrors(['slug']);
$this->postJson('/manager/pages', ['slug' => 'home', 'title' => 'Again'])->assertJsonValidationErrors(['slug']);
$this->postJson('/manager/pages', ['slug' => 'Bad Slug', 'title' => 'x'])->assertJsonValidationErrors(['slug']);
$this->putJson('/manager/pages/privacy', ['title' => 'Privacy policy', 'body' => 'We keep little.', 'is_published' => true, 'meta_description' => 'About privacy'])->assertOk();
expect(Page::query()->where('slug', 'privacy')->sole())->toMatchArray(['title' => 'Privacy policy', 'body' => 'We keep little.', 'is_published' => true, 'meta_description' => 'About privacy']);
$this->deleteJson('/manager/pages/privacy')->assertOk();
$this->deleteJson('/manager/pages/home')->assertUnprocessable();
$this->putJson('/manager/pages/nothing', ['title' => 'x'])->assertNotFound();
$this->getJson('/manager/pages/nothing')->assertNotFound();
});
it('needs the permission', function () {
$this->actingAs(makeUser(['posts.view']));
$this->getJson('/manager/pages')->assertForbidden();
$this->putJson('/manager/pages/home', ['title' => 'Home'])->assertForbidden();
});
it('cleans values by their type', function () {
$fields = Fields::normalize(['a' => ['type' => 'toggle'], 'b' => ['type' => 'number'], 'c' => ['type' => 'lines']]);
expect(Fields::clean($fields, ['a' => '0', 'b' => '', 'c' => " one\ntwo "]))->toBe(['a' => false, 'b' => null, 'c' => "one\ntwo"]);
});
+68
View File
@@ -0,0 +1,68 @@
<?php
use Illuminate\Contracts\Auth\Authenticatable;
use IriksIT\Manager\Contracts\PermissionResolver;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Tests\Fixtures\User;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
class FromTheSite implements PermissionResolver
{
public function permissions(Authenticatable $user): array
{
return str_starts_with($user->email, 'editor') ? ['posts.write', 'posts.view', 'nonsense.thing'] : [];
}
}
function editor(string $role = 'editor', array $groups = []): User
{
$user = makeUser($groups);
$user->setAttribute('role', $role);
return $user;
}
it('uses the groups only, as before', function () {
config(['manager.permissions.roles' => ['editor' => ['posts.view']]]);
expect(editor('editor', ['media.view'])->managerPermissions())->toBe(['media.view']);
});
it('takes the permissions from the roles of the site in host mode, and not from the groups', function () {
config(['manager.permissions' => ['mode' => 'host', 'roles' => ['editor' => ['posts.write', 'unknown.thing'], 'owner' => ['*']]] + config('manager.permissions')]);
expect(editor('editor', ['media.view'])->managerPermissions())->toBe(['posts.view', 'posts.write'])
->and(editor('owner')->managerPermissions())->toBe(app(ModuleRegistry::class)->permissionValues())
->and(editor('nobody')->managerPermissions())->toBe([]);
$this->actingAs(editor('editor'));
$this->getJson('/manager/posts')->assertOk();
$this->getJson('/manager/media/items')->assertForbidden();
});
it('adds the roles to the groups in merge mode, and reads a list of roles', function () {
config(['manager.permissions' => ['mode' => 'merge', 'roles' => ['editor' => ['posts.view'], 'writer' => ['posts.write']]] + config('manager.permissions')]);
$user = editor('editor', ['media.view']);
$user->setAttribute('role', ['editor', 'writer']);
expect($user->managerPermissions())->toEqualCanonicalizing(['posts.view', 'posts.write', 'media.view']);
});
it('asks a resolver of the site, which can only give permissions that exist', function () {
config(['manager.permissions' => ['mode' => 'host', 'resolver' => FromTheSite::class] + config('manager.permissions')]);
$user = makeUser();
$user->forceFill(['email' => '[email protected]'])->save();
expect($user->managerPermissions())->toBe(['posts.view', 'posts.write'])
->and(makeUser()->managerPermissions())->toBe([]);
});
it('keeps a super admin all-powerful in every mode', function () {
config(['manager.permissions.mode' => 'host']);
expect(makeUser(superAdmin: true)->managerPermissions())->toContain('posts.view', 'media.view');
});
+15
View File
@@ -0,0 +1,15 @@
<?php
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Tests\PostsOffTestCase;
uses(PostsOffTestCase::class);
it('has no posts, labels, tables or rights for a site without posts', function () {
expect(Route::has('manager.posts.index'))->toBeFalse()
->and(Route::has('manager.labels.index'))->toBeFalse()
->and(Schema::hasTable('manager_posts'))->toBeFalse()
->and(Schema::hasTable('manager_post_labels'))->toBeFalse()
->and(Manager::permissionValues())->not->toContain('posts.view', 'posts.labels');
});
+288
View File
@@ -0,0 +1,288 @@
<?php
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Modules\Posts\PostLabels;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
function postForm(array $overrides = []): array
{
return [
'title' => 'My first post',
'slug' => '',
'excerpt' => 'A short text',
'body' => "# Hello\n\nSome **markdown**.",
'cover_image' => '',
'category' => 'Tutorial',
'tags' => ['Laravel', ' Vue ', ''],
'is_featured' => true,
'is_published' => true,
'published_at' => '',
...$overrides,
];
}
function post(array $attributes = []): Post
{
static $n = 0;
$n++;
return Post::create([
'title' => "Post {$n}",
'slug' => "post-{$n}",
'body' => 'Body',
'published_at' => now()->subDay(),
...$attributes,
]);
}
beforeEach(fn () => $this->actingAs(makeUser(superAdmin: true)));
describe('post list', function () {
it('shows drafts first, then the newest posts, with their status', function () {
post(['title' => 'Published']);
post(['title' => 'Scheduled', 'published_at' => now()->addWeek()]);
post(['title' => 'Draft', 'published_at' => null]);
$this->getJson('/manager/posts')->assertOk()
->assertJsonCount(3, 'posts')
->assertJsonPath('posts.0.status', 'draft')
->assertJsonPath('posts.1.status', 'scheduled')
->assertJsonPath('posts.2.status', 'published');
});
});
describe('creating a post', function () {
it('offers the configured categories, the ones in use, the ones of the site, and tags', function () {
post(['category' => 'Tutorial', 'tags' => ['php']]);
post(['category' => 'Tutorial']);
post(['category' => null]);
app(PostLabels::class)->suggestCategories(fn () => ['Services']);
$this->getJson('/manager/posts/create')->assertOk()
->assertJsonPath('post', null)
->assertJsonPath('categories', ['Services', 'General', 'Tutorial'])
->assertJsonPath('known_tags', ['php']);
});
it('publishes now when no date is given, and makes the slug from the title', function () {
$this->freezeSecond();
$this->postJson('/manager/posts', postForm())->assertCreated();
$post = Post::sole();
expect($post->slug)->toBe('my-first-post')
->and($post->tags)->toBe(['Laravel', 'Vue'])
->and($post->is_featured)->toBeTrue()
->and($post->published_at?->equalTo(now()))->toBeTrue()
->and(Post::published()->count())->toBe(1);
});
it('saves a draft without a publish date', function () {
$this->postJson('/manager/posts', postForm(['is_published' => false, 'published_at' => '2026-01-01T10:00']));
expect(Post::sole()->published_at)->toBeNull()->and(Post::sole()->status())->toBe('draft');
});
it('schedules a post with a date in the future', function () {
$this->travelTo('2026-11-17 12:00');
$this->postJson('/manager/posts', postForm(['published_at' => '2026-12-01T09:30']));
$post = Post::sole();
expect($post->published_at?->format('Y-m-d H:i'))->toBe('2026-12-01 09:30')
->and($post->isPublished())->toBeFalse()
->and($post->status())->toBe('scheduled')
->and(Post::published()->count())->toBe(0);
});
it('gives a second post with the same title its own slug', function () {
$this->postJson('/manager/posts', postForm());
$this->postJson('/manager/posts', postForm());
expect(Post::orderBy('id')->pluck('slug')->all())->toBe(['my-first-post', 'my-first-post-2']);
});
it('stores empty optional fields as null', function () {
$this->postJson('/manager/posts', postForm(['excerpt' => '', 'cover_image' => '', 'category' => '', 'tags' => []]));
$post = Post::sole();
expect($post->excerpt)->toBeNull()->and($post->cover_image)->toBeNull()->and($post->category)->toBeNull()->and($post->tags)->toBe([]);
});
it('validates the form', function (array $input, string $field) {
post(['slug' => 'taken']);
$this->postJson('/manager/posts', postForm($input))->assertJsonValidationErrors($field);
expect(Post::count())->toBe(1);
})->with([
'missing title' => [['title' => ''], 'title'],
'missing body' => [['body' => ''], 'body'],
'slug in use' => [['slug' => 'taken'], 'slug'],
'slug with spaces' => [['slug' => 'Not A Slug'], 'slug'],
'invalid date' => [['published_at' => 'tomorrow-ish'], 'published_at'],
]);
});
describe('editing a post', function () {
it('shows the form filled in', function () {
$post = post(['published_at' => '2026-03-04 15:30:00']);
$this->getJson("/manager/posts/{$post->id}/edit")->assertOk()
->assertJsonPath('post.id', $post->id)
->assertJsonPath('post.is_published', true)
->assertJsonPath('post.published_at', '2026-03-04T15:30');
});
it('updates the post and keeps its own slug valid', function () {
$post = post(['slug' => 'my-slug']);
$this->putJson("/manager/posts/{$post->id}", postForm(['title' => 'New title', 'slug' => 'my-slug']))->assertOk();
expect($post->refresh()->title)->toBe('New title')->and($post->slug)->toBe('my-slug');
});
it('keeps the original publish date when saving without a date', function () {
$post = post(['published_at' => '2024-04-09 10:00:00']);
$this->putJson("/manager/posts/{$post->id}", postForm(['published_at' => '']));
expect($post->refresh()->published_at?->toDateTimeString())->toBe('2024-04-09 10:00:00');
});
it('unpublishes a post, which hides it from the site', function () {
$post = post(['slug' => 'my-slug']);
$this->putJson("/manager/posts/{$post->id}", postForm(['slug' => 'my-slug', 'is_published' => false]));
expect($post->refresh()->published_at)->toBeNull()->and(Post::published()->count())->toBe(0);
});
it('puts a post online and takes it off again', function () {
$post = post(['published_at' => null]);
$this->putJson("/manager/posts/{$post->id}/online", ['online' => true])->assertJsonPath('status', 'published');
$this->putJson("/manager/posts/{$post->id}/online", ['online' => false])->assertJsonPath('status', 'draft');
});
it('previews a draft, with the markdown rendered and raw html escaped', function () {
$post = post(['published_at' => null, 'body' => "**Draft** text <script>alert(1)</script>\n\n[out](https://example.org)"]);
$html = $this->getJson("/manager/posts/{$post->id}/preview")->assertOk()->assertJsonPath('preview', true)->json('post.body_html');
expect($html)->toContain('<strong>Draft</strong>')->not->toContain('<script>')->toContain('target="_blank"');
});
});
describe('deleting a post', function () {
it('removes it', function () {
$post = post();
$this->deleteJson("/manager/posts/{$post->id}")->assertOk();
expect(Post::count())->toBe(0);
});
});
describe('who may do what', function () {
it('lets a writer work on drafts, but never publish or touch what is live', function () {
$this->actingAs(makeUser(['posts.write', 'posts.delete']));
$live = post();
$draft = post(['published_at' => null]);
// Asking to publish still saves a draft.
$this->postJson('/manager/posts', postForm(['is_published' => true]))->assertCreated();
expect(Post::latest('id')->first()->published_at)->toBeNull();
$this->putJson("/manager/posts/{$draft->id}", postForm(['slug' => $draft->slug, 'is_published' => true]))->assertOk();
expect($draft->refresh()->published_at)->toBeNull();
$this->getJson("/manager/posts/{$live->id}/edit")->assertForbidden();
$this->putJson("/manager/posts/{$live->id}", postForm(['slug' => $live->slug]))->assertForbidden();
$this->deleteJson("/manager/posts/{$live->id}")->assertForbidden();
$this->putJson("/manager/posts/{$draft->id}/online", ['online' => true])->assertForbidden();
$this->deleteJson("/manager/posts/{$draft->id}")->assertOk();
});
it('does not show the delete button for a live post to a writer', function () {
$this->actingAs(makeUser(['posts.write', 'posts.delete']));
post();
$this->getJson('/manager/posts')->assertJsonPath('posts.0.can_change', false)->assertJsonPath('posts.0.can_delete', false);
});
it('keeps a viewer out of the form', function () {
$this->actingAs(makeUser(['posts.view']));
$this->getJson('/manager/posts')->assertOk();
$this->postJson('/manager/posts', postForm())->assertForbidden();
});
});
describe('categories and tags', function () {
it('lists every category and tag with the number of posts, drafts included', function () {
post(['category' => 'Laravel', 'tags' => ['php', 'Tutorial']]);
post(['category' => 'Laravel', 'tags' => ['php', 'php'], 'published_at' => null]);
post(['category' => 'devops', 'tags' => []]);
post(['category' => null, 'tags' => null]);
$this->getJson('/manager/labels')->assertOk()
->assertJsonPath('categories', [['name' => 'devops', 'posts' => 1], ['name' => 'Laravel', 'posts' => 2]])
->assertJsonPath('tags', [['name' => 'php', 'posts' => 2], ['name' => 'Tutorial', 'posts' => 1]]);
});
it('renames a category on every post, and merges two by using a name that exists', function () {
$one = post(['category' => 'Devops']);
$two = post(['category' => 'Dev ops']);
$other = post(['category' => 'Laravel']);
$this->putJson('/manager/labels', ['type' => 'category', 'name' => 'Devops', 'new_name' => ' DevOps '])->assertJsonPath('posts', 1);
$this->putJson('/manager/labels', ['type' => 'category', 'name' => 'Dev ops', 'new_name' => 'DevOps'])->assertJsonPath('posts', 1);
expect($one->refresh()->category)->toBe('DevOps')->and($two->refresh()->category)->toBe('DevOps')->and($other->refresh()->category)->toBe('Laravel');
});
it('renames a tag, keeps the order, and keeps it once in a post that had both names', function () {
$one = post(['tags' => ['first', 'laravel', 'last']]);
$both = post(['tags' => ['Laravel', 'laravel', 'php']]);
$other = post(['tags' => ['php']]);
$this->putJson('/manager/labels', ['type' => 'tag', 'name' => 'laravel', 'new_name' => 'Laravel'])->assertJsonPath('posts', 2);
expect($one->refresh()->tags)->toBe(['first', 'Laravel', 'last'])
->and($both->refresh()->tags)->toBe(['Laravel', 'php'])
->and($other->refresh()->tags)->toBe(['php']);
});
it('takes a label off every post and leaves the posts', function () {
$post = post(['category' => 'Old', 'tags' => ['old', 'php']]);
$this->deleteJson('/manager/labels', ['type' => 'category', 'name' => 'Old'])->assertJsonPath('posts', 1);
$this->deleteJson('/manager/labels', ['type' => 'tag', 'name' => 'old'])->assertJsonPath('posts', 1);
expect($post->refresh()->category)->toBeNull()->and($post->tags)->toBe(['php'])->and(Post::count())->toBe(1);
});
it('makes a label by hand, which a rename and a removal follow', function () {
$this->postJson('/manager/labels', ['type' => 'category', 'name' => 'Future'])->assertCreated();
$this->postJson('/manager/labels', ['type' => 'category', 'name' => 'Future'])->assertStatus(422);
$this->getJson('/manager/labels')->assertJsonPath('categories', [['name' => 'Future', 'posts' => 0]]);
$this->putJson('/manager/labels', ['type' => 'category', 'name' => 'Future', 'new_name' => 'Soon']);
$this->getJson('/manager/labels')->assertJsonPath('categories', [['name' => 'Soon', 'posts' => 0]]);
$this->deleteJson('/manager/labels', ['type' => 'category', 'name' => 'Soon']);
$this->getJson('/manager/labels')->assertJsonPath('categories', []);
});
it('refuses a tag with a comma and an unknown type, and needs its own permission', function () {
$this->postJson('/manager/labels', ['type' => 'tag', 'name' => 'a,b'])->assertJsonValidationErrors('name');
$this->postJson('/manager/labels', ['type' => 'other', 'name' => 'x'])->assertJsonValidationErrors('type');
$this->actingAs(makeUser(['posts.write']));
$this->getJson('/manager/labels')->assertForbidden();
});
});
+21
View File
@@ -0,0 +1,21 @@
<?php
use Illuminate\Support\Facades\Blade;
use IriksIT\Manager\Tests\StatisticsOnTestCase;
uses(StatisticsOnTestCase::class);
it('serves the script for the public pages, without cookies or a session', function () {
$response = $this->get('/pulse/pulse.js')->assertOk()->assertHeader('Content-Type', 'application/javascript');
$script = $response->getFile()->getContent();
expect($script)->toContain('/view', '/leave', 'doNotTrack', 'globalPrivacyControl', "credentials: 'omit'")
->and($response->headers->get('Set-Cookie'))->toBeNull();
});
it('has a component that puts the script in a page', function () {
$html = Blade::render('<x-manager::pulse />');
expect(trim($html))->toBe('<script src="/pulse/pulse.js" defer ></script>');
expect(Blade::render('<x-manager::pulse :spa="true" />'))->toContain('data-spa');
});
+23
View File
@@ -0,0 +1,23 @@
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Tests\RenamedTestCase;
uses(RenamedTestCase::class);
it('moves routes, tables and the menu out of the way of the site', function () {
expect(Route::has('pkg-manager.dashboard'))->toBeTrue()
->and(Route::has('pkg-manager.posts.index'))->toBeTrue()
->and(Route::has('manager.dashboard'))->toBeFalse()
->and(Schema::hasTable('pkg_posts'))->toBeTrue()
->and(Schema::hasTable('site_files'))->toBeTrue()
->and(Schema::hasTable('manager_posts'))->toBeFalse()
->and(Schema::hasTable('pkg_media'))->toBeFalse();
$routes = collect(app(ModuleRegistry::class)->navigation())->pluck('route');
expect($routes)->not->toBeEmpty()
->and($routes->every(fn ($route) => str_starts_with($route, 'pkg-manager.')))->toBeTrue();
});
+88
View File
@@ -0,0 +1,88 @@
<?php
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Models\Record;
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Support\Resources;
use IriksIT\Manager\Tests\ResourcesTestCase;
uses(ResourcesTestCase::class);
class Service extends Eloquent
{
protected $table = 'site_services';
protected $guarded = ['secret'];
protected function casts(): array
{
return ['visible' => 'boolean'];
}
}
beforeEach(function () {
Schema::create('site_services', function ($table) {
$table->id();
$table->string('name');
$table->integer('position')->nullable();
$table->boolean('visible')->default(true);
$table->string('secret')->nullable();
$table->timestamps();
});
$this->actingAs(makeUser(['services.manage', 'services.view', 'links.view', 'links.manage']));
});
it('puts a menu item and permissions in the manager for each resource', function () {
$registry = app(ModuleRegistry::class);
expect($registry->permissionValues())->toContain('services.view', 'services.manage', 'links.view')
->and($registry->permissionValues())->not->toContain('posts.view-more')
->and(collect($registry->navigation())->firstWhere('label', 'Services'))->toMatchArray(['route' => 'manager.records.index', 'params' => ['resource' => 'services']]);
$this->getJson('/manager')->assertOk()->assertJsonFragment(['href' => '/manager/records/services']);
});
it('keeps the records of a resource in a model of the site', function () {
$this->postJson('/manager/records/services', ['name' => 'Roofs', 'position' => 2, 'visible' => true, 'secret' => 'x'])->assertCreated();
$this->postJson('/manager/records/services', ['name' => 'Floors', 'position' => 1])->assertCreated();
$rows = $this->getJson('/manager/records/services')->assertOk()->json('rows');
expect(collect($rows)->pluck('values.name')->all())->toBe(['Floors', 'Roofs'])
->and(Service::query()->where('name', 'Roofs')->value('secret'))->toBeNull();
$id = $rows[0]['id'];
$this->putJson("/manager/records/services/{$id}", ['name' => 'Floors and walls', 'position' => 1])->assertOk();
$this->getJson("/manager/records/services/{$id}/edit")->assertOk()->assertJsonPath('record.values.name', 'Floors and walls');
$this->deleteJson("/manager/records/services/{$id}")->assertOk();
expect(Service::query()->count())->toBe(1);
});
it('keeps the records of a resource without a model in the table of the package', function () {
$this->postJson('/manager/records/links', ['label' => 'Home', 'url' => '/', 'new_tab' => true])->assertCreated();
$this->postJson('/manager/records/links', ['label' => 'Bad', 'url' => 'javascript:alert(1)'])->assertJsonValidationErrors(['url']);
$this->postJson('/manager/records/links', ['url' => '/x'])->assertJsonValidationErrors(['label']);
expect(Record::query()->where('resource', 'links')->sole()->data)->toBe(['label' => 'Home', 'url' => '/', 'new_tab' => true]);
$this->getJson('/manager/records/links/create')->assertOk()->assertJsonPath('record.values.new_tab', false)->assertJsonCount(3, 'resource.fields');
});
it('is closed to those without the permission and to what was not defined', function () {
$this->actingAs(makeUser(['services.view']));
$this->getJson('/manager/records/services')->assertOk();
$this->postJson('/manager/records/services', ['name' => 'x'])->assertForbidden();
$this->getJson('/manager/records/links')->assertForbidden();
$this->getJson('/manager/records/posts')->assertNotFound();
$this->getJson('/manager/records/nothing')->assertNotFound();
$this->getJson('/manager/records/services/99/edit')->assertForbidden();
});
it('does not take a name that belongs to a module', function () {
config(['manager.resources.posts' => ['fields' => ['a' => ['type' => 'text']]]]);
expect(array_keys(Resources::all()))->toBe(['services', 'links']);
});
+11
View File
@@ -0,0 +1,11 @@
<?php
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Tests\ReviewsOnTestCase;
uses(ReviewsOnTestCase::class);
it('can switch an optional module on', function () {
expect(Route::has('manager.reviews.index'))->toBeTrue()
->and(Schema::hasTable('manager_reviews'))->toBeTrue();
});
+88
View File
@@ -0,0 +1,88 @@
<?php
use IriksIT\Manager\Models\Page;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Models\Revision;
use IriksIT\Manager\Tests\AllModulesTestCase;
uses(AllModulesTestCase::class);
function writtenPost(array $values = []): Post
{
return Post::create($values + ['title' => 'First', 'slug' => 'first', 'body' => 'One', 'tags' => ['a']]);
}
it('keeps a state at every save, and nothing when nothing changed', function () {
$post = writtenPost();
$post->update(['body' => 'Two']);
$post->save();
$revisions = Revision::query()->where('type', 'posts')->orderBy('id')->get();
expect($revisions)->toHaveCount(2)
->and($revisions[0]->changed)->toContain('title', 'body')
->and($revisions[1]->changed)->toBe(['body'])
->and($revisions[1]->data)->not->toHaveKey('published_at')->and($revisions[1]->data)->not->toHaveKey('id');
});
it('lists the history to someone who may see it, and only that', function () {
$post = writtenPost();
$post->update(['body' => 'Two']);
$this->actingAs(makeUser(['posts.view', 'revisions.view']));
$list = $this->getJson("/manager/revisions/posts/{$post->id}")->assertOk()->json();
expect($list['revisions'])->toHaveCount(2)
->and($list['revisions'][0])->toMatchArray(['current' => true, 'changed' => ['body']])
->and($list['revisions'][0]['values']['body'])->toBe('Two')
->and($list['can_restore'])->toBeFalse();
$this->actingAs(makeUser(['revisions.view']))->getJson("/manager/revisions/posts/{$post->id}")->assertForbidden();
$this->actingAs(makeUser(['posts.view']))->getJson("/manager/revisions/posts/{$post->id}")->assertForbidden();
$this->actingAs(makeUser(['posts.view', 'revisions.view']))->getJson('/manager/revisions/cars/1')->assertNotFound();
});
it('puts an earlier state back without touching whether the post is on the site', function () {
$post = writtenPost(['published_at' => now()->subDay()]);
$first = Revision::query()->where('type', 'posts')->sole();
$post->update(['body' => 'Two', 'tags' => ['b'], 'published_at' => null]);
$this->actingAs(makeUser(['posts.view', 'posts.write', 'revisions.view', 'revisions.restore']));
$this->postJson("/manager/revisions/posts/{$post->id}/{$first->id}/restore")->assertOk();
$post->refresh();
expect($post->body)->toBe('One')->and($post->tags)->toBe(['a'])->and($post->published_at)->toBeNull()
->and(Revision::query()->where('type', 'posts')->count())->toBe(3);
});
it('keeps a live post for those who may publish', function () {
$post = writtenPost(['published_at' => now()->subDay()]);
$first = Revision::query()->where('type', 'posts')->sole();
$post->update(['body' => 'Two']);
$this->actingAs(makeUser(['posts.view', 'posts.write', 'revisions.view', 'revisions.restore']));
$this->postJson("/manager/revisions/posts/{$post->id}/{$first->id}/restore")->assertForbidden();
$this->actingAs(makeUser(['posts.view', 'posts.write', 'posts.publish', 'revisions.view', 'revisions.restore']));
$this->postJson("/manager/revisions/posts/{$post->id}/{$first->id}/restore")->assertOk();
$this->actingAs(makeUser(['posts.view', 'revisions.view']));
$this->postJson("/manager/revisions/posts/{$post->id}/{$first->id}/restore")->assertForbidden();
});
it('has a history for pages, forgets it with the page, and keeps only the newest', function () {
$page = Page::create(['slug' => 'privacy', 'title' => 'Privacy', 'body' => '1']);
config(['manager.revisions.keep' => 5]);
foreach (range(2, 9) as $n) {
$page->update(['body' => (string) $n]);
}
expect(Revision::query()->where('type', 'pages')->count())->toBe(5)
->and(Revision::query()->where('type', 'pages')->orderByDesc('id')->first()->data['body'])->toBe('9');
$page->delete();
expect(Revision::query()->where('type', 'pages')->count())->toBe(0);
});
+127
View File
@@ -0,0 +1,127 @@
<?php
use Illuminate\Support\Facades\Artisan;
use IriksIT\Manager\Models\UserSetting;
use IriksIT\Manager\Support\Themes;
use IriksIT\Manager\Tests\Fixtures\User;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
function signedIn(): User
{
$user = User::create(['name' => 'Ann', 'email' => '[email protected]', 'password' => Hash::make('a-long-enough-password')]);
$user->forceFill(['is_super_admin' => true])->save();
test()->actingAs($user);
return $user;
}
it('gives a browser the shell and a script the data', function () {
signedIn();
$this->get('/manager/posts')->assertOk()->assertSee('id="manager"', false)->assertSee('"navigation"', false);
$this->getJson('/manager/posts')->assertOk()->assertJsonStructure(['posts']);
});
it('sends a guest to the login of the manager when the app has none', function () {
$this->get('/manager/posts')->assertRedirect('/manager/login');
$this->getJson('/manager/posts')->assertUnauthorized();
$this->get('/manager/login')->assertOk()->assertSee('"user":null', false);
});
it('logs in and out through the JSON routes', function () {
User::create(['name' => 'Ann', 'email' => '[email protected]', 'password' => Hash::make('a-long-enough-password')]);
$this->postJson('/manager/login', ['email' => '[email protected]', 'password' => 'wrong'])->assertUnprocessable()->assertJsonValidationErrors('email');
$this->postJson('/manager/login', ['email' => '[email protected]', 'password' => 'a-long-enough-password'])->assertOk()->assertJson(['redirect' => '/manager']);
$this->assertAuthenticated();
$this->postJson('/manager/logout')->assertOk();
$this->assertGuest();
});
it('serves only the two built files', function () {
$this->get('/manager/_assets/manager.css')->assertOk()->assertHeader('X-Content-Type-Options', 'nosniff');
$this->get('/manager/_assets/secret.php')->assertNotFound();
});
it('has no screens when the app builds its own', function () {
config(['manager.ui' => 'none']);
expect(Route::has('manager.login'))->toBeTrue(); // routes were registered at boot; the shell stays out of the way
signedIn();
$this->get('/manager/posts')->assertOk()->assertJsonStructure(['posts']);
});
describe('themes', function () {
it('lets an account choose a theme, and only a known one', function () {
$user = signedIn();
$this->putJson('/manager/profile', ['name' => 'Ann', 'theme' => 'light'])->assertOk();
expect(UserSetting::where('user_id', $user->id)->value('theme'))->toBe('light');
$this->get('/manager')->assertSee('--m-brand:#009ba3', false);
$this->putJson('/manager/profile', ['name' => 'Ann', 'theme' => 'nope'])->assertUnprocessable();
});
it('ignores the choice when the site switched it off', function () {
config(['manager.user_themes' => false]);
$user = signedIn();
UserSetting::create(['user_id' => $user->id, 'theme' => 'light']);
expect(app(Themes::class)->keyFor($user))->toBe('dark');
});
it('never lets a theme file put CSS or markup in the page', function () {
config(['manager.themes' => ['evil' => [
'colors' => ['brand' => 'red;}</style><script>alert(1)</script>', 'ink' => '#123456'],
'radius' => '1rem;}', 'font' => 'x</style>', 'logo' => 'javascript:alert(1)', 'name' => '<b>Shop</b>',
]]]);
config(['manager.theme' => 'evil']);
signedIn();
$html = $this->get('/manager')->getContent();
expect($html)->not->toContain('<script>alert')->and($html)->toContain('--m-ink:#123456')->toContain('--m-radius:0.5rem')
->and($html)->not->toContain('javascript:');
});
it('reads a custom theme from a JSON file', function () {
$dir = sys_get_temp_dir().'/manager-themes-'.uniqid();
mkdir($dir);
file_put_contents($dir.'/house.json', json_encode(['label' => 'House', 'colors' => ['brand' => '#ff8800'], 'name' => 'Acme']));
config(['manager.themes_path' => $dir, 'manager.theme' => 'house']);
signedIn();
$this->get('/manager')->assertSee('--m-brand:#ff8800', false)->assertSee('<title>Acme</title>', false);
unlink($dir.'/house.json');
rmdir($dir);
});
});
it('lets an account change its password only with the current one', function () {
$user = signedIn();
$this->putJson('/manager/profile', ['name' => 'Ann', 'current_password' => 'wrong', 'password' => 'another-long-password', 'password_confirmation' => 'another-long-password'])->assertUnprocessable();
$this->putJson('/manager/profile', ['name' => 'Ann', 'current_password' => 'a-long-enough-password', 'password' => 'another-long-password', 'password_confirmation' => 'another-long-password'])->assertOk();
expect(Hash::check('another-long-password', $user->fresh()->password))->toBeTrue();
});
describe('make-theme', function () {
it('writes a theme file the manager then uses', function () {
$dir = sys_get_temp_dir().'/manager-make-'.uniqid();
config(['manager.themes_path' => $dir]);
expect(Artisan::call('manager:make-theme', ['key' => 'acme', '--brand' => '#e4002b', '--name' => 'Acme', '--light' => true]))->toBe(0);
expect(app(Themes::class)->all()['acme']['colors']['brand'])->toBe('#e4002b')
->and(app(Themes::class)->all()['acme']['scheme'])->toBe('light');
// No overwrite without --force, and nothing that could break out of a style block.
expect(Artisan::call('manager:make-theme', ['key' => 'acme']))->toBe(1);
expect(Artisan::call('manager:make-theme', ['key' => 'bad', '--brand' => 'red;}', '--force' => true]))->toBe(1);
expect(file_exists($dir.'/bad.json'))->toBeFalse();
array_map('unlink', glob($dir.'/*.json'));
rmdir($dir);
});
});
+23
View File
@@ -0,0 +1,23 @@
<?php
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use IriksIT\Manager\Facades\Manager;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
it('has no statistics, pulse routes, tables or rights unless the site switched them on', function () {
expect(Route::has('manager.statistics.index'))->toBeFalse()
->and(Route::has('manager.pulse.view'))->toBeFalse()
->and(Schema::hasTable('manager_visits'))->toBeFalse()
->and(Schema::hasTable('manager_bot_hits'))->toBeFalse()
->and(Manager::permissionValues())->not->toContain('statistics.view');
$this->postJson('/pulse/view', ['path' => '/'])->assertNotFound();
});
it('puts nothing in a page for the pulse component', function () {
expect(trim(Blade::render('<x-manager::pulse />')))->toBe('');
});
+131
View File
@@ -0,0 +1,131 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Testing\TestResponse;
use IriksIT\Manager\Models\PageView;
use IriksIT\Manager\Models\Post;
use IriksIT\Manager\Models\Visit;
use IriksIT\Manager\Models\VisitorSalt;
use IriksIT\Manager\Modules\Statistics\CountedPages;
use IriksIT\Manager\Tests\StatisticsOnTestCase;
uses(StatisticsOnTestCase::class);
const BROWSER = 'Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0';
function pulse(array $payload = [], array $headers = []): TestResponse
{
return test()->withHeaders(['User-Agent' => BROWSER, ...$headers])->postJson('/pulse/view', ['path' => '/', ...$payload]);
}
describe('counting a page view', function () {
it('counts a page of the list, with how the visitor arrived, and keeps no address', function () {
$token = pulse(['referrer' => 'https://www.google.com/search?q=x'], ['CF-IPCountry' => 'NL'])->assertOk()->json('token');
$visit = Visit::sole();
expect($token)->toBeString()
->and($visit->entry_path)->toBe('/')
->and($visit->channel)->toBe('search')
->and($visit->country)->toBe('NL')
->and($visit->browser)->toBe('Firefox')
->and($visit->page_views)->toBe(1)
->and(PageView::sole()->token)->toBe($token);
expect(json_encode(DB::table('manager_visits')->get()))->not->toContain('127.0.0.1')->not->toContain('Firefox/130');
});
it('puts the next page in the same visit', function () {
pulse();
pulse(['path' => '/about']);
expect(Visit::count())->toBe(1)->and(Visit::sole()->page_views)->toBe(2)->and(Visit::sole()->exit_path)->toBe('/about');
});
it('ignores an address that is not a page, a program, and a browser that asks not to be followed', function () {
expect(pulse(['path' => '/made-up'])->json('token'))->toBeNull();
expect(pulse([], ['User-Agent' => 'Googlebot/2.1'])->json('token'))->toBeNull();
expect(pulse([], ['DNT' => '1'])->json('token'))->toBeNull();
expect(pulse([], ['Sec-GPC' => '1'])->json('token'))->toBeNull();
expect(Visit::count())->toBe(0);
});
it('counts a published post under the posts path, and not a draft', function () {
Post::create(['title' => 'Live', 'slug' => 'live', 'body' => 'x', 'published_at' => now()->subDay()]);
Post::create(['title' => 'Draft', 'slug' => 'draft', 'body' => 'x']);
expect(pulse(['path' => '/blog/live'])->json('token'))->toBeString();
expect(pulse(['path' => '/blog/draft'])->json('token'))->toBeNull();
expect(PageView::sole()->post_id)->toBe(Post::where('slug', 'live')->value('id'));
});
it('asks the resolvers of the site for the rest', function () {
app(CountedPages::class)->register(fn (string $path) => $path === '/shop/1' ? ['path' => $path, 'post_id' => null] : null);
expect(pulse(['path' => '/shop/1'])->json('token'))->toBeString();
expect(pulse(['path' => '/shop/2'])->json('token'))->toBeNull();
});
it('records the time on a page, never longer than has passed', function () {
$token = pulse()->json('token');
$this->travel(20)->seconds();
$this->postJson('/pulse/leave', ['token' => $token, 'seconds' => 9999])->assertNoContent();
expect(PageView::sole()->seconds)->toBeLessThanOrEqual(30)->and(Visit::sole()->seconds)->toBe(PageView::sole()->seconds);
});
it('makes a new visitor code every day and forgets the old keys', function () {
pulse();
$this->travel(1)->days();
pulse();
expect(Visit::distinct()->count('visitor_hash'))->toBe(2)->and(VisitorSalt::count())->toBe(1);
$this->artisan('manager:forget-visitor-keys')->assertSuccessful();
});
});
describe('programs', function () {
it('counts a page that was served to a program, per day, and nothing about the program', function () {
Route::middleware('web')->get('/robots-test', fn () => 'ok')->name('robots-test');
$this->withHeaders(['User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'])->get('/robots-test')->assertOk();
$this->withHeaders(['User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'])->get('/robots-test')->assertOk();
$this->withHeaders(['User-Agent' => BROWSER])->get('/robots-test')->assertOk();
$row = DB::table('manager_bot_hits')->sole();
expect($row->hits)->toBe(2)->and($row->kind)->toBe('search')->and($row->path)->toBe('/robots-test');
});
});
describe('the report', function () {
it('needs statistics.view', function () {
$this->actingAs(makeUser());
$this->getJson('/manager/statistics')->assertForbidden();
$this->get('/manager/statistics/export?sheet=days')->assertForbidden();
});
it('shows the totals, pages and channels of the period', function () {
pulse(['referrer' => 'https://www.google.com/']);
pulse(['path' => '/about']);
$this->actingAs(makeUser(['statistics.view']));
$this->getJson('/manager/statistics?range=today')->assertOk()
->assertJsonPath('totals.visits', 1)
->assertJsonPath('totals.page_views', 2)
->assertJsonCount(2, 'pages')
->assertJsonPath('channels.0.name', 'search');
});
it('downloads a sheet as CSV', function () {
app(CountedPages::class)->register(fn (string $path) => $path === '/=1+1' ? ['path' => $path, 'post_id' => null] : null);
pulse(['path' => '/=1+1']);
$this->actingAs(makeUser(['statistics.view']));
$response = $this->get('/manager/statistics/export?sheet=pages&range=today')->assertOk();
expect($response->headers->get('Content-Type'))->toContain('text/csv')
->and($response->streamedContent())->toContain('/=1+1,,1,');
});
});
+59
View File
@@ -0,0 +1,59 @@
<?php
use IriksIT\Manager\Support\ModuleRegistry;
use IriksIT\Manager\Tests\AllModulesTestCase;
uses(AllModulesTestCase::class);
it('has a Dutch text for every label the modules give', function () {
$registry = app(ModuleRegistry::class);
$english = [];
foreach ($registry->active() as $module) {
$english[] = $module->label();
foreach ($module->permissions() as $permission) {
array_push($english, $permission->label, $permission->section);
}
foreach ($module->navigation() as $item) {
$english[] = $item['label'];
}
foreach ($module->actions() as $action) {
$english[] = $action[0];
}
array_push($english, ...array_values($module->views()));
}
$dutch = json_decode(file_get_contents(__DIR__.'/../../resources/lang/nl.json'), true);
$missing = collect($english)->unique()->filter(fn (string $text) => $text !== '' && ! array_key_exists($text, $dutch))->values()->all();
expect($missing)->toBe([]);
});
it('says the menu and the group form in the language of the app', function () {
app()->setLocale('nl');
$registry = app(ModuleRegistry::class);
expect(collect($registry->navigation())->pluck('label'))->toContain('Berichten', 'Groepen')
->and(collect($registry->catalogue())->pluck('section'))->toContain('Inhoud van de site');
app()->setLocale('en');
expect(collect($registry->navigation())->pluck('label'))->toContain('Posts');
});
it('lets the site override a text', function () {
app()->setLocale('nl');
$folder = sys_get_temp_dir().'/manager-lang-'.uniqid();
mkdir($folder);
file_put_contents($folder.'/nl.json', json_encode(['Posts' => 'Nieuws']));
app('translator')->addJsonPath($folder);
expect(collect(app(ModuleRegistry::class)->navigation())->pluck('label'))->toContain('Nieuws');
unlink($folder.'/nl.json');
rmdir($folder);
});
+132
View File
@@ -0,0 +1,132 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Tests\Fixtures\User;
use IriksIT\Manager\Tests\TestCase;
uses(TestCase::class);
describe('groups', function () {
beforeEach(fn () => $this->actingAs(makeUser(superAdmin: true)));
it('lists the groups with what they allow and everything that can be allowed', function () {
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
makeUser()->managerGroups()->attach($group);
$this->getJson('/manager/groups')->assertOk()
->assertJsonPath('groups.0.name', 'Writers')
->assertJsonPath('groups.0.permissions', ['posts.view', 'posts.write'])
->assertJsonPath('groups.0.accounts', 1);
$values = collect($this->getJson('/manager/groups')->json('catalogue'))->flatMap(fn ($s) => collect($s['permissions'])->pluck('value'))->all();
expect($values)->toContain('accounts.manage', 'media.upload')->not->toContain('groups.manage', 'reviews.manage');
});
it('creates a group, with what its permissions need', function () {
$this->postJson('/manager/groups', ['name' => ' Editors ', 'description' => 'Publish', 'permissions' => ['posts.publish', 'media.upload']])->assertCreated();
expect(Group::sole()->permissions)->toBe(['media.view', 'media.upload', 'posts.view', 'posts.write', 'posts.publish']);
});
it('refuses a name that is taken, a permission that does not exist and groups.manage', function () {
Group::create(['name' => 'Writers']);
$this->postJson('/manager/groups', ['name' => 'Writers'])->assertJsonValidationErrors('name');
$this->postJson('/manager/groups', ['name' => 'Others', 'permissions' => ['groups.manage']])->assertJsonValidationErrors('permissions.0');
expect(Group::count())->toBe(1);
});
it('changes what a group allows, which its accounts feel at once', function () {
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
$writer = makeUser();
$writer->managerGroups()->attach($group);
$this->putJson("/manager/groups/{$group->id}", ['name' => 'Writers', 'permissions' => ['pages.edit']])->assertOk();
$this->actingAs($writer->refresh())->getJson('/manager/posts')->assertForbidden();
$this->getJson('/manager/pages')->assertOk();
});
it('deletes a group and leaves its accounts, without what it allowed', function () {
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
$writer = makeUser();
$writer->managerGroups()->attach($group);
$this->deleteJson("/manager/groups/{$group->id}")->assertOk();
expect(Group::count())->toBe(0)->and($writer->refresh()->managerPermissions())->toBe([]);
});
it('is not for someone who manages accounts but is no super admin', function () {
$this->actingAs(makeUser(['accounts.manage']));
$this->getJson('/manager/groups')->assertForbidden();
$this->postJson('/manager/groups', ['name' => 'Mine'])->assertForbidden();
expect(Group::where('name', 'Mine')->exists())->toBeFalse();
});
});
describe('accounts', function () {
it('creates an account with a hashed password, never as super admin', function () {
$this->actingAs(makeUser(superAdmin: true));
$group = Group::create(['name' => 'Writers', 'permissions' => ['posts.write']]);
$this->postJson('/manager/accounts', ['name' => 'Ann', 'email' => ' [email protected] ', 'password' => 'a-long-password-1', 'groups' => [$group->id], 'is_super_admin' => true])->assertCreated();
$ann = User::where('email', '[email protected]')->sole();
expect(Hash::check('a-long-password-1', $ann->password))->toBeTrue()
->and($ann->isManagerSuperAdmin())->toBeFalse()
->and($ann->managerGroups->pluck('name')->all())->toBe(['Writers']);
});
it('refuses a short password and an address that is in use', function () {
$me = makeUser(superAdmin: true);
$this->actingAs($me);
$this->postJson('/manager/accounts', ['name' => 'A', 'email' => '[email protected]', 'password' => 'short'])->assertJsonValidationErrors('password');
$this->postJson('/manager/accounts', ['name' => 'A', 'email' => $me->email, 'password' => 'a-long-password-1'])->assertJsonValidationErrors('email');
});
it('does not let someone hand out more than they have', function () {
$this->actingAs(makeUser(['accounts.manage', 'posts.write']));
$big = Group::create(['name' => 'Big', 'permissions' => ['pages.edit']]);
$this->postJson('/manager/accounts', ['name' => 'B', 'email' => '[email protected]', 'password' => 'a-long-password-1', 'groups' => [$big->id]])->assertJsonValidationErrors('groups');
expect(User::where('email', '[email protected]')->exists())->toBeFalse();
});
it('does not let someone change or delete a mightier account, or themselves', function () {
$me = makeUser(['accounts.manage']);
$mighty = makeUser(['accounts.manage', 'posts.write']);
$boss = makeUser(superAdmin: true);
$this->actingAs($me);
$this->putJson("/manager/accounts/{$mighty->id}", ['name' => 'X', 'email' => '[email protected]', 'password' => 'a-long-password-1'])->assertForbidden();
$this->deleteJson("/manager/accounts/{$boss->id}")->assertForbidden();
$this->deleteJson("/manager/accounts/{$me->id}")->assertStatus(422);
});
it('keeps the password when it is left empty, and removes the group links on delete', function () {
$this->actingAs(makeUser(superAdmin: true));
$user = makeUser(['posts.view']);
$hash = $user->password;
$this->putJson("/manager/accounts/{$user->id}", ['name' => 'New name', 'email' => $user->email, 'password' => ''])->assertOk();
expect($user->refresh()->name)->toBe('New name')->and($user->password)->toBe($hash);
$this->deleteJson("/manager/accounts/{$user->id}")->assertOk();
expect(DB::table('manager_group_user')->count())->toBe(0);
});
});
it('makes a super admin only with the command', function () {
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'a-long-password-1'])->assertSuccessful();
$root = User::where('email', '[email protected]')->sole();
expect($root->isManagerSuperAdmin())->toBeTrue()->and(Hash::check('a-long-password-1', $root->password))->toBeTrue();
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'a-long-password-1'])->assertFailed();
$this->artisan('manager:create-user', ['--name' => 'Root', '--email' => '[email protected]', '--password' => 'short'])->assertFailed();
});
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace IriksIT\Manager\Tests\Fixtures;
use Illuminate\Foundation\Auth\User as Authenticatable;
use IriksIT\Manager\Concerns\HasManagerAccess;
/** Like the User of a normal app: no `hashed` cast, and no `is_super_admin` in $fillable. */
class User extends Authenticatable
{
use HasManagerAccess;
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password'];
}
@@ -0,0 +1,20 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 70 B

+20
View File
@@ -0,0 +1,20 @@
<?php
use IriksIT\Manager\Models\Group;
use IriksIT\Manager\Tests\Fixtures\User;
function makeUser(array $permissions = [], bool $superAdmin = false, string $name = 'Someone'): User
{
static $n = 0;
$n++;
$user = new User(['name' => $name, 'email' => "user{$n}@example.com", 'password' => 'secret']);
$user->is_super_admin = $superAdmin;
$user->save();
if ($permissions !== []) {
$user->managerGroups()->attach(Group::create(['name' => "Group {$n}", 'permissions' => $permissions]));
}
return $user;
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace IriksIT\Manager\Tests;
abstract class MediaOffTestCase extends TestCase
{
protected array $modules = ['media' => false];
}
+3
View File
@@ -0,0 +1,3 @@
<?php
require_once __DIR__.'/Helpers.php';
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace IriksIT\Manager\Tests;
abstract class PostsOffTestCase extends TestCase
{
protected array $modules = ['posts' => false];
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site that already has `manager.*` routes and `manager_*` tables of its own. */
abstract class RenamedTestCase extends TestCase
{
protected array $modules = ['reviews' => true];
protected function defineEnvironment($app): void
{
parent::defineEnvironment($app);
$app['config']->set('manager.route_name', 'pkg-manager');
$app['config']->set('manager.table_prefix', 'pkg_');
$app['config']->set('manager.tables', ['media' => 'site_files']);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site with two resources of its own: one in a model of the site, one in the table of the package. */
abstract class ResourcesTestCase extends TestCase
{
protected function defineEnvironment($app): void
{
parent::defineEnvironment($app);
$app['config']->set('manager.resources', [
'services' => [
'label' => 'Services', 'singular' => 'Service', 'model' => \Service::class, 'columns' => ['name'], 'order' => ['position', 'asc'],
'fields' => ['name' => ['type' => 'text', 'required' => true], 'position' => ['type' => 'number'], 'visible' => ['type' => 'toggle']],
],
'links' => [
'label' => 'Links',
'fields' => ['label' => ['type' => 'text', 'required' => true], 'url' => ['type' => 'url'], 'new_tab' => ['type' => 'toggle']],
],
]);
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site that switched the optional reviews module on. */
abstract class ReviewsOnTestCase extends TestCase
{
protected array $modules = ['reviews' => true];
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site that turned the simple face of the manager on. */
abstract class SimpleViewTestCase extends TestCase
{
protected function defineEnvironment($app): void
{
parent::defineEnvironment($app);
$app['config']->set('manager.simple_view', true);
$app['config']->set('manager.menu.items', ['posts.index' => ['simple' => true, 'order' => 5, 'section' => 'Content', 'icon' => 'file']]);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace IriksIT\Manager\Tests;
/** A site that switched the optional statistics on. */
abstract class StatisticsOnTestCase extends TestCase
{
protected array $modules = ['statistics' => true];
protected function defineEnvironment($app): void
{
parent::defineEnvironment($app);
$app['config']->set('manager.statistics.pages', ['/', '/about']);
$app['config']->set('manager.statistics.posts_path', '/blog');
$app['config']->set('manager.statistics.country_header', 'CF-IPCountry');
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace IriksIT\Manager\Tests;
use Illuminate\Foundation\Testing\RefreshDatabase;
use IriksIT\Manager\ManagerServiceProvider;
use IriksIT\Manager\Tests\Fixtures\User;
use Orchestra\Testbench\TestCase as Orchestra;
abstract class TestCase extends Orchestra
{
use RefreshDatabase;
/** @var array<string, bool> */
protected array $modules = [];
protected function getPackageProviders($app): array
{
return [ManagerServiceProvider::class];
}
protected function defineEnvironment($app): void
{
$app['config']->set('database.default', 'testing');
$app['config']->set('app.key', 'base64:'.base64_encode(str_repeat('a', 32)));
$app['config']->set('manager.user_model', User::class);
$app['config']->set('manager.modules', array_merge($app['config']->get('manager.modules'), $this->modules));
}
protected function defineDatabaseMigrations(): void
{
$this->loadMigrationsFrom(__DIR__.'/Fixtures/migrations');
}
}
+1
View File
@@ -0,0 +1 @@
node_modules
+2182
View File
File diff suppressed because it is too large. Load diff
+20
View File
@@ -0,0 +1,20 @@
{
"name": "laravel-manager-ui",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"typecheck": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "^3.5.46"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.5",
"@vitejs/plugin-vue": "^6.0.11",
"tailwindcss": "^4.3.5",
"typescript": "^5.9.3",
"vite": "^8.4.1",
"vue-tsc": "^3.0.0"
}
}
+23
View File
@@ -0,0 +1,23 @@
<script setup lang="ts">
import { boot } from './api';
import { t } from './i18n';
import Layout from './components/Layout.vue';
import { state } from './state';
</script>
<template>
<component :is="state.component" v-if="state.component && !boot.user" />
<Layout v-else-if="state.component">
<p v-if="state.forbidden" class="m-card p-5 text-sm">{{ t('You may not open this page.') }}</p>
<p v-else-if="state.loading" class="text-sm text-muted">{{ t('Loading…') }}</p>
<component :is="state.component" v-else v-bind="state.props" />
</Layout>
<div
v-if="state.toast"
role="status"
class="fixed bottom-5 right-5 z-50 rounded-lg border border-l-4 border-line bg-panel px-4 py-3 text-sm font-medium text-text shadow-xl"
:class="state.toast.error ? 'border-l-red-500' : 'border-l-emerald-500'"
>
{{ state.toast.text }}
</div>
</template>
+117
View File
@@ -0,0 +1,117 @@
import { reactive } from 'vue';
export class ApiError extends Error {
constructor(public status: number, public body: any) {
super(body?.message ?? `HTTP ${status}`);
}
/** Validation errors by field, first message each. */
get errors(): Record<string, string> {
return Object.fromEntries(Object.entries(this.body?.errors ?? {}).map(([k, v]) => [k, (v as string[])[0]]));
}
}
export interface NavItem {
label: string;
href: string;
section?: string;
icon?: string;
new_tab?: boolean;
}
/** What the page was started with (see resources/views/shell.blade.php). */
export interface Boot {
base: string;
name: string;
logo: string | null;
locale: string;
user: { name: string; email: string; is_super_admin: boolean } | null;
permissions: string[];
navigation: NavItem[];
view: 'full' | 'simple';
extensions: string[];
login_fields: { name: string; type: string; label?: string; autocomplete?: string; required?: boolean; site_key?: string }[];
can_switch: boolean;
theme: string;
can_login: boolean;
}
export const boot: Boot = JSON.parse(document.getElementById('manager-boot')!.textContent!);
function xsrf(): string {
const match = document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]+)/);
return match ? decodeURIComponent(match[1]) : '';
}
export async function request<T = any>(method: string, path: string, body?: unknown): Promise<T> {
const response = await fetch(path, {
method,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-XSRF-TOKEN': xsrf(),
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const data = response.status === 204 ? null : await response.json().catch(() => null);
if (!response.ok) {
throw new ApiError(response.status, data);
}
return data as T;
}
/** A file upload: multipart, the browser sets the content type. */
export async function upload<T = any>(path: string, form: FormData): Promise<T> {
const response = await fetch(path, {
method: 'POST',
credentials: 'same-origin',
headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-XSRF-TOKEN': xsrf() },
body: form,
});
const data = await response.json().catch(() => null);
if (!response.ok) {
throw new ApiError(response.status, data);
}
return data as T;
}
export const api = {
get: <T = any>(path: string) => request<T>('GET', path),
post: <T = any>(path: string, body: unknown = {}) => request<T>('POST', path, body),
put: <T = any>(path: string, body: unknown = {}) => request<T>('PUT', path, body),
delete: <T = any>(path: string, body?: unknown) => request<T>('DELETE', path, body),
};
/** A form: values, errors by field, a busy flag. */
export function useForm<T extends Record<string, any>>(initial: T) {
const form = reactive({
values: { ...initial } as T,
errors: {} as Record<string, string>,
busy: false,
async send<R = any>(method: 'post' | 'put', path: string): Promise<R | null> {
form.busy = true;
form.errors = {};
try {
return await api[method]<R>(path, form.values);
} catch (error) {
if (error instanceof ApiError && error.status === 422) {
form.errors = error.errors;
return null;
}
throw error;
} finally {
form.busy = false;
}
},
});
return form;
}
+70
View File
@@ -0,0 +1,70 @@
<script setup lang="ts">
import { ref } from 'vue';
import { boot } from '../api';
import { t } from '../i18n';
import MarkdownEditor from './MarkdownEditor.vue';
import MediaPicker from './MediaPicker.vue';
/** One field as the server describes it (src/Support/Fields.php). */
export interface Field {
key: string;
label: string;
type: string;
help: string | null;
required: boolean;
options: Record<string, string>;
max: number | null;
}
// Draws a form from field definitions: pages use it now, and any record a site defines without code of its own.
// `values` is changed in place; `errors` is keyed like the server does (`<prefix><key>`).
defineProps<{ fields: Field[]; values: Record<string, any>; errors?: Record<string, string>; prefix?: string }>();
const picking = ref<string | null>(null);
const canPick = boot.permissions.includes('media.view');
</script>
<template>
<div class="space-y-5">
<div v-for="field in fields" :key="field.key">
<label v-if="field.type === 'toggle'" class="flex items-center gap-2 text-sm">
<input v-model="values[field.key]" type="checkbox" /> {{ t(field.label) }}
</label>
<template v-else>
<label :for="'f-' + field.key" class="m-label">{{ t(field.label) }}<span v-if="field.required" class="text-muted"> *</span></label>
<select v-if="field.type === 'select'" :id="'f-' + field.key" v-model="values[field.key]" class="m-input">
<option v-if="!field.required" value="" />
<option v-for="(label, value) in field.options" :key="value" :value="value">{{ label }}</option>
</select>
<MarkdownEditor v-else-if="field.type === 'markdown'" :id="'f-' + field.key" v-model="values[field.key]" :required="field.required" :maxlength="field.max ?? undefined" />
<textarea
v-else-if="field.type === 'textarea' || field.type === 'lines'"
:id="'f-' + field.key"
v-model="values[field.key]"
:rows="field.type === 'lines' ? 5 : 4"
:maxlength="field.max ?? undefined"
:required="field.required"
class="m-input"
/>
<div v-else-if="field.type === 'media'" class="flex gap-2">
<input :id="'f-' + field.key" v-model="values[field.key]" maxlength="2048" class="m-input" />
<button v-if="canPick" type="button" class="m-btn m-btn-secondary shrink-0" @click="picking = field.key">{{ t('Choose') }}</button>
</div>
<input
v-else
:id="'f-' + field.key"
v-model="values[field.key]"
:type="field.type === 'number' ? 'number' : field.type === 'date' ? 'date' : 'text'"
:maxlength="field.max ?? undefined"
:required="field.required"
class="m-input"
/>
<img v-if="field.type === 'media' && values[field.key]" :src="values[field.key]" alt="" class="mt-2 h-24 w-auto rounded-lg border border-line object-cover" />
</template>
<p v-if="field.type === 'lines'" class="mt-1 text-xs text-muted">{{ t('One per line.') }}</p>
<p v-if="field.help" class="mt-1 text-xs text-muted">{{ t(field.help) }}</p>
<p v-if="errors?.[(prefix ?? '') + field.key]" class="m-error">{{ errors[(prefix ?? '') + field.key] }}</p>
</div>
<MediaPicker v-if="picking" @pick="(url) => { values[picking!] = url; picking = null; }" @close="picking = null" />
</div>
</template>
+34
View File
@@ -0,0 +1,34 @@
<script setup lang="ts">
// A small set of line icons for the menu; an unknown name draws nothing.
defineProps<{ name?: string }>();
const paths: Record<string, string> = {
home: 'M3 11l9-8 9 8v9a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z',
file: 'M7 3h7l5 5v13H7zM14 3v5h5',
image: 'M4 5h16v14H4zM4 16l5-5 4 4 3-3 4 4M9 9h.01',
users: 'M16 20v-1a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v1M10 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6M20 20v-1a3 3 0 0 0-2-2.8M16 5.2a3 3 0 0 1 0 5.6',
group: 'M3 7h18v12H3zM8 7V5h8v2',
chart: 'M4 20V10M10 20V4M16 20v-8M22 20H2',
shield: 'M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z',
star: 'M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z',
tag: 'M3 12V4h8l10 10-8 8zM7.5 8h.01',
link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1',
cog: 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.4-2.3.9a7 7 0 0 0-2-1.2L14.2 3h-4l-.4 2.6a7 7 0 0 0-2 1.2l-2.3-.9-2 3.4 2 1.5A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.5 2 3.4 2.3-.9a7 7 0 0 0 2 1.2l.4 2.6h4l.4-2.6a7 7 0 0 0 2-1.2l2.3.9 2-3.4-2-1.5c.1-.4.1-.8.1-1.2',
};
</script>
<template>
<svg
v-if="name && paths[name]"
class="h-4 w-4 shrink-0"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path :d="paths[name]" />
</svg>
</template>
+103
View File
@@ -0,0 +1,103 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { api, boot, type NavItem } from '../api';
import { t } from '../i18n';
import { state } from '../state';
import Icon from './Icon.vue';
import Link from './Link.vue';
const open = ref(false);
const groups = computed(() => {
const list: { title: string; items: NavItem[] }[] = [];
for (const item of [{ label: 'Dashboard', href: boot.base, icon: 'home' } as NavItem, ...boot.navigation]) {
const title = item.section ?? '';
const last = list[list.length - 1];
last && last.title === title ? last.items.push(item) : list.push({ title, items: [item] });
}
return list;
});
const view = ref(boot.view);
async function switchView(): Promise<void> {
await api.put(boot.base + '/profile/view', { view: view.value === 'simple' ? 'full' : 'simple' });
window.location.assign(boot.base);
}
function active(href: string): boolean {
const path = state.path.split('?')[0];
return href === boot.base ? path === href : path === href || path.startsWith(href + '/');
}
async function logout(): Promise<void> {
const { redirect } = await api.post(boot.base + '/logout');
window.location.assign(redirect);
}
watch(() => state.path, () => (open.value = false));
</script>
<template>
<div class="min-h-screen">
<header class="fixed inset-x-0 top-0 z-40 flex h-14 items-center justify-between border-b border-line bg-panel px-4 md:hidden">
<span class="font-display font-bold">{{ boot.name }}</span>
<button type="button" class="m-btn m-btn-secondary" :aria-expanded="open" @click="open = !open">{{ t('Menu') }}</button>
</header>
<aside
class="fixed inset-y-0 left-0 z-30 flex w-60 flex-col border-r border-line bg-panel pt-14 transition-transform md:translate-x-0 md:pt-0"
:class="open ? 'translate-x-0' : '-translate-x-full'"
>
<div class="hidden h-16 items-center gap-2 px-5 md:flex">
<img v-if="boot.logo" :src="boot.logo" alt="" class="h-7 w-auto" />
<span class="font-display text-lg font-bold">{{ boot.name }}</span>
</div>
<nav class="flex-1 space-y-0.5 overflow-y-auto px-3 py-3" aria-label="Manager">
<template v-for="(group, index) in groups" :key="group.title + index">
<hr v-if="!group.title && index > 0" class="my-3 border-line" />
<p v-if="group.title" class="px-3 pb-1 pt-4 text-xs font-semibold uppercase tracking-wide text-muted">{{ t(group.title) }}</p>
<template v-for="item in group.items" :key="item.href">
<a
v-if="item.new_tab"
:href="item.href"
target="_blank"
rel="noopener"
class="flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-muted transition hover:bg-text/5 hover:text-text"
>
<Icon :name="item.icon" />{{ t(item.label) }}
</a>
<Link
v-else
:href="item.href"
class="flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition"
:class="active(item.href) ? 'bg-brand/15 text-text' : 'text-muted hover:bg-text/5 hover:text-text'"
:aria-current="active(item.href) ? 'page' : undefined"
>
<Icon :name="item.icon" />{{ t(item.label) }}
</Link>
</template>
</template>
</nav>
<div class="border-t border-line p-4">
<Link :href="boot.base + '/profile'" class="group block">
<p class="truncate text-sm font-semibold group-hover:text-brand">{{ boot.user?.name }}</p>
<p class="truncate text-xs text-muted">{{ boot.user?.email }}</p>
</Link>
<button v-if="boot.can_switch" type="button" class="m-btn m-btn-secondary mt-3 w-full justify-center" @click="switchView">
{{ view === 'simple' ? t('Show everything') : t('Simple view') }}
</button>
<button type="button" class="m-btn m-btn-secondary mt-3 w-full justify-center" @click="logout">{{ t('Log out') }}</button>
</div>
</aside>
<div v-if="open" class="fixed inset-0 z-20 bg-black/60 md:hidden" @click="open = false" />
<main class="px-4 pb-16 pt-20 md:ml-60 md:px-8 md:pt-8">
<div class="mx-auto max-w-5xl"><slot /></div>
</main>
</div>
</template>
+18
View File
@@ -0,0 +1,18 @@
<script setup lang="ts">
import { navigate } from '../state';
defineProps<{ href: string }>();
function go(event: MouseEvent, href: string): void {
// Let the browser handle new tabs and downloads.
if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) {
return;
}
event.preventDefault();
void navigate(href);
}
</script>
<template>
<a :href="href" @click="go($event, href)"><slot /></a>
</template>
+105
View File
@@ -0,0 +1,105 @@
<script setup lang="ts">
import { ref } from 'vue';
import { api, boot } from '../api';
import { t } from '../i18n';
import MediaPicker from './MediaPicker.vue';
// A Markdown text with a toolbar, photos from the media library and a preview that is rendered by the server, like the site does it.
const props = defineProps<{ modelValue: string; id?: string; rows?: number; required?: boolean; maxlength?: number }>();
const emit = defineEmits<{ 'update:modelValue': [value: string] }>();
const area = ref<HTMLTextAreaElement | null>(null);
const tab = ref<'write' | 'preview'>('write');
const html = ref('');
const loading = ref(false);
const picking = ref(false);
const canPick = boot.permissions.includes('media.view');
/** Puts `before` and `after` around the selection (or the placeholder when nothing is selected). */
function wrap(before: string, after = before, placeholder = ''): void {
const el = area.value!;
const start = el.selectionStart;
const end = el.selectionEnd;
const chosen = props.modelValue.slice(start, end) || placeholder;
const next = props.modelValue.slice(0, start) + before + chosen + after + props.modelValue.slice(end);
emit('update:modelValue', next);
requestAnimationFrame(() => {
el.focus();
el.setSelectionRange(start + before.length, start + before.length + chosen.length);
});
}
/** Puts a mark at the start of every selected line. */
function lines(mark: string): void {
const el = area.value!;
const start = props.modelValue.lastIndexOf('\n', el.selectionStart - 1) + 1;
const end = el.selectionEnd;
const block = props.modelValue.slice(start, end).split('\n').map((line) => mark + line).join('\n');
emit('update:modelValue', props.modelValue.slice(0, start) + block + props.modelValue.slice(end));
requestAnimationFrame(() => el.focus());
}
function insertImage(url: string, item?: { alt?: string | null; name?: string }): void {
picking.value = false;
const alt = (item?.alt || item?.name || '').replace(/[[\]]/g, '');
const el = area.value!;
const at = el.selectionStart;
const markup = `![${alt}](${url})`;
emit('update:modelValue', props.modelValue.slice(0, at) + markup + props.modelValue.slice(el.selectionEnd));
requestAnimationFrame(() => {
el.focus();
el.setSelectionRange(at + markup.length, at + markup.length);
});
}
async function show(next: 'write' | 'preview'): Promise<void> {
tab.value = next;
if (next === 'preview') {
loading.value = true;
try {
html.value = (await api.post(`${boot.base}/markdown`, { text: props.modelValue })).html;
} finally {
loading.value = false;
}
}
}
</script>
<template>
<div>
<div class="mb-2 flex flex-wrap items-center gap-1" role="toolbar" :aria-label="t('Formatting')">
<button type="button" class="m-btn m-btn-secondary !px-2 !py-1 font-bold" :disabled="tab === 'preview'" :title="t('Bold')" @click="wrap('**', '**', t('bold'))">B</button>
<button type="button" class="m-btn m-btn-secondary !px-2 !py-1 italic" :disabled="tab === 'preview'" :title="t('Italic')" @click="wrap('*', '*', t('italic'))">I</button>
<button type="button" class="m-btn m-btn-secondary !px-2 !py-1" :disabled="tab === 'preview'" :title="t('Heading')" @click="lines('## ')">H</button>
<button type="button" class="m-btn m-btn-secondary !px-2 !py-1" :disabled="tab === 'preview'" :title="t('List')" @click="lines('- ')">•</button>
<button type="button" class="m-btn m-btn-secondary !px-2 !py-1" :disabled="tab === 'preview'" :title="t('Quote')" @click="lines('> ')">”</button>
<button type="button" class="m-btn m-btn-secondary !px-2 !py-1" :disabled="tab === 'preview'" :title="t('Link')" @click="wrap('[', '](https://)', t('text'))">🔗</button>
<button v-if="canPick" type="button" class="m-btn m-btn-secondary !px-2 !py-1" :disabled="tab === 'preview'" @click="picking = true">{{ t('Photo') }}</button>
<span class="ml-auto flex gap-1">
<button type="button" class="m-btn !px-3 !py-1" :class="tab === 'write' ? 'm-btn-primary' : 'm-btn-secondary'" @click="show('write')">{{ t('Write') }}</button>
<button type="button" class="m-btn !px-3 !py-1" :class="tab === 'preview' ? 'm-btn-primary' : 'm-btn-secondary'" @click="show('preview')">{{ t('Preview') }}</button>
</span>
</div>
<textarea
v-show="tab === 'write'"
:id="id"
ref="area"
:value="modelValue"
:rows="rows ?? 14"
:required="required"
:maxlength="maxlength"
class="m-input font-mono"
@input="emit('update:modelValue', ($event.target as HTMLTextAreaElement).value)"
/>
<div v-if="tab === 'preview'" class="m-input min-h-40 overflow-auto">
<p v-if="loading" class="text-sm text-muted">{{ t('Loading…') }}</p>
<div v-else class="m-prose" v-html="html" />
</div>
<MediaPicker v-if="picking" @pick="insertImage" @close="picking = false" />
</div>
</template>
+36
View File
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { api, boot } from '../api';
import { t } from '../i18n';
const emit = defineEmits<{ pick: [url: string, item: { id: number; name: string; alt: string | null }]; close: [] }>();
const items = ref<{ id: number; name: string; alt: string | null; url: string; is_image: boolean }[]>([]);
const loading = ref(true);
onMounted(async () => {
try {
items.value = (await api.get(`${boot.base}/media/items`)).items.filter((item: any) => item.is_image);
} finally {
loading.value = false;
}
});
</script>
<template>
<div class="fixed inset-0 z-50 grid place-items-center bg-black/60 p-4" @click.self="emit('close')">
<div class="m-card max-h-[85vh] w-full max-w-3xl overflow-y-auto p-5" role="dialog" aria-modal="true">
<div class="mb-4 flex items-center justify-between">
<h2 class="font-display text-lg font-bold">{{ t('Choose an image') }}</h2>
<button type="button" class="m-btn m-btn-secondary" @click="emit('close')">{{ t('Cancel') }}</button>
</div>
<p v-if="loading" class="text-sm text-muted">{{ t('Loading…') }}</p>
<p v-else-if="!items.length" class="text-sm text-muted">{{ t('No images yet.') }}</p>
<div v-else class="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4">
<button v-for="item in items" :key="item.id" type="button" class="overflow-hidden rounded-lg border border-line text-left hover:border-brand" @click="emit('pick', item.url, item)">
<img :src="item.url" :alt="item.name" loading="lazy" class="aspect-square w-full object-cover" />
<span class="block truncate px-2 py-1 text-xs">{{ item.name }}</span>
</button>
</div>
</div>
</div>
</template>
+66
View File
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { api, boot } from '../api';
import { t } from '../i18n';
import { flash, reload } from '../state';
// The history of a post, a page or another record: what was saved when and by whom, and a way back.
const props = defineProps<{ type: string; id: number }>();
interface Revision { id: number; created_at: string; user: string | null; changed: string[]; current: boolean; values: Record<string, string> }
const revisions = ref<Revision[]>([]);
const canRestore = ref(false);
const open = ref<number | null>(null);
const loading = ref(true);
const base = `${boot.base}/revisions/${props.type}/${props.id}`;
onMounted(async () => {
try {
const data = await api.get(base);
revisions.value = data.revisions;
canRestore.value = data.can_restore;
} finally {
loading.value = false;
}
});
async function restore(revision: Revision): Promise<void> {
if (!window.confirm(t('Put this version back? The text now is kept in the history.'))) {
return;
}
await api.post(`${base}/${revision.id}/restore`);
flash(t('The earlier version is back.'));
await reload();
}
const when = (value: string) => new Date(value).toLocaleString(boot.locale || undefined);
</script>
<template>
<section class="m-card mt-6 max-w-3xl p-5">
<h2 class="font-display text-lg font-bold">{{ t('History') }}</h2>
<p v-if="loading" class="mt-2 text-sm text-muted">{{ t('Loading…') }}</p>
<p v-else-if="!revisions.length" class="mt-2 text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul v-else class="mt-3 divide-y divide-line">
<li v-for="revision in revisions" :key="revision.id" class="py-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<button type="button" class="text-left text-sm" :aria-expanded="open === revision.id" @click="open = open === revision.id ? null : revision.id">
<span class="font-semibold">{{ when(revision.created_at) }}</span>
<span v-if="revision.user" class="text-muted"> · {{ revision.user }}</span>
<span v-if="revision.current" class="m-badge ml-2">{{ t('Now') }}</span>
<span class="block text-xs text-muted">{{ revision.changed.join(', ') }}</span>
</button>
<button v-if="canRestore && !revision.current" type="button" class="m-btn m-btn-secondary" @click="restore(revision)">{{ t('Put back') }}</button>
</div>
<dl v-if="open === revision.id" class="mt-2 space-y-2 text-sm">
<div v-for="(value, key) in revision.values" :key="key">
<dt class="text-xs font-semibold uppercase tracking-wide text-muted">{{ key }}</dt>
<dd class="whitespace-pre-wrap break-words">{{ value }}</dd>
</div>
</dl>
</li>
</ul>
</section>
</template>
+46
View File
@@ -0,0 +1,46 @@
// Two languages for now: English (the default) and Dutch, picked from the locale the app runs in.
const nl: Record<string, string> = {
'Dashboard': 'Dashboard', 'Log in': 'Inloggen', 'Log out': 'Uitloggen', 'Email': 'E-mailadres', 'Password': 'Wachtwoord',
'Keep me logged in': 'Ingelogd blijven', 'Logging in…': 'Bezig met inloggen…', 'Log in to manage the site.': 'Log in om de site te beheren.',
'My account': 'Mijn account', 'Name': 'Naam', 'Email address': 'E-mailadres', 'What you may do': 'Wat je mag',
'Super admin: everything': 'Super admin: alles', 'Not in a group yet': 'Nog in geen groep', 'New password': 'Nieuw wachtwoord',
'Leave empty to keep the password you have.': 'Laat leeg om je wachtwoord te houden.', 'Current password': 'Huidig wachtwoord',
'At least 12 characters.': 'Minstens 12 tekens.', 'New password, once more': 'Nieuw wachtwoord, nogmaals', 'Save': 'Opslaan',
'Saving…': 'Bezig met opslaan…', 'Saved.': 'Opgeslagen.', 'Look': 'Uiterlijk', 'Theme': 'Thema', 'Posts': 'Berichten',
'New post': 'Nieuw bericht', 'Title': 'Titel', 'Status': 'Status', 'Category': 'Categorie', 'Edit': 'Bewerken', 'Delete': 'Verwijderen',
'Put online': 'Online zetten', 'Take offline': 'Offline halen', 'Draft': 'Concept', 'Scheduled': 'Ingepland', 'Published': 'Gepubliceerd',
'Are you sure?': 'Weet je het zeker?', 'No posts yet.': 'Nog geen berichten.', 'Address (slug)': 'Adres (slug)', 'Summary': 'Samenvatting',
'Text (Markdown)': 'Tekst (Markdown)', 'Cover image': 'Omslagafbeelding', 'Tags (comma separated)': 'Tags (met komma\'s)',
'Featured': 'Uitgelicht', 'Publish': 'Publiceren', 'Publish at': 'Publiceren op', 'Menu': 'Menu', 'Click the part of the picture that must stay in view.': 'Klik op het deel van de foto dat in beeld moet blijven.', 'Focus point': 'Scherpstelpunt', 'Clear': 'Wissen', 'Formatting': 'Opmaak', 'Bold': 'Vet', 'Italic': 'Cursief', 'Heading': 'Kop', 'List': 'Lijst', 'Quote': 'Citaat', 'Link': 'Link', 'bold': 'vet', 'italic': 'cursief', 'text': 'tekst', 'Photo': 'Foto', 'Write': 'Schrijven', 'Preview': 'Voorbeeld', 'History': 'Geschiedenis', 'Now': 'Nu', 'Put back': 'Terugzetten', 'Put this version back? The text now is kept in the history.': 'Deze versie terugzetten? De tekst van nu blijft bewaard in de geschiedenis.', 'The earlier version is back.': 'De eerdere versie is terug.', 'New': 'Nieuw', 'New page': 'Nieuwe pagina', 'Description for search engines': 'Omschrijving voor zoekmachines', 'One per line.': 'Eén per regel.', 'Show everything': 'Alles tonen', 'Simple view': 'Simpele weergave', 'Loading…': 'Laden…',
'You may not open this page.': 'Je mag deze pagina niet openen.', 'Something went wrong. Try again.': 'Er ging iets mis. Probeer het opnieuw.',
'This page has no screen in the manager yet.': 'Deze pagina heeft nog geen scherm in de manager.', 'Go to the dashboard': 'Naar het dashboard',
'The page expired. Reload it and try again.': 'De pagina is verlopen. Laad hem opnieuw en probeer het nog eens.', 'Back': 'Terug',
'Accounts': 'Accounts', 'New account': 'Nieuw account', 'you': 'jij', 'Super admin': 'Super admin', 'Groups': 'Groepen', 'Cancel': 'Annuleren',
'New group': 'Nieuwe groep', 'Description': 'Omschrijving', 'accounts': 'accounts', 'Categories and tags': 'Categorieën en tags',
'Categories': 'Categorieën', 'Tags': 'Tags', 'Add': 'Toevoegen', 'Rename': 'Hernoemen', 'New name': 'Nieuwe naam',
'Pages': 'Pagina\'s', 'Reviews': 'Reviews', 'Nothing here yet.': 'Hier is nog niets.', 'Previous': 'Vorige', 'Next': 'Volgende', 'Media': 'Media',
'Choose an image': 'Kies een afbeelding', 'No images yet.': 'Nog geen afbeeldingen.', 'Uploaded.': 'Geüpload.', 'Upload': 'Uploaden',
'Uploading…': 'Bezig met uploaden…', 'This file is in use. Delete it anyway?': 'Dit bestand is in gebruik. Toch verwijderen?',
'Largest file': 'Grootste bestand', 'Alternative text': 'Alternatieve tekst', 'Used': 'Gebruikt', 'No files yet.': 'Nog geen bestanden.', 'Choose': 'Kiezen',
'Audit log': 'Auditlog', 'Addresses banned': 'Geblokkeerde adressen', 'Logins (24 h)': 'Logins (24 u)', 'Failed logins (24 h)': 'Mislukte logins (24 u)',
'Refused (24 h)': 'Geweigerd (24 u)', 'all': 'alles', 'logins': 'logins', 'failed': 'mislukt', 'actions': 'acties', 'viewed': 'bekeken', 'refused': 'geweigerd', 'bans': 'blokkades',
'Search': 'Zoeken', 'Account': 'Account', 'Everyone': 'Iedereen', 'Filter': 'Filteren', 'Someone': 'Iemand', 'banned': 'geblokkeerd', 'Ban': 'Blokkeren', 'Bans': 'Blokkades',
'Minutes (0 = until lifted)': 'Minuten (0 = tot opgeheven)', 'Reason': 'Reden', 'Whole site': 'Hele site', 'No bans.': 'Geen blokkades.', 'automatic': 'automatisch',
'whole site': 'hele site', 'hits': 'pogingen', 'Lift': 'Opheffen', 'Rules': 'Regels', 'until lifted': 'tot opgeheven',
'Ban an address by itself after too many failed logins': 'Een adres zelf blokkeren na te veel mislukte logins', 'Failed logins': 'Mislukte logins', 'Within minutes': 'Binnen minuten',
'Ban for minutes (0 = until lifted)': 'Blokkeren voor minuten (0 = tot opgeheven)', 'Keep the log (days)': 'Log bewaren (dagen)', 'Notes about addresses': 'Notities over adressen',
'Group': 'Groep', 'Note': 'Notitie', 'Statistics': 'Statistieken', 'compared with': 'vergeleken met', 'Visitors': 'Bezoekers', 'Visits': 'Bezoeken', 'Page views': 'Paginaweergaven',
'Average time': 'Gemiddelde tijd', 'Bounce rate': 'Bouncepercentage', 'Channels': 'Kanalen', 'Sources': 'Bronnen', 'Countries': 'Landen', 'Devices': 'Apparaten', 'Browsers': 'Browsers',
'Systems': 'Systemen', 'Direct': 'Direct', 'When people visit': 'Wanneer mensen komen', 'Programs': 'Programma\'s', 'Download': 'Downloaden',
'Open': 'Openen', 'Created.': 'Aangemaakt.', 'Deleted.': 'Verwijderd.',
};
let words: Record<string, string> = {};
export function setLocale(locale: string): void {
words = locale.toLowerCase().startsWith('nl') ? nl : {};
}
export function t(text: string): string {
return words[text] ?? text;
}
+31
View File
@@ -0,0 +1,31 @@
import * as Vue from 'vue';
import App from './App.vue';
import { api, boot } from './api';
import FormFields from './components/FormFields.vue';
import Icon from './components/Icon.vue';
import Link from './components/Link.vue';
import MediaPicker from './components/MediaPicker.vue';
import { setLocale, t } from './i18n';
import { flash, navigate, register, start } from './state';
import './style.css';
setLocale(boot.locale);
// What a site's own bundle (config `manager.extensions`) may use. Its `import 'vue'` is mapped to this very Vue (see
// resources/dist/vue.js), so its components share the reactivity of the screens.
(window as any).IriksManager = { Vue, boot, api, t, flash, navigate, register, components: { Link, FormFields, Icon, MediaPicker } };
async function run(): Promise<void> {
for (const url of boot.extensions ?? []) {
try {
await import(/* @vite-ignore */ url);
} catch (error) {
console.error(`Manager extension ${url} did not load`, error);
}
}
Vue.createApp(App).mount('#manager');
start();
}
void run();
+103
View File
@@ -0,0 +1,103 @@
<script setup lang="ts">
import { ref } from 'vue';
import { api, boot, useForm } from '../api';
import { t } from '../i18n';
import { flash, reload } from '../state';
interface Group { id: number; name: string; description: string | null; can_give: boolean }
interface Account {
id: number; name: string; email: string; is_super_admin: boolean; is_you: boolean;
groups: { id: number; name: string }[]; can_change: boolean; can_delete: boolean;
}
defineProps<{ accounts: Account[]; groups: Group[] }>();
const editing = ref<Account | 'new' | null>(null);
const form = useForm({ name: '', email: '', password: '', groups: [] as number[] });
function open(account: Account | 'new'): void {
editing.value = account;
form.errors = {};
form.values.name = account === 'new' ? '' : account.name;
form.values.email = account === 'new' ? '' : account.email;
form.values.password = '';
form.values.groups = account === 'new' ? [] : account.groups.map((g) => g.id);
}
async function save(): Promise<void> {
const account = editing.value;
const saved = account === 'new'
? await form.send('post', `${boot.base}/accounts`)
: await form.send('put', `${boot.base}/accounts/${(account as Account).id}`);
if (saved) {
flash(t('Saved.'));
editing.value = null;
await reload();
}
}
async function remove(account: Account): Promise<void> {
if (window.confirm(t('Are you sure?'))) {
await api.delete(`${boot.base}/accounts/${account.id}`);
flash(t('Deleted.'));
await reload();
}
}
</script>
<template>
<div class="mb-6 flex flex-wrap items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ t('Accounts') }}</h1>
<button type="button" class="m-btn m-btn-primary" @click="open('new')">{{ t('New account') }}</button>
</div>
<form v-if="editing" class="m-card mb-6 max-w-2xl space-y-4 p-5" @submit.prevent="save">
<div class="grid gap-4 sm:grid-cols-2">
<div>
<label class="m-label" for="a-name">{{ t('Name') }}</label>
<input id="a-name" v-model="form.values.name" required maxlength="255" class="m-input" />
<p v-if="form.errors.name" class="m-error">{{ form.errors.name }}</p>
</div>
<div>
<label class="m-label" for="a-email">{{ t('Email address') }}</label>
<input id="a-email" v-model="form.values.email" type="email" required maxlength="255" class="m-input" />
<p v-if="form.errors.email" class="m-error">{{ form.errors.email }}</p>
</div>
</div>
<div>
<label class="m-label" for="a-pass">{{ t('Password') }}</label>
<input id="a-pass" v-model="form.values.password" type="password" minlength="12" maxlength="200" :required="editing === 'new'" class="m-input" autocomplete="new-password" />
<p class="m-help">{{ editing === 'new' ? t('At least 12 characters.') : t('Leave empty to keep the password you have.') }}</p>
<p v-if="form.errors.password" class="m-error">{{ form.errors.password }}</p>
</div>
<fieldset v-if="groups.length">
<legend class="m-label">{{ t('Groups') }}</legend>
<label v-for="group in groups" :key="group.id" class="flex items-center gap-2 py-0.5 text-sm" :class="group.can_give ? '' : 'opacity-50'">
<input v-model="form.values.groups" type="checkbox" :value="group.id" :disabled="!group.can_give" />
{{ group.name }}
</label>
</fieldset>
<div class="flex gap-2">
<button type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ form.busy ? t('Saving…') : t('Save') }}</button>
<button type="button" class="m-btn m-btn-secondary" @click="editing = null">{{ t('Cancel') }}</button>
</div>
</form>
<ul class="m-card divide-y divide-line">
<li v-for="account in accounts" :key="account.id" class="flex flex-wrap items-center justify-between gap-3 p-4">
<div class="min-w-0">
<p class="truncate font-semibold">{{ account.name }} <span v-if="account.is_you" class="text-xs font-normal text-muted">({{ t('you') }})</span></p>
<p class="truncate text-xs text-muted">{{ account.email }}</p>
<p class="mt-1 flex flex-wrap gap-1">
<span v-if="account.is_super_admin" class="m-badge">{{ t('Super admin') }}</span>
<span v-for="group in account.groups" :key="group.id" class="m-badge">{{ group.name }}</span>
</p>
</div>
<div class="flex gap-2">
<button v-if="account.can_change" type="button" class="m-btn m-btn-secondary" @click="open(account)">{{ t('Edit') }}</button>
<button v-if="account.can_delete" type="button" class="m-btn m-btn-danger" @click="remove(account)">{{ t('Delete') }}</button>
</div>
</li>
</ul>
</template>
+171
View File
@@ -0,0 +1,171 @@
<script setup lang="ts">
import { reactive } from 'vue';
import { api, boot, useForm } from '../api';
import Link from '../components/Link.vue';
import { t } from '../i18n';
import { flash, navigate, reload } from '../state';
interface Entry {
id: number; at: string; event: string; summary: string; subject: { type: string; label: string; url: string | null } | null;
details: Record<string, any>; who: string | null; email: string | null; ip: string | null; browser: string | null;
banned: boolean; never_banned: boolean;
}
interface Ban { id: number; ip: string; reason: string | null; automatic: boolean; whole_site: boolean; by: string | null; hits: number; expires_at: string | null; active: boolean }
const props = defineProps<{
entries: Entry[]; pagination: { page: number; pages: number; total: number };
filters: { show: string; user: number | null; ip: string; q: string };
accounts: { id: number; name: string }[];
summary: { logins: number; failed: number; refused: number; banned: number };
bans: Ban[]; notes: { ip: string; group: string | null; note: string; by: string | null }[];
settings: { auto_ban: boolean; max_failures: number; window_minutes: number; ban_minutes: number; keep_days: number };
max_keep_days: number; can_manage: boolean; my_ip: string; never_banned: string[]; whole_site_bans: boolean;
}>();
const tabs = ['all', 'logins', 'failed', 'actions', 'viewed', 'refused', 'bans'];
const search = reactive({ q: props.filters.q, ip: props.filters.ip, user: props.filters.user ?? '' });
const when = (iso: string) => new Date(iso).toLocaleString();
function go(extra: Record<string, string | number>): void {
const query = new URLSearchParams();
const merged: Record<string, string | number> = { show: props.filters.show, q: search.q, ip: search.ip, user: search.user, ...extra };
for (const [key, value] of Object.entries(merged)) {
value !== '' && value !== 'all' && value !== 1 && query.set(key, String(value));
}
void navigate(`${boot.base}/audit${query.size ? '?' + query : ''}`);
}
const ban = useForm({ ip: '', minutes: 1440, reason: '', whole_site: false });
async function banIp(ip?: string): Promise<void> {
if (ip) {
ban.values.ip = ip;
}
const done = await ban.send<{ message: string }>('post', `${boot.base}/audit/bans`);
if (done) {
flash(done.message);
ban.values.ip = ban.values.reason = '';
await reload();
}
}
async function lift(item: Ban): Promise<void> {
flash((await api.delete(`${boot.base}/audit/bans/${item.id}`)).message);
await reload();
}
const rules = useForm({ ...props.settings });
async function saveRules(): Promise<void> {
if (await rules.send('put', `${boot.base}/audit/settings`)) {
flash(t('Saved.'));
await reload();
}
}
const note = useForm({ ip: '', group: '', note: '' });
async function saveNote(): Promise<void> {
if (await note.send('put', `${boot.base}/audit/notes`)) {
flash(t('Saved.'));
note.values.ip = note.values.group = note.values.note = '';
await reload();
}
}
const expires = (item: Ban) => (item.expires_at ? when(item.expires_at) : t('until lifted'));
</script>
<template>
<h1 class="font-display mb-6 text-2xl font-bold">{{ t('Audit log') }}</h1>
<div class="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4">
<div v-for="(value, key) in summary" :key="key" class="m-card p-4">
<p class="text-2xl font-bold">{{ value }}</p>
<p class="m-help">{{ t(key === 'banned' ? 'Addresses banned' : key === 'logins' ? 'Logins (24 h)' : key === 'failed' ? 'Failed logins (24 h)' : 'Refused (24 h)') }}</p>
</div>
</div>
<nav class="mb-4 flex flex-wrap gap-2">
<button v-for="tab in tabs" :key="tab" type="button" class="m-btn" :class="filters.show === tab ? 'm-btn-primary' : 'm-btn-secondary'" @click="go({ show: tab, page: 1 })">{{ t(tab) }}</button>
</nav>
<form class="mb-4 flex flex-wrap gap-2" @submit.prevent="go({ page: 1 })">
<input v-model="search.q" class="m-input max-w-xs" :placeholder="t('Search')" :aria-label="t('Search')" />
<input v-model="search.ip" class="m-input max-w-[12rem]" placeholder="IP" aria-label="IP" />
<select v-model="search.user" class="m-input max-w-[12rem]" :aria-label="t('Account')">
<option value="">{{ t('Everyone') }}</option>
<option v-for="account in accounts" :key="account.id" :value="account.id">{{ account.name }}</option>
</select>
<button type="submit" class="m-btn m-btn-secondary">{{ t('Filter') }}</button>
</form>
<p v-if="!entries.length" class="m-card p-5 text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul v-else class="m-card divide-y divide-line">
<li v-for="entry in entries" :key="entry.id" class="flex flex-wrap items-start justify-between gap-3 p-4 text-sm">
<div class="min-w-0">
<p class="font-semibold">{{ entry.summary }}
<template v-if="entry.subject">
· <Link v-if="entry.subject.url" :href="entry.subject.url" class="underline">{{ entry.subject.label }}</Link><span v-else>{{ entry.subject.label }}</span>
</template>
</p>
<p class="text-xs text-muted">{{ when(entry.at) }} · {{ entry.who ?? entry.email ?? t('Someone') }} · {{ entry.ip }} · {{ entry.browser }}</p>
</div>
<span class="flex gap-2">
<span v-if="entry.banned" class="m-badge">{{ t('banned') }}</span>
<button v-if="can_manage && entry.ip && !entry.banned && !entry.never_banned && entry.ip !== my_ip" type="button" class="m-btn m-btn-danger" @click="banIp(entry.ip)">{{ t('Ban') }}</button>
</span>
</li>
</ul>
<nav v-if="pagination.pages > 1" class="mt-4 flex items-center gap-2">
<button v-if="pagination.page > 1" type="button" class="m-btn m-btn-secondary" @click="go({ page: pagination.page - 1 })">{{ t('Previous') }}</button>
<span class="text-sm text-muted">{{ pagination.page }} / {{ pagination.pages }}</span>
<button v-if="pagination.page < pagination.pages" type="button" class="m-btn m-btn-secondary" @click="go({ page: pagination.page + 1 })">{{ t('Next') }}</button>
</nav>
<h2 class="font-display mb-3 mt-10 text-xl font-bold">{{ t('Bans') }}</h2>
<form v-if="can_manage" class="m-card mb-4 flex max-w-3xl flex-wrap items-end gap-3 p-4" @submit.prevent="banIp()">
<div><label class="m-label" for="b-ip">IP</label><input id="b-ip" v-model="ban.values.ip" required class="m-input" /></div>
<div><label class="m-label" for="b-min">{{ t('Minutes (0 = until lifted)') }}</label><input id="b-min" v-model.number="ban.values.minutes" type="number" min="0" class="m-input w-32" /></div>
<div class="min-w-[10rem] flex-1"><label class="m-label" for="b-why">{{ t('Reason') }}</label><input id="b-why" v-model="ban.values.reason" maxlength="200" class="m-input" /></div>
<label v-if="whole_site_bans" class="flex items-center gap-2 text-sm"><input v-model="ban.values.whole_site" type="checkbox" /> {{ t('Whole site') }}</label>
<button type="submit" class="m-btn m-btn-danger">{{ t('Ban') }}</button>
<p v-if="ban.errors.ip" class="m-error w-full">{{ ban.errors.ip }}</p>
</form>
<p v-if="!bans.length" class="text-sm text-muted">{{ t('No bans.') }}</p>
<ul v-else class="m-card divide-y divide-line">
<li v-for="item in bans" :key="item.id" class="flex flex-wrap items-center justify-between gap-3 p-4 text-sm" :class="item.active ? '' : 'opacity-50'">
<div>
<p class="font-semibold">{{ item.ip }} <span v-if="item.automatic" class="m-badge">{{ t('automatic') }}</span> <span v-if="item.whole_site" class="m-badge">{{ t('whole site') }}</span></p>
<p class="text-xs text-muted">{{ item.reason }} · {{ expires(item) }} · {{ item.hits }} {{ t('hits') }}</p>
</div>
<button v-if="can_manage && item.active" type="button" class="m-btn m-btn-secondary" @click="lift(item)">{{ t('Lift') }}</button>
</li>
</ul>
<template v-if="can_manage">
<h2 class="font-display mb-3 mt-10 text-xl font-bold">{{ t('Rules') }}</h2>
<form class="m-card grid max-w-3xl gap-4 p-5 sm:grid-cols-2" @submit.prevent="saveRules">
<label class="flex items-center gap-2 text-sm sm:col-span-2"><input v-model="rules.values.auto_ban" type="checkbox" /> {{ t('Ban an address by itself after too many failed logins') }}</label>
<div><label class="m-label" for="r-max">{{ t('Failed logins') }}</label><input id="r-max" v-model.number="rules.values.max_failures" type="number" min="3" max="100" class="m-input" /></div>
<div><label class="m-label" for="r-win">{{ t('Within minutes') }}</label><input id="r-win" v-model.number="rules.values.window_minutes" type="number" min="1" max="1440" class="m-input" /></div>
<div><label class="m-label" for="r-ban">{{ t('Ban for minutes (0 = until lifted)') }}</label><input id="r-ban" v-model.number="rules.values.ban_minutes" type="number" min="0" class="m-input" /></div>
<div><label class="m-label" for="r-keep">{{ t('Keep the log (days)') }}</label><input id="r-keep" v-model.number="rules.values.keep_days" type="number" min="7" :max="max_keep_days" class="m-input" /><p class="m-help">≤ {{ max_keep_days }}</p></div>
<div class="sm:col-span-2"><button type="submit" class="m-btn m-btn-primary" :disabled="rules.busy">{{ t('Save') }}</button></div>
<template v-for="(message, field) in rules.errors" :key="field"><p class="m-error sm:col-span-2">{{ message }}</p></template>
</form>
<h2 class="font-display mb-3 mt-10 text-xl font-bold">{{ t('Notes about addresses') }}</h2>
<form class="m-card mb-4 flex max-w-3xl flex-wrap items-end gap-3 p-4" @submit.prevent="saveNote">
<div><label class="m-label" for="n-ip">IP</label><input id="n-ip" v-model="note.values.ip" required class="m-input" /></div>
<div><label class="m-label" for="n-group">{{ t('Group') }}</label><input id="n-group" v-model="note.values.group" maxlength="60" class="m-input" /></div>
<div class="min-w-[10rem] flex-1"><label class="m-label" for="n-note">{{ t('Note') }}</label><input id="n-note" v-model="note.values.note" maxlength="2000" class="m-input" /></div>
<button type="submit" class="m-btn m-btn-secondary">{{ t('Save') }}</button>
<p v-if="note.errors.ip" class="m-error w-full">{{ note.errors.ip }}</p>
</form>
<ul v-if="notes.length" class="m-card divide-y divide-line text-sm">
<li v-for="item in notes" :key="item.ip" class="p-3"><b>{{ item.ip }}</b> <span v-if="item.group" class="m-badge">{{ item.group }}</span> {{ item.note }}</li>
</ul>
</template>
</template>
+17
View File
@@ -0,0 +1,17 @@
<script setup lang="ts">
import { boot } from '../api';
import Link from '../components/Link.vue';
import { t } from '../i18n';
defineProps<{ navigation: { label: string; href: string }[] }>();
</script>
<template>
<h1 class="font-display mb-6 text-2xl font-bold">{{ t('Dashboard') }}</h1>
<p class="mb-4 text-muted">{{ boot.user?.name }}</p>
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<Link v-for="item in navigation" :key="item.href" :href="item.href" class="m-card block p-5 font-semibold transition hover:border-brand">
{{ t(item.label) }}
</Link>
</div>
</template>
+12
View File
@@ -0,0 +1,12 @@
<script setup lang="ts">
import { boot } from '../api';
import Link from '../components/Link.vue';
import { t } from '../i18n';
</script>
<template>
<div class="m-card max-w-xl p-6">
<p class="text-sm">{{ t('This page has no screen in the manager yet.') }}</p>
<Link :href="boot.base" class="m-btn m-btn-secondary mt-4">{{ t('Go to the dashboard') }}</Link>
</div>
</template>
+97
View File
@@ -0,0 +1,97 @@
<script setup lang="ts">
import { ref } from 'vue';
import { api, boot, useForm } from '../api';
import { t } from '../i18n';
import { flash, reload } from '../state';
interface Perm { value: string; label: string; needs: string[] }
interface Group { id: number; name: string; description: string | null; permissions: string[]; accounts: number }
const props = defineProps<{ groups: Group[]; catalogue: { section: string; permissions: Perm[] }[] }>();
const editing = ref<Group | 'new' | null>(null);
const form = useForm({ name: '', description: '', permissions: [] as string[] });
const all = props.catalogue.flatMap((s) => s.permissions);
function open(group: Group | 'new'): void {
editing.value = group;
form.errors = {};
form.values.name = group === 'new' ? '' : group.name;
form.values.description = group === 'new' ? '' : (group.description ?? '');
form.values.permissions = group === 'new' ? [] : [...group.permissions];
}
/** A permission that needs others brings them along; the server does the same, this only shows it. */
function toggled(perm: Perm): void {
if (form.values.permissions.includes(perm.value)) {
form.values.permissions = [...new Set([...form.values.permissions, ...perm.needs])];
} else {
form.values.permissions = form.values.permissions.filter((value) => !all.find((p) => p.value === value)?.needs.includes(perm.value));
}
}
async function save(): Promise<void> {
const group = editing.value;
const saved = group === 'new'
? await form.send('post', `${boot.base}/groups`)
: await form.send('put', `${boot.base}/groups/${(group as Group).id}`);
if (saved) {
flash(t('Saved.'));
editing.value = null;
await reload();
}
}
async function remove(group: Group): Promise<void> {
if (window.confirm(t('Are you sure?'))) {
await api.delete(`${boot.base}/groups/${group.id}`);
flash(t('Deleted.'));
await reload();
}
}
</script>
<template>
<div class="mb-6 flex flex-wrap items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ t('Groups') }}</h1>
<button type="button" class="m-btn m-btn-primary" @click="open('new')">{{ t('New group') }}</button>
</div>
<form v-if="editing" class="m-card mb-6 max-w-3xl space-y-4 p-5" @submit.prevent="save">
<div>
<label class="m-label" for="g-name">{{ t('Name') }}</label>
<input id="g-name" v-model="form.values.name" required maxlength="60" class="m-input" />
<p v-if="form.errors.name" class="m-error">{{ form.errors.name }}</p>
</div>
<div>
<label class="m-label" for="g-desc">{{ t('Description') }}</label>
<textarea id="g-desc" v-model="form.values.description" rows="2" maxlength="500" class="m-input" />
</div>
<fieldset v-for="section in catalogue" :key="section.section" class="rounded-lg border border-line p-3">
<legend class="px-1 text-sm font-semibold">{{ section.section }}</legend>
<label v-for="perm in section.permissions" :key="perm.value" class="flex items-center gap-2 py-0.5 text-sm">
<input v-model="form.values.permissions" type="checkbox" :value="perm.value" @change="toggled(perm)" />
{{ perm.label }}
</label>
</fieldset>
<div class="flex gap-2">
<button type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ form.busy ? t('Saving…') : t('Save') }}</button>
<button type="button" class="m-btn m-btn-secondary" @click="editing = null">{{ t('Cancel') }}</button>
</div>
</form>
<p v-if="!groups.length" class="m-card p-5 text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul v-else class="m-card divide-y divide-line">
<li v-for="group in groups" :key="group.id" class="flex flex-wrap items-center justify-between gap-3 p-4">
<div class="min-w-0">
<p class="font-semibold">{{ group.name }} <span class="text-xs font-normal text-muted">· {{ group.accounts }} {{ t('accounts') }}</span></p>
<p v-if="group.description" class="text-xs text-muted">{{ group.description }}</p>
</div>
<div class="flex gap-2">
<button type="button" class="m-btn m-btn-secondary" @click="open(group)">{{ t('Edit') }}</button>
<button type="button" class="m-btn m-btn-danger" @click="remove(group)">{{ t('Delete') }}</button>
</div>
</li>
</ul>
</template>
+66
View File
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { ref } from 'vue';
import { api, boot, ApiError } from '../api';
import { t } from '../i18n';
import { flash, reload } from '../state';
type Label = { name: string; posts: number };
defineProps<{ categories: Label[]; tags: Label[] }>();
const kinds = [
{ type: 'category', title: 'Categories' },
{ type: 'tag', title: 'Tags' },
] as const;
const adding = ref<Record<string, string>>({ category: '', tag: '' });
const error = ref('');
async function run(action: () => Promise<unknown>): Promise<void> {
error.value = '';
try {
await action();
await reload();
} catch (e) {
if (e instanceof ApiError && e.status === 422) {
error.value = Object.values(e.errors)[0] ?? e.message;
} else {
throw e;
}
}
}
const add = (type: string) => run(async () => {
await api.post(`${boot.base}/labels`, { type, name: adding.value[type] });
adding.value[type] = '';
flash(t('Created.'));
});
const rename = (type: string, name: string) => {
const to = window.prompt(t('New name'), name);
return to && to !== name ? run(() => api.put(`${boot.base}/labels`, { type, name, new_name: to })) : undefined;
};
const remove = (type: string, name: string) =>
window.confirm(t('Are you sure?')) ? run(() => api.delete(`${boot.base}/labels`, { type, name })) : undefined;
</script>
<template>
<h1 class="font-display mb-6 text-2xl font-bold">{{ t('Categories and tags') }}</h1>
<p v-if="error" class="m-error mb-4">{{ error }}</p>
<div class="grid gap-6 md:grid-cols-2">
<section v-for="kind in kinds" :key="kind.type" class="m-card p-4">
<h2 class="mb-3 font-semibold">{{ t(kind.title) }}</h2>
<form class="mb-3 flex gap-2" @submit.prevent="add(kind.type)">
<input v-model="adding[kind.type]" required maxlength="60" class="m-input" :aria-label="t(kind.title)" />
<button type="submit" class="m-btn m-btn-primary">{{ t('Add') }}</button>
</form>
<ul class="divide-y divide-line">
<li v-for="label in kind.type === 'category' ? categories : tags" :key="label.name" class="flex items-center justify-between gap-2 py-2 text-sm">
<span class="min-w-0 truncate">{{ label.name }} <span class="text-xs text-muted">· {{ label.posts }}</span></span>
<span class="flex gap-1">
<button type="button" class="m-btn m-btn-secondary" @click="rename(kind.type, label.name)">{{ t('Rename') }}</button>
<button type="button" class="m-btn m-btn-danger" @click="remove(kind.type, label.name)">{{ t('Delete') }}</button>
</span>
</li>
</ul>
</section>
</div>
</template>
+34
View File
@@ -0,0 +1,34 @@
<script setup lang="ts">
import { computed } from 'vue';
import Link from '../components/Link.vue';
import { t } from '../i18n';
import { state } from '../state';
// Pages and reviews are still plain lists (a paginated answer), so one read-only screen shows both.
const props = defineProps<{ data: Record<string, any>[]; current_page: number; last_page: number; path: string }>();
const kind = computed(() => (state.path.includes('/reviews') ? 'reviews' : 'pages'));
const heading = computed(() => (kind.value === 'reviews' ? 'Reviews' : 'Pages'));
const title = (row: Record<string, any>) => (kind.value === 'reviews' ? row.author : row.title);
const detail = (row: Record<string, any>) => (kind.value === 'reviews' ? (row.rating ? '★'.repeat(row.rating) : '') : row.slug);
const live = (row: Record<string, any>) => (kind.value === 'reviews' ? row.is_visible : row.is_published);
const page = (n: number) => `${state.path.split('?')[0]}?page=${n}`;
</script>
<template>
<h1 class="font-display mb-6 text-2xl font-bold">{{ t(heading) }}</h1>
<p v-if="!props.data.length" class="m-card p-5 text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul v-else class="m-card divide-y divide-line">
<li v-for="row in props.data" :key="row.id" class="flex items-center justify-between gap-3 p-4">
<div class="min-w-0">
<p class="truncate font-semibold">{{ title(row) }}</p>
<p class="truncate text-xs text-muted">{{ detail(row) }}</p>
</div>
<span class="m-badge">{{ live(row) ? t('Published') : t('Draft') }}</span>
</li>
</ul>
<nav v-if="props.last_page > 1" class="mt-4 flex gap-2">
<Link v-if="props.current_page > 1" :href="page(props.current_page - 1)" class="m-btn m-btn-secondary">{{ t('Previous') }}</Link>
<Link v-if="props.current_page < props.last_page" :href="page(props.current_page + 1)" class="m-btn m-btn-secondary">{{ t('Next') }}</Link>
</nav>
</template>
+91
View File
@@ -0,0 +1,91 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { boot, useForm } from '../api';
import { t } from '../i18n';
// What a check of the site adds to the form (config `manager.login.checks`): fields, and the Turnstile captcha.
const extra = boot.login_fields ?? [];
const form = useForm({ email: '', password: '', remember: false, ...Object.fromEntries(extra.map((field) => [field.name, ''])) } as Record<string, any>);
const widget = ref<HTMLElement | null>(null);
let widgetId: string | undefined;
onMounted(() => {
const captcha = extra.find((field) => field.type === 'turnstile');
if (!captcha) {
return;
}
const draw = () => {
widgetId = (window as any).turnstile.render(widget.value, { sitekey: captcha.site_key, callback: (token: string) => (form.values[captcha.name] = token) });
};
if ((window as any).turnstile) {
draw();
} else {
const script = document.createElement('script');
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
script.async = true;
script.onload = draw;
document.head.appendChild(script);
}
});
async function submit(): Promise<void> {
const done = await form.send<{ redirect: string }>('post', boot.base + '/login');
if (done) {
window.location.assign(done.redirect);
} else {
form.values.password = '';
// A token works once.
widgetId !== undefined && (window as any).turnstile.reset(widgetId);
extra.filter((field) => field.type === 'turnstile').forEach((field) => (form.values[field.name] = ''));
}
}
</script>
<template>
<div class="grid min-h-screen place-items-center px-4">
<form class="m-card w-full max-w-sm p-7" @submit.prevent="submit">
<img v-if="boot.logo" :src="boot.logo" alt="" class="mb-4 h-9 w-auto" />
<h1 class="font-display text-2xl font-bold">{{ boot.name }}</h1>
<p class="mt-1 text-sm text-muted">{{ t('Log in to manage the site.') }}</p>
<div class="mt-6">
<label for="email" class="m-label">{{ t('Email') }}</label>
<input id="email" v-model="form.values.email" type="email" autocomplete="username" required autofocus class="m-input" />
<p v-if="form.errors.email" class="m-error">{{ form.errors.email }}</p>
</div>
<div class="mt-4">
<label for="password" class="m-label">{{ t('Password') }}</label>
<input id="password" v-model="form.values.password" type="password" autocomplete="current-password" required class="m-input" />
<p v-if="form.errors.password" class="m-error">{{ form.errors.password }}</p>
</div>
<template v-for="field in extra" :key="field.name">
<div v-if="field.type === 'turnstile'" class="mt-4">
<div :ref="(el: any) => (widget = el)" />
<p v-if="form.errors[field.name]" class="m-error">{{ form.errors[field.name] }}</p>
</div>
<div v-else class="mt-4">
<label :for="'login-' + field.name" class="m-label">{{ t(field.label ?? field.name) }}</label>
<input
:id="'login-' + field.name"
v-model="form.values[field.name]"
:type="field.type === 'password' || field.type === 'number' ? field.type : 'text'"
:autocomplete="field.autocomplete"
:required="field.required"
class="m-input"
/>
<p v-if="form.errors[field.name]" class="m-error">{{ form.errors[field.name] }}</p>
</div>
</template>
<label class="mt-4 flex items-center gap-2 text-sm text-muted">
<input v-model="form.values.remember" type="checkbox" />
{{ t('Keep me logged in') }}
</label>
<button type="submit" class="m-btn m-btn-primary mt-6 w-full justify-center" :disabled="form.busy">
{{ form.busy ? t('Logging in…') : t('Log in') }}
</button>
</form>
</div>
</template>
+148
View File
@@ -0,0 +1,148 @@
<script setup lang="ts">
import { ref } from 'vue';
import { ApiError, api, boot, upload, useForm } from '../api';
import { t } from '../i18n';
import { flash, reload } from '../state';
interface Item {
id: number; name: string; filename: string; url: string; mime_type: string; is_image: boolean; size: number;
width: number | null; height: number | null; alt: string | null; focus_x: number | null; focus_y: number | null; uploaded_by: string | null; usage_count: number;
}
defineProps<{
items: Item[]; max_file_mb: number; extensions: string[];
storage: { used: number; limit: number; left: number };
}>();
const can = (permission: string) => boot.permissions.includes(permission);
const busy = ref(false);
const selected = ref<Item | null>(null);
const form = useForm({ name: '', alt: '', focus_x: null as number | null, focus_y: null as number | null });
const size = (bytes: number) => (bytes > 1e6 ? `${(bytes / 1e6).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1e3))} kB`);
function choose(item: Item): void {
selected.value = item;
form.errors = {};
form.values.name = item.name;
form.values.alt = item.alt ?? '';
form.values.focus_x = item.focus_x;
form.values.focus_y = item.focus_y;
}
/** The point of the picture that must stay in view when the site crops it: set with a click. */
function setFocus(event: MouseEvent): void {
if (!can('media.edit')) {
return;
}
const box = (event.currentTarget as HTMLElement).getBoundingClientRect();
form.values.focus_x = Math.round(Math.min(1, Math.max(0, (event.clientX - box.left) / box.width)) * 1000) / 1000;
form.values.focus_y = Math.round(Math.min(1, Math.max(0, (event.clientY - box.top) / box.height)) * 1000) / 1000;
}
const position = (x: number | null, y: number | null) => `${(x ?? 0.5) * 100}% ${(y ?? 0.5) * 100}%`;
async function send(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
busy.value = true;
try {
for (const file of Array.from(input.files ?? [])) {
const data = new FormData();
data.append('file', file);
await upload(`${boot.base}/media`, data);
}
flash(t('Uploaded.'));
await reload();
} catch (error) {
flash(error instanceof ApiError ? (Object.values(error.errors)[0] ?? error.message) : t('Something went wrong. Try again.'), true);
} finally {
busy.value = false;
input.value = '';
}
}
async function save(): Promise<void> {
if (selected.value && (await form.send('put', `${boot.base}/media/${selected.value.id}`))) {
flash(t('Saved.'));
selected.value = null;
await reload();
}
}
async function remove(item: Item): Promise<void> {
const warning = item.usage_count > 0 ? t('This file is in use. Delete it anyway?') : t('Are you sure?');
if (window.confirm(warning)) {
await api.delete(`${boot.base}/media/${item.id}`);
selected.value = null;
flash(t('Deleted.'));
await reload();
}
}
</script>
<template>
<div class="mb-6 flex flex-wrap items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ t('Media') }}</h1>
<label v-if="can('media.upload')" class="m-btn m-btn-primary cursor-pointer" :class="busy ? 'opacity-50' : ''">
{{ busy ? t('Uploading…') : t('Upload') }}
<input type="file" multiple class="sr-only" :accept="extensions.map((e) => '.' + e).join(',')" :disabled="busy" @change="send" />
</label>
</div>
<div class="mb-6 max-w-md" :title="`${size(storage.used)} / ${size(storage.limit)}`">
<div class="h-2 overflow-hidden rounded-full bg-panel-2">
<div class="h-full bg-brand" :style="{ width: Math.min(100, (storage.used / Math.max(1, storage.limit)) * 100) + '%' }" />
</div>
<p class="m-help">{{ size(storage.used) }} / {{ size(storage.limit) }} · {{ t('Largest file') }}: {{ max_file_mb }} MB</p>
</div>
<form v-if="selected" class="m-card mb-6 flex max-w-3xl flex-wrap gap-5 p-5" @submit.prevent="save">
<div v-if="selected.is_image" class="w-full shrink-0 sm:w-64">
<div class="relative" :class="can('media.edit') ? 'cursor-crosshair' : ''" @click="setFocus">
<img :src="selected.url" :alt="selected.alt ?? ''" class="w-full rounded-lg" draggable="false" />
<span
v-if="form.values.focus_x !== null"
class="pointer-events-none absolute h-5 w-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-brand/60 shadow"
:style="{ left: (form.values.focus_x ?? 0) * 100 + '%', top: (form.values.focus_y ?? 0) * 100 + '%' }"
/>
</div>
<p class="m-help">{{ can('media.edit') ? t('Click the part of the picture that must stay in view.') : t('Focus point') }}</p>
<div class="mt-2 flex items-center gap-2">
<img :src="selected.url" alt="" class="h-16 w-16 rounded-lg object-cover" :style="{ objectPosition: position(form.values.focus_x, form.values.focus_y) }" />
<button v-if="can('media.edit') && form.values.focus_x !== null" type="button" class="m-btn m-btn-secondary" @click="form.values.focus_x = form.values.focus_y = null">{{ t('Clear') }}</button>
</div>
</div>
<div class="min-w-0 flex-1 space-y-3">
<div>
<label class="m-label" for="m-name">{{ t('Name') }}</label>
<input id="m-name" v-model="form.values.name" required maxlength="250" class="m-input" :disabled="!can('media.edit')" />
<p v-if="form.errors.name" class="m-error">{{ form.errors.name }}</p>
</div>
<div v-if="selected.is_image">
<label class="m-label" for="m-alt">{{ t('Alternative text') }}</label>
<input id="m-alt" v-model="form.values.alt" maxlength="500" class="m-input" :disabled="!can('media.edit')" />
</div>
<p class="m-help">
{{ selected.mime_type }} · {{ size(selected.size) }}<span v-if="selected.width"> · {{ selected.width }}×{{ selected.height }}</span>
· {{ t('Used') }}: {{ selected.usage_count }}<span v-if="selected.uploaded_by"> · {{ selected.uploaded_by }}</span>
</p>
<p class="m-help break-all">{{ selected.url }}</p>
<div class="flex gap-2">
<button v-if="can('media.edit')" type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ t('Save') }}</button>
<button v-if="can('media.delete')" type="button" class="m-btn m-btn-danger" @click="remove(selected)">{{ t('Delete') }}</button>
<button type="button" class="m-btn m-btn-secondary" @click="selected = null">{{ t('Cancel') }}</button>
</div>
</div>
</form>
<p v-if="!items.length" class="m-card p-5 text-sm text-muted">{{ t('No files yet.') }}</p>
<div v-else class="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
<button v-for="item in items" :key="item.id" type="button" class="m-card overflow-hidden text-left transition hover:border-brand" :class="selected?.id === item.id ? 'border-brand' : ''" @click="choose(item)">
<img v-if="item.is_image" :src="item.url" :alt="item.alt ?? ''" loading="lazy" class="aspect-square w-full object-cover" />
<span v-else class="grid aspect-square w-full place-items-center text-xs text-muted">{{ item.mime_type }}</span>
<span class="block truncate px-2 py-1.5 text-xs">{{ item.name }}</span>
</button>
</div>
</template>
+71
View File
@@ -0,0 +1,71 @@
<script setup lang="ts">
import { api, boot, useForm } from '../api';
import FormFields, { type Field } from '../components/FormFields.vue';
import MarkdownEditor from '../components/MarkdownEditor.vue';
import Link from '../components/Link.vue';
import RevisionsPanel from '../components/RevisionsPanel.vue';
import { t } from '../i18n';
import { flash, navigate } from '../state';
const props = defineProps<{
page: {
id: number | null; slug: string; title: string; meta_description: string; defined: boolean; fields: Field[];
content: Record<string, any> | null; body: string | null; is_published: boolean | null;
};
}>();
const page = props.page;
const form = useForm({
title: page.title,
meta_description: page.meta_description ?? '',
...(page.defined ? { content: { ...page.content } } : { body: page.body ?? '', is_published: page.is_published ?? false }),
} as Record<string, any>);
async function submit(): Promise<void> {
if (await form.send('put', `${boot.base}/pages/${page.slug}`)) {
flash(t('Saved.'));
}
}
async function remove(): Promise<void> {
if (!window.confirm(t('Are you sure?'))) {
return;
}
await api.delete(`${boot.base}/pages/${page.slug}`);
void navigate(`${boot.base}/pages`);
}
</script>
<template>
<div class="mb-6 flex items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ page.title }}</h1>
<Link :href="boot.base + '/pages'" class="m-btn m-btn-secondary">{{ t('Back') }}</Link>
</div>
<form class="m-card max-w-3xl space-y-5 p-5" @submit.prevent="submit">
<div>
<label for="title" class="m-label">{{ t('Title') }}</label>
<input id="title" v-model="form.values.title" required maxlength="255" class="m-input" />
<p v-if="form.errors.title" class="m-error">{{ form.errors.title }}</p>
</div>
<div>
<label for="meta" class="m-label">{{ t('Description for search engines') }}</label>
<input id="meta" v-model="form.values.meta_description" maxlength="255" class="m-input" />
<p v-if="form.errors.meta_description" class="m-error">{{ form.errors.meta_description }}</p>
</div>
<FormFields v-if="page.defined" :fields="page.fields" :values="form.values.content" :errors="form.errors" prefix="content." />
<template v-else>
<div>
<label for="body" class="m-label">{{ t('Text (Markdown)') }}</label>
<MarkdownEditor id="body" v-model="form.values.body" />
<p v-if="form.errors.body" class="m-error">{{ form.errors.body }}</p>
</div>
<label class="flex items-center gap-2 text-sm"><input v-model="form.values.is_published" type="checkbox" /> {{ t('Publish') }}</label>
</template>
<div class="flex gap-3">
<button type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ form.busy ? t('Saving…') : t('Save') }}</button>
<button v-if="!page.defined" type="button" class="m-btn m-btn-danger" @click="remove">{{ t('Delete') }}</button>
</div>
</form>
<RevisionsPanel v-if="page.id && boot.permissions.includes('revisions.view')" type="pages" :id="page.id" />
</template>
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { boot, useForm } from '../api';
import Link from '../components/Link.vue';
import { t } from '../i18n';
import { navigate } from '../state';
defineProps<{ pages: { slug: string; title: string; defined: boolean; saved: boolean; is_published?: boolean; updated_at: string | null }[] }>();
const form = useForm({ slug: '', title: '' });
async function create(): Promise<void> {
if (await form.send('post', `${boot.base}/pages`)) {
void navigate(`${boot.base}/pages/${form.values.slug}`);
}
}
</script>
<template>
<h1 class="font-display mb-6 text-2xl font-bold">{{ t('Pages') }}</h1>
<ul class="m-card divide-y divide-line">
<li v-for="page in pages" :key="page.slug" class="flex items-center justify-between gap-3 p-4">
<div class="min-w-0">
<p class="truncate font-semibold">{{ page.title }}</p>
<p class="truncate text-xs text-muted">/{{ page.slug }}</p>
</div>
<div class="flex items-center gap-2">
<span v-if="!page.defined" class="m-badge">{{ page.is_published ? t('Published') : t('Draft') }}</span>
<Link :href="`${boot.base}/pages/${page.slug}`" class="m-btn m-btn-secondary">{{ t('Edit') }}</Link>
</div>
</li>
<li v-if="!pages.length" class="p-4 text-sm text-muted">{{ t('Nothing here yet.') }}</li>
</ul>
<form class="m-card mt-6 grid max-w-3xl gap-4 p-5 sm:grid-cols-[1fr_1fr_auto] sm:items-end" @submit.prevent="create">
<div>
<label for="new-title" class="m-label">{{ t('Title') }}</label>
<input id="new-title" v-model="form.values.title" required maxlength="255" class="m-input" />
<p v-if="form.errors.title" class="m-error">{{ form.errors.title }}</p>
</div>
<div>
<label for="new-slug" class="m-label">{{ t('Address (slug)') }}</label>
<input id="new-slug" v-model="form.values.slug" required maxlength="120" class="m-input" />
<p v-if="form.errors.slug" class="m-error">{{ form.errors.slug }}</p>
</div>
<button type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ t('New page') }}</button>
</form>
</template>
+95
View File
@@ -0,0 +1,95 @@
<script setup lang="ts">
import { boot, useForm } from '../api';
import { ref } from 'vue';
import Link from '../components/Link.vue';
import MarkdownEditor from '../components/MarkdownEditor.vue';
import MediaPicker from '../components/MediaPicker.vue';
import RevisionsPanel from '../components/RevisionsPanel.vue';
import { t } from '../i18n';
import { flash, navigate } from '../state';
const props = defineProps<{ post: Record<string, any> | null; categories: string[]; known_tags: string[] }>();
const post = props.post;
const form = useForm({
title: post?.title ?? '', slug: post?.slug ?? '', excerpt: post?.excerpt ?? '', body: post?.body ?? '',
cover_image: post?.cover_image ?? '', category: post?.category ?? '', tags: (post?.tags ?? []) as string[],
is_featured: post?.is_featured ?? false, is_published: post?.is_published ?? false, published_at: post?.published_at ?? '',
});
const picking = ref(false);
// Tags are typed as one comma separated line.
let tagLine = (post?.tags ?? []).join(', ');
async function submit(): Promise<void> {
form.values.tags = tagLine.split(',').map((tag: string) => tag.trim()).filter(Boolean);
const saved = post
? await form.send('put', `${boot.base}/posts/${post.id}`)
: await form.send('post', `${boot.base}/posts`);
if (saved) {
flash(t(post ? 'Saved.' : 'Created.'));
void navigate(`${boot.base}/posts`);
}
}
</script>
<template>
<div class="mb-6 flex items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ post ? post.title : t('New post') }}</h1>
<Link :href="boot.base + '/posts'" class="m-btn m-btn-secondary">{{ t('Back') }}</Link>
</div>
<form class="m-card max-w-3xl space-y-5 p-5" @submit.prevent="submit">
<div>
<label for="title" class="m-label">{{ t('Title') }}</label>
<input id="title" v-model="form.values.title" required maxlength="255" class="m-input" />
<p v-if="form.errors.title" class="m-error">{{ form.errors.title }}</p>
</div>
<div class="grid gap-5 sm:grid-cols-2">
<div>
<label for="slug" class="m-label">{{ t('Address (slug)') }}</label>
<input id="slug" v-model="form.values.slug" maxlength="255" class="m-input" />
<p v-if="form.errors.slug" class="m-error">{{ form.errors.slug }}</p>
</div>
<div>
<label for="category" class="m-label">{{ t('Category') }}</label>
<input id="category" v-model="form.values.category" list="categories" maxlength="60" class="m-input" />
<datalist id="categories"><option v-for="category in categories" :key="category" :value="category" /></datalist>
</div>
</div>
<div>
<label for="excerpt" class="m-label">{{ t('Summary') }}</label>
<textarea id="excerpt" v-model="form.values.excerpt" rows="2" maxlength="500" class="m-input" />
<p v-if="form.errors.excerpt" class="m-error">{{ form.errors.excerpt }}</p>
</div>
<div>
<label for="body" class="m-label">{{ t('Text (Markdown)') }}</label>
<MarkdownEditor id="body" v-model="form.values.body" required />
<p v-if="form.errors.body" class="m-error">{{ form.errors.body }}</p>
</div>
<div class="grid gap-5 sm:grid-cols-2">
<div>
<label for="cover" class="m-label">{{ t('Cover image') }}</label>
<div class="flex gap-2">
<input id="cover" v-model="form.values.cover_image" maxlength="2048" class="m-input" />
<button v-if="boot.permissions.includes('media.view')" type="button" class="m-btn m-btn-secondary shrink-0" @click="picking = true">{{ t('Choose') }}</button>
</div>
</div>
<div>
<label for="tags" class="m-label">{{ t('Tags (comma separated)') }}</label>
<input id="tags" v-model="tagLine" list="known-tags" class="m-input" />
<datalist id="known-tags"><option v-for="tag in known_tags" :key="tag" :value="tag" /></datalist>
</div>
</div>
<div class="flex flex-wrap items-center gap-6">
<label class="flex items-center gap-2 text-sm"><input v-model="form.values.is_featured" type="checkbox" /> {{ t('Featured') }}</label>
<label v-if="boot.permissions.includes('posts.publish')" class="flex items-center gap-2 text-sm"><input v-model="form.values.is_published" type="checkbox" /> {{ t('Publish') }}</label>
<div v-if="form.values.is_published">
<label for="at" class="m-label">{{ t('Publish at') }}</label>
<input id="at" v-model="form.values.published_at" type="datetime-local" class="m-input" />
</div>
</div>
<button type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ form.busy ? t('Saving…') : t('Save') }}</button>
</form>
<RevisionsPanel v-if="post && boot.permissions.includes('revisions.view')" type="posts" :id="post.id" />
<MediaPicker v-if="picking" @pick="(url) => { form.values.cover_image = url; picking = false; }" @close="picking = false" />
</template>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import { api, boot } from '../api';
import Link from '../components/Link.vue';
import { t } from '../i18n';
import { flash, reload } from '../state';
interface Post {
id: number; title: string; slug: string; category: string | null; status: 'draft' | 'scheduled' | 'published';
can_change: boolean; can_delete: boolean;
}
defineProps<{ posts: Post[] }>();
const label = { draft: 'Draft', scheduled: 'Scheduled', published: 'Published' } as const;
async function online(post: Post): Promise<void> {
await api.put(`${boot.base}/posts/${post.id}/online`, { online: post.status !== 'published' });
await reload();
}
async function remove(post: Post): Promise<void> {
if (!window.confirm(t('Are you sure?'))) {
return;
}
await api.delete(`${boot.base}/posts/${post.id}`);
flash(t('Deleted.'));
await reload();
}
</script>
<template>
<div class="mb-6 flex flex-wrap items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ t('Posts') }}</h1>
<Link v-if="boot.permissions.includes('posts.write')" :href="boot.base + '/posts/create'" class="m-btn m-btn-primary">{{ t('New post') }}</Link>
</div>
<p v-if="!posts.length" class="m-card p-5 text-sm text-muted">{{ t('No posts yet.') }}</p>
<ul v-else class="m-card divide-y divide-line">
<li v-for="post in posts" :key="post.id" class="flex flex-wrap items-center justify-between gap-3 p-4">
<div class="min-w-0">
<p class="truncate font-semibold">{{ post.title }}</p>
<p class="mt-1 flex items-center gap-2 text-xs text-muted">
<span class="m-badge">{{ t(label[post.status]) }}</span>
<span v-if="post.category">{{ post.category }}</span>
</p>
</div>
<div class="flex gap-2">
<button v-if="boot.permissions.includes('posts.publish') && post.can_change" type="button" class="m-btn m-btn-secondary" @click="online(post)">
{{ post.status === 'published' ? t('Take offline') : t('Put online') }}
</button>
<Link v-if="post.can_change" :href="`${boot.base}/posts/${post.id}/edit`" class="m-btn m-btn-secondary">{{ t('Edit') }}</Link>
<button v-if="post.can_delete" type="button" class="m-btn m-btn-danger" @click="remove(post)">{{ t('Delete') }}</button>
</div>
</li>
</ul>
</template>
+93
View File
@@ -0,0 +1,93 @@
<script setup lang="ts">
import { boot, useForm } from '../api';
import { t } from '../i18n';
import { flash } from '../state';
const props = defineProps<{
profile: {
name: string; email: string; is_super_admin: boolean; groups: string[]; theme: string;
themes: { key: string; label: string; colors: Record<string, string> }[];
};
}>();
const form = useForm({ name: props.profile.name, theme: props.profile.theme, current_password: '', password: '', password_confirmation: '' });
async function submit(): Promise<void> {
const saved = await form.send('put', boot.base + '/profile');
if (saved) {
flash(t('Saved.'));
// The look is set by the page that was served: load it again with the new choice.
if (form.values.theme !== boot.theme) {
window.location.reload();
}
form.values.current_password = form.values.password = form.values.password_confirmation = '';
}
}
</script>
<template>
<h1 class="font-display mb-6 text-2xl font-bold">{{ t('My account') }}</h1>
<form class="m-card max-w-xl space-y-5 p-5" @submit.prevent="submit">
<div>
<label for="name" class="m-label">{{ t('Name') }}</label>
<input id="name" v-model="form.values.name" type="text" required maxlength="255" class="m-input" autocomplete="name" />
<p v-if="form.errors.name" class="m-error">{{ form.errors.name }}</p>
</div>
<div>
<span class="m-label">{{ t('Email address') }}</span>
<p class="text-sm">{{ profile.email }}</p>
</div>
<div>
<span class="m-label">{{ t('What you may do') }}</span>
<p class="flex flex-wrap gap-1.5">
<span v-if="profile.is_super_admin" class="m-badge">{{ t('Super admin: everything') }}</span>
<template v-else>
<span v-for="group in profile.groups" :key="group" class="m-badge">{{ group }}</span>
<span v-if="!profile.groups.length" class="m-badge">{{ t('Not in a group yet') }}</span>
</template>
</p>
</div>
<fieldset v-if="profile.themes.length" class="rounded-lg border border-line p-4">
<legend class="px-1.5 text-sm font-semibold">{{ t('Look') }}</legend>
<div class="mt-1 flex flex-wrap gap-3">
<label
v-for="theme in profile.themes"
:key="theme.key"
class="flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm"
:class="form.values.theme === theme.key ? 'border-brand' : 'border-line'"
>
<input v-model="form.values.theme" type="radio" name="theme" :value="theme.key" class="sr-only" />
<span class="flex">
<span v-for="name in ['ink', 'panel', 'brand']" :key="name" class="h-4 w-4 border border-line" :style="{ background: theme.colors[name] }" />
</span>
{{ theme.label }}
</label>
</div>
<p v-if="form.errors.theme" class="m-error">{{ form.errors.theme }}</p>
</fieldset>
<fieldset class="space-y-4 rounded-lg border border-line p-4">
<legend class="px-1.5 text-sm font-semibold">{{ t('New password') }}</legend>
<p class="m-help">{{ t('Leave empty to keep the password you have.') }}</p>
<div>
<label for="current_password" class="m-label">{{ t('Current password') }}</label>
<input id="current_password" v-model="form.values.current_password" type="password" class="m-input" autocomplete="current-password" />
<p v-if="form.errors.current_password" class="m-error">{{ form.errors.current_password }}</p>
</div>
<div>
<label for="password" class="m-label">{{ t('New password') }}</label>
<input id="password" v-model="form.values.password" type="password" minlength="12" maxlength="200" class="m-input" autocomplete="new-password" />
<p class="m-help">{{ t('At least 12 characters.') }}</p>
<p v-if="form.errors.password" class="m-error">{{ form.errors.password }}</p>
</div>
<div>
<label for="password_confirmation" class="m-label">{{ t('New password, once more') }}</label>
<input id="password_confirmation" v-model="form.values.password_confirmation" type="password" maxlength="200" class="m-input" autocomplete="new-password" />
</div>
</fieldset>
<button type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ form.busy ? t('Saving…') : t('Save') }}</button>
</form>
</template>
+35
View File
@@ -0,0 +1,35 @@
<script setup lang="ts">
import { boot, useForm } from '../api';
import FormFields, { type Field } from '../components/FormFields.vue';
import Link from '../components/Link.vue';
import { t } from '../i18n';
import { flash, navigate } from '../state';
const props = defineProps<{
resource: { key: string; label: string; singular: string; fields: Field[] };
record: { id: number | null; values: Record<string, any> };
}>();
const base = `${boot.base}/records/${props.resource.key}`;
const form = useForm({ ...props.record.values });
async function submit(): Promise<void> {
const saved = props.record.id === null ? await form.send('post', base) : await form.send('put', `${base}/${props.record.id}`);
if (saved) {
flash(t('Saved.'));
void navigate(base);
}
}
</script>
<template>
<div class="mb-6 flex items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ record.id === null ? t('New') + ': ' + t(resource.singular) : t(resource.singular) }}</h1>
<Link :href="base" class="m-btn m-btn-secondary">{{ t('Back') }}</Link>
</div>
<form class="m-card max-w-3xl space-y-5 p-5" @submit.prevent="submit">
<FormFields :fields="resource.fields" :values="form.values" :errors="form.errors" />
<button type="submit" class="m-btn m-btn-primary" :disabled="form.busy">{{ form.busy ? t('Saving…') : t('Save') }}</button>
</form>
</template>
+68
View File
@@ -0,0 +1,68 @@
<script setup lang="ts">
import { api, boot } from '../api';
import type { Field } from '../components/FormFields.vue';
import Link from '../components/Link.vue';
import { t } from '../i18n';
import { reload } from '../state';
const props = defineProps<{
resource: { key: string; label: string; singular: string; columns: string[]; fields: Field[]; can_manage: boolean };
rows: { id: number; values: Record<string, any> }[];
current_page: number;
last_page: number;
}>();
const base = `${boot.base}/records/${props.resource.key}`;
const labelOf = (key: string) => props.resource.fields.find((field) => field.key === key)?.label ?? key;
function shown(row: { values: Record<string, any> }, key: string): string {
const value = row.values[key];
const field = props.resource.fields.find((f) => f.key === key);
if (field?.type === 'toggle') {
return value ? '✓' : '';
}
return field?.type === 'select' ? (field.options[value] ?? value) : String(value ?? '');
}
async function remove(row: { id: number }): Promise<void> {
if (!window.confirm(t('Are you sure?'))) {
return;
}
await api.delete(`${base}/${row.id}`);
await reload();
}
</script>
<template>
<div class="mb-6 flex items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ t(resource.label) }}</h1>
<Link v-if="resource.can_manage" :href="base + '/create'" class="m-btn m-btn-primary">{{ t('Add') }}</Link>
</div>
<p v-if="!rows.length" class="m-card p-5 text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<div v-else class="m-card overflow-x-auto">
<table class="w-full text-left text-sm">
<thead class="border-b border-line text-xs uppercase tracking-wide text-muted">
<tr>
<th v-for="column in resource.columns" :key="column" class="px-4 py-3 font-semibold">{{ t(labelOf(column)) }}</th>
<th v-if="resource.can_manage" class="px-4 py-3" />
</tr>
</thead>
<tbody class="divide-y divide-line">
<tr v-for="row in rows" :key="row.id">
<td v-for="column in resource.columns" :key="column" class="max-w-xs truncate px-4 py-3">{{ shown(row, column) }}</td>
<td v-if="resource.can_manage" class="flex justify-end gap-2 px-4 py-2">
<Link :href="`${base}/${row.id}/edit`" class="m-btn m-btn-secondary">{{ t('Edit') }}</Link>
<button type="button" class="m-btn m-btn-danger" @click="remove(row)">{{ t('Delete') }}</button>
</td>
</tr>
</tbody>
</table>
</div>
<nav v-if="last_page > 1" class="mt-4 flex gap-2">
<Link v-if="current_page > 1" :href="`${base}?page=${current_page - 1}`" class="m-btn m-btn-secondary">{{ t('Previous') }}</Link>
<Link v-if="current_page < last_page" :href="`${base}?page=${current_page + 1}`" class="m-btn m-btn-secondary">{{ t('Next') }}</Link>
</nav>
</template>
+103
View File
@@ -0,0 +1,103 @@
<script setup lang="ts">
import { computed } from 'vue';
import { boot } from '../api';
import Link from '../components/Link.vue';
import { t } from '../i18n';
import { state } from '../state';
type Totals = { visitors: number; visits: number; page_views: number; average_seconds: number; bounce_rate: number };
type Row = { name: string; visits: number; channel?: string };
const props = defineProps<{
range: { key: string; label: string; from: string; to: string; compared_to: string | null };
ranges: { key: string; label: string }[]; exports: Record<string, string>;
totals: Totals; previous: Totals | null;
series: { key: string; label: string; visitors: number; visits: number; page_views: number; bot_hits: number }[];
pages: { path: string; title: string | null; views: number; average_seconds: number }[];
posts: { title: string; slug: string; views: number; average_seconds: number }[];
channels: Row[]; sources: Row[]; countries: Row[]; devices: Row[]; browsers: Row[]; systems: Row[];
heatmap: { day: string; hours: number[] }[];
bots: { total: number; previous: number | null; names: { name: string; kind: string; hits: number }[]; kinds: { name: string; hits: number }[]; pages: { path: string; hits: number }[] };
}>();
const tiles = computed(() => [
['Visitors', 'visitors'], ['Visits', 'visits'], ['Page views', 'page_views'], ['Average time', 'average_seconds'], ['Bounce rate', 'bounce_rate'],
] as const);
const value = (key: keyof Totals, n: number) => (key === 'average_seconds' ? `${Math.floor(n / 60)}:${String(n % 60).padStart(2, '0')}` : key === 'bounce_rate' ? `${n}%` : n.toLocaleString());
const change = (key: keyof Totals) => {
const before = props.previous?.[key];
return before ? Math.round(((props.totals[key] - before) / before) * 100) : null;
};
const top = computed(() => Math.max(1, ...props.series.map((s) => s.visits)));
const heat = computed(() => Math.max(1, ...props.heatmap.flatMap((row) => row.hours)));
const lists = computed(() => [
['Channels', props.channels], ['Sources', props.sources], ['Countries', props.countries], ['Devices', props.devices], ['Browsers', props.browsers], ['Systems', props.systems],
] as const);
const rangeLink = (key: string) => `${boot.base}/statistics?range=${key}`;
const csv = (sheet: string) => `${boot.base}/statistics/export?sheet=${sheet}&range=${new URLSearchParams(state.path.split('?')[1] ?? '').get('range') ?? props.range.key}`;
</script>
<template>
<div class="mb-6 flex flex-wrap items-center justify-between gap-3">
<h1 class="font-display text-2xl font-bold">{{ t('Statistics') }}</h1>
<p class="text-sm text-muted">{{ range.from }} → {{ range.to }}<span v-if="range.compared_to"> · {{ t('compared with') }} {{ range.compared_to }}</span></p>
</div>
<nav class="mb-6 flex flex-wrap gap-2">
<Link v-for="item in ranges" :key="item.key" :href="rangeLink(item.key)" class="m-btn" :class="range.key === item.key ? 'm-btn-primary' : 'm-btn-secondary'">{{ item.label }}</Link>
</nav>
<div class="mb-6 grid grid-cols-2 gap-3 md:grid-cols-5">
<div v-for="[label, key] in tiles" :key="key" class="m-card p-4">
<p class="text-2xl font-bold">{{ value(key, totals[key]) }}</p>
<p class="m-help">{{ t(label) }}<span v-if="change(key) !== null" :class="(change(key) ?? 0) >= 0 ? 'text-emerald-500' : 'text-red-500'"> {{ (change(key) ?? 0) > 0 ? '+' : '' }}{{ change(key) }}%</span></p>
</div>
</div>
<section class="m-card mb-6 p-4">
<h2 class="mb-3 font-semibold">{{ t('Visits') }}</h2>
<div class="flex h-40 items-end gap-px" role="img" :aria-label="t('Visits')">
<div v-for="point in series" :key="point.key" class="min-w-px flex-1 rounded-t bg-brand" :style="{ height: Math.max(2, (point.visits / top) * 100) + '%' }" :title="`${point.label}: ${point.visits}`" />
</div>
</section>
<div class="mb-6 grid gap-6 md:grid-cols-2">
<section class="m-card p-4">
<h2 class="mb-3 font-semibold">{{ t('Pages') }}</h2>
<p v-if="!pages.length" class="text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul class="divide-y divide-line text-sm"><li v-for="row in pages" :key="row.path" class="flex justify-between gap-3 py-1.5"><span class="truncate">{{ row.title ?? row.path }}</span><span class="text-muted">{{ row.views }}</span></li></ul>
</section>
<section class="m-card p-4">
<h2 class="mb-3 font-semibold">{{ t('Posts') }}</h2>
<p v-if="!posts.length" class="text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul class="divide-y divide-line text-sm"><li v-for="row in posts" :key="row.slug" class="flex justify-between gap-3 py-1.5"><span class="truncate">{{ row.title }}</span><span class="text-muted">{{ row.views }}</span></li></ul>
</section>
<section v-for="[title, rows] in lists" :key="title" class="m-card p-4">
<h2 class="mb-3 font-semibold">{{ t(title) }}</h2>
<p v-if="!rows.length" class="text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul class="divide-y divide-line text-sm"><li v-for="row in rows" :key="row.name + (row.channel ?? '')" class="flex justify-between gap-3 py-1.5"><span class="truncate">{{ row.name || t('Direct') }}</span><span class="text-muted">{{ row.visits }}</span></li></ul>
</section>
</div>
<section class="m-card mb-6 overflow-x-auto p-4">
<h2 class="mb-3 font-semibold">{{ t('When people visit') }}</h2>
<div class="space-y-0.5 text-xs">
<div v-for="row in heatmap" :key="row.day" class="flex items-center gap-0.5">
<span class="w-9 shrink-0 text-muted">{{ row.day }}</span>
<span v-for="(n, hour) in row.hours" :key="hour" class="block h-5 min-w-3 flex-1 rounded-sm border border-line" :title="`${row.day} ${hour}:00 · ${n}`" :style="{ background: `color-mix(in srgb, var(--m-brand) ${Math.round((n / heat) * 100)}%, var(--m-panel-2))` }" />
</div>
</div>
</section>
<section class="m-card mb-6 p-4">
<h2 class="mb-3 font-semibold">{{ t('Programs') }} <span class="text-sm font-normal text-muted">· {{ bots.total }}</span></h2>
<p v-if="!bots.names.length" class="text-sm text-muted">{{ t('Nothing here yet.') }}</p>
<ul class="divide-y divide-line text-sm"><li v-for="row in bots.names" :key="row.name" class="flex justify-between gap-3 py-1.5"><span>{{ row.name }} <span class="text-xs text-muted">{{ row.kind }}</span></span><span class="text-muted">{{ row.hits }}</span></li></ul>
</section>
<p class="flex flex-wrap items-center gap-2 text-sm">
<span class="text-muted">{{ t('Download') }}:</span>
<a v-for="(label, sheet) in exports" :key="sheet" :href="csv(String(sheet))" class="m-btn m-btn-secondary">{{ label }} (CSV)</a>
</p>
</template>
+121
View File
@@ -0,0 +1,121 @@
import { reactive } from 'vue';
import { ApiError, api, boot } from './api';
import { t } from './i18n';
import Dashboard from './pages/Dashboard.vue';
import Fallback from './pages/Fallback.vue';
import Login from './pages/Login.vue';
import PostForm from './pages/PostForm.vue';
import PostsIndex from './pages/PostsIndex.vue';
import Profile from './pages/Profile.vue';
import AccountsIndex from './pages/AccountsIndex.vue';
import GroupsIndex from './pages/GroupsIndex.vue';
import LabelsIndex from './pages/LabelsIndex.vue';
import MediaLibrary from './pages/MediaLibrary.vue';
import AuditLog from './pages/AuditLog.vue';
import StatisticsReport from './pages/StatisticsReport.vue';
import ListPage from './pages/ListPage.vue';
import RecordForm from './pages/RecordForm.vue';
import RecordsIndex from './pages/RecordsIndex.vue';
import PageForm from './pages/PageForm.vue';
import PagesIndex from './pages/PagesIndex.vue';
/** The screens that exist. Every other manager address shows `Fallback` until its module gets a screen. */
const routes: { pattern: RegExp; component: any; guest?: boolean; data?: boolean; source?: string }[] = [
{ pattern: /^\/?$/, component: Dashboard, data: true },
{ pattern: /^\/login$/, component: Login, guest: true },
{ pattern: /^\/profile$/, component: Profile, data: true },
{ pattern: /^\/posts$/, component: PostsIndex, data: true },
{ pattern: /^\/posts\/create$/, component: PostForm, data: true },
{ pattern: /^\/posts\/\d+\/edit$/, component: PostForm, data: true },
{ pattern: /^\/media$/, component: MediaLibrary, data: true, source: '/media/items' },
{ pattern: /^\/audit$/, component: AuditLog, data: true },
{ pattern: /^\/statistics$/, component: StatisticsReport, data: true },
{ pattern: /^\/accounts$/, component: AccountsIndex, data: true },
{ pattern: /^\/groups$/, component: GroupsIndex, data: true },
{ pattern: /^\/labels$/, component: LabelsIndex, data: true },
{ pattern: /^\/pages$/, component: PagesIndex, data: true },
{ pattern: /^\/pages\/[a-z0-9]+(?:-[a-z0-9]+)*$/, component: PageForm, data: true },
{ pattern: /^\/records\/[a-z][a-z0-9_]*$/, component: RecordsIndex, data: true },
{ pattern: /^\/records\/[a-z][a-z0-9_]*\/(create|\d+\/edit)$/, component: RecordForm, data: true },
{ pattern: /^\/reviews$/, component: ListPage, data: true },
];
/**
* A screen of a site's own bundle (config `manager.extensions`): `pattern` is a regular expression for the path inside the
* manager, `data` fetches the same address (or `source`) as JSON and passes it as props. Its screens win over the built in ones.
*/
export function register(pattern: string, component: any, options: { data?: boolean; source?: string } = {}): void {
routes.unshift({ pattern: new RegExp(pattern), component, data: options.data, source: options.source });
}
export const state = reactive({
path: '',
component: null as any,
props: {} as Record<string, any>,
loading: true,
forbidden: false,
toast: null as { text: string; error: boolean } | null,
});
let timer: number | undefined;
export function flash(text: string, error = false): void {
state.toast = { text, error };
window.clearTimeout(timer);
timer = window.setTimeout(() => (state.toast = null), 4000);
}
/** The path inside the manager: without the base, without the query. */
function inside(url: string): string {
return url.split('?')[0].slice(boot.base.length) || '/';
}
export async function load(url: string): Promise<void> {
const route = routes.find((r) => r.pattern.test(inside(url)));
if (!boot.user && !route?.guest) {
window.location.assign(boot.base + '/login');
return;
}
if (boot.user && route?.guest) {
return navigate(boot.base, true);
}
state.loading = true;
state.forbidden = false;
state.path = url;
state.component = route?.component ?? Fallback;
state.props = {};
try {
state.props = route?.data ? await api.get(route.source ? boot.base + route.source : url) : {};
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
window.location.assign(boot.base + '/login');
} else if (error instanceof ApiError && error.status === 403) {
state.forbidden = true;
} else {
flash(t('Something went wrong. Try again.'), true);
}
} finally {
state.loading = false;
}
}
export function navigate(url: string, replace = false): Promise<void> {
window.history[replace ? 'replaceState' : 'pushState']({}, '', url);
window.scrollTo(0, 0);
return load(url);
}
export function reload(): Promise<void> {
return load(state.path);
}
export function start(): void {
window.addEventListener('popstate', () => load(window.location.pathname + window.location.search));
void load(window.location.pathname + window.location.search);
}
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more