Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afad275408 | ||
|
|
2063f52698 | ||
|
|
45f4ed2660 | ||
|
|
fc51dd5bdb | ||
|
|
a5e640b31b | ||
|
|
3e8a73d3da | ||
|
|
bb1f4e1292 | ||
|
|
41d82a969a | ||
|
|
541d1ee690 | ||
|
|
a921f14d85 | ||
|
|
69ed8c742a | ||
|
|
258c25efe1 | ||
|
|
a378fdf345 | ||
|
|
96e3fead0a | ||
|
|
5c0a94f167 | ||
|
|
1e002ed0c5 | ||
|
|
6a51b0e649 | ||
|
|
6b41bfddd3 | ||
|
|
6fdb02040b | ||
|
|
eb37a7c6fb | ||
|
|
3345797141 | ||
|
|
37a29d9195 | ||
|
|
517039b625 | ||
|
|
ce1a8a1370 | ||
|
|
c7d0971813 | ||
|
|
6f31a54818 | ||
|
|
362a5bce2e | ||
|
|
e39ca4ba0a | ||
|
|
a34965d4b7 | ||
|
|
56de8ee76a | ||
|
|
60ad85a621 | ||
|
|
984024eb85 | ||
|
|
c49c1e3909 | ||
|
|
60f836088b | ||
|
|
b23b0c1c53 | ||
|
|
f2dad190c0 | ||
|
|
ef9a83496c | ||
|
|
c05950c0e3 | ||
|
|
6df410c37b | ||
|
|
a25a421028 | ||
|
|
8bc583bd19 | ||
|
|
65f6ac91ac | ||
|
|
548bb66d0e | ||
|
|
775f8ef789 | ||
|
|
e593274b19 | ||
|
|
9a98f633ab | ||
|
|
441d76ef96 | ||
|
|
9ff162460d | ||
|
|
4934d18f2a | ||
|
|
1c9ccadf4e | ||
|
|
0caa196908 | ||
|
|
d14de1d44d | ||
|
|
6993ad3557 | ||
|
|
351667abaf | ||
|
|
4bf0a8bbb0 | ||
|
|
6f4d9b44f2 | ||
|
|
ebb5063ed1 | ||
|
|
a8055c69f8 | ||
|
|
e0299bf77b | ||
|
|
f7cbd6c621 | ||
|
|
e570b849f2 | ||
|
|
81ea30f038 | ||
|
|
cebb66b7d6 | ||
|
|
2f6789147e | ||
|
|
3d6b92497c | ||
|
|
556dfce585 | ||
|
|
f0cb58d7e5 | ||
|
|
4e77e4b427 | ||
|
|
7482ee489b | ||
|
|
2c00fa8f07 | ||
|
|
594e69c0cf | ||
|
|
acb8620621 | ||
|
|
d2ea1bacac | ||
|
|
b75403e5ea | ||
|
|
b863f9a346 | ||
|
|
2539dfcc3e | ||
|
|
98d12db241 | ||
|
|
498ffd4462 | ||
|
|
5a0b53025b | ||
|
|
da5bace656 | ||
|
|
5c0eec9477 | ||
|
|
22cbe043f1 | ||
|
|
a0d7840158 | ||
|
|
16fdfc887c | ||
|
|
02f0ec5149 | ||
|
|
eb93e890d6 | ||
|
|
86ecde31ea | ||
|
|
476311544f | ||
|
|
fb0caac84e | ||
|
|
ee29c41363 | ||
|
|
302a1c699d | ||
|
|
7a979bb081 | ||
|
|
f34e3d312e | ||
|
|
f74ab3a94b | ||
|
|
2768234739 | ||
|
|
bf8201059f | ||
|
|
7105cfc239 | ||
|
|
e093614169 | ||
|
|
a9a1625241 | ||
|
|
9f2a21fa1f | ||
|
|
f86f5aea28 | ||
|
|
08289db744 | ||
|
|
936c794597 |
No files matched your search
@@ -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
|
||||
@@ -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. -->
|
||||
@@ -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()
|
||||
@@ -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())
|
||||
@@ -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())
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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" ]
|
||||
@@ -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 }}
|
||||
@@ -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 }}
|
||||
@@ -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 }}
|
||||
@@ -0,0 +1,5 @@
|
||||
vendor/
|
||||
composer.lock
|
||||
.phpunit.result.cache
|
||||
.env
|
||||
__pycache__/
|
||||
@@ -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.
|
||||
@@ -4,31 +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
|
||||
the section is the text of the release in Gitea.
|
||||
|
||||
## v0.6.0 - 2026-12-04
|
||||
|
||||
- Per account: the face of the manager (the whole one or the simple one) is stored on the account and wins over what its rights give; an administrator sets it
|
||||
on the accounts screen, an account with `manager.switch` (or `manager.full`) sets it itself. The language (Dutch or English) is a choice in the profile
|
||||
and applies on the server too, inside the manager only. New migration: `locale` and `tutorial` on the user settings.
|
||||
- The tour: an administrator switches it on for an account (accounts screen); the account gets it at its next load, and finishing or skipping it is stored
|
||||
(`PUT /manager/profile/tutorial`), so it does not come back until it is switched on again.
|
||||
- The simple face, made usable: posts, pages, media and the lists of `manager.resources` are marked `simple` by default (so with `simple_view` on, a simple
|
||||
account has something to work with), menu items and lists take a `hint` (a line of explanation), a field takes `advanced` (left out of the simple face)
|
||||
and `help` (shown under the field). The simple face has a start page of big buttons with a line of explanation, and bigger type and calmer spacing everywhere.
|
||||
- The tour: a playful walk through the manager with a mascot (a card beside what it points at, steps for exactly what this account sees, Back/Next, dots).
|
||||
It can be stopped at any moment (the cross, Escape or the link) and that is remembered per account, whether it was finished or not; it comes back only when
|
||||
an administrator switches it on again, and an account that has had it can start it again ("Show the tour", in the menu and the profile). The pictures are
|
||||
`resources/mascot/<name>.webp|png` (or a folder of the site: `manager.mascot.path`); a picture that is missing is a paw. A module adds steps with `tutorial()`.
|
||||
|
||||
## 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
|
||||
|
||||
- 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`),
|
||||
|
||||
@@ -261,7 +261,7 @@ Nobody opens a pull request to `develop`, and `production` and the release branc
|
||||
| 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. |
|
||||
| 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 | *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`:
|
||||
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
|
||||
`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.
|
||||
|
||||
@@ -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 |
|
||||
@@ -165,8 +165,7 @@ return [
|
||||
| Lists the site manages without code of its own: a form, a list, permissions (`<key>.view`, `<key>.manage`)
|
||||
| and a menu item for each. `model` keeps the records in a model of the site (the field keys are its
|
||||
| attributes); without it they go into the package's own table. Fields: see `pages`.
|
||||
| A `hint` is the line under the item on the simple start page.
|
||||
| 'services' => ['label' => 'Services', 'hint' => 'What you offer', 'singular' => 'Service', 'model' => App\Models\Service::class,
|
||||
| 'services' => ['label' => 'Services', 'singular' => 'Service', 'model' => App\Models\Service::class,
|
||||
| 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => ['name' => ['type' => 'text', 'required' => true], ...]]
|
||||
*/
|
||||
'resources' => [],
|
||||
@@ -222,12 +221,6 @@ return [
|
||||
*/
|
||||
'simple_view' => (bool) env('MANAGER_SIMPLE_VIEW', false),
|
||||
|
||||
/*
|
||||
| The pictures of the tour: a folder with `welcome`, `point`, `calm`, `write`, `photos`, `pages`, `undo`, `oops`, `party`, `profile` and
|
||||
| `peek` (`.webp` or `.png`). Null: the set of the package. A picture that is missing is replaced by a paw.
|
||||
*/
|
||||
'mascot' => ['path' => null],
|
||||
|
||||
/*
|
||||
| Prefix for the tables of the package.
|
||||
*/
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** The language an account chose, and where it stands with the tour (null, `pending`, `done` or `skipped`). */
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table(Names::table('user_settings'), function (Blueprint $table) {
|
||||
$table->string('locale', 5)->nullable()->after('view');
|
||||
$table->string('tutorial', 10)->nullable()->after('locale');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table(Names::table('user_settings'), function (Blueprint $table) {
|
||||
$table->dropColumn(['locale', 'tutorial']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 45 KiB |
@@ -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>
|
||||
@@ -1,3 +1,3 @@
|
||||
/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */
|
||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000}}}@layer theme{:root,:host{--font-sans:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-500:oklch(63.7% .237 25.331);--color-emerald-500:oklch(69.6% .17 162.48);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--leading-snug:1.375;--leading-relaxed:1.625;--radius-sm:.25rem;--radius-lg:.5rem;--radius-xl:.75rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fieldLine truncated
|
||||
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000}}}@layer theme{:root,:host{--font-sans:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-500:oklch(63.7% .237 25.331);--color-emerald-500:oklch(69.6% .17 162.48);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--radius-sm:.25rem;--radius-lg:.5rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-fiLine truncated
|
||||
/*$vite$:1*/
|
||||
@@ -1,7 +1,7 @@
|
||||
var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};function n(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var r={},i=[],a=()=>{},o=()=>!1,s=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),c=e=>e.startsWith(`onUpdate:`),l=Object.assign,u=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},d=Object.prototype.hasOwnProperty,f=(e,t)=>d.call(e,t),p=Array.isArray,m=e=>C(e)===`[object Map]`,h=e=>C(e)===`[object Set]`,g=e=>C(e)===`[object Date]`,_=e=>C(e)===`[object RegExp]`,v=e=>typeof e==`function`,y=e=>typeof e==`string`,b=e=>typeof e==`symbol`,x=e=>typeof e==`object`&&!!e,S=e=>(x(e)||v(e))&&v(e.then)&&v(e.catch),ee=Object.prototype.toString,C=e=>ee.call(e),te=e=>C(e).slice(8,-1),w=e=>C(e)===`[object Object]`,T=e=>y(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=n(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=1e4,ie=e=>{let t=Object.create(null),n=0;return(r=>{let i=t[r];return i===void 0?(++n>re&&(t=Object.create(null),n=1),t[r]=e(r)):i})},ae=/-\w/g,E=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),oe=/\B([A-Z])/g,se=ie(e=>e.replace(oe,`-$1`).toLowerCase()),ce=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),le=ie(e=>e?`on${ce(e)}`:``),D=(e,t)=>!Object.is(e,t),ue=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},de=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},fe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},pe=e=>{let t=y(e)?Number(e):NaN;return isNaN(t)?e:t},me,he=()=>me||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ge=n(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function _e(e){if(p(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=y(r)?xe(r):_e(r);if(i)for(let e in i)t[e]=i[e]}return t}if(y(e)||x(e))return e}var ve=/;(?![^(]*\))/g,ye=/:([^]+)/,be=/"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;function xe(e){let t={};return e.replace(be,e=>e.startsWith(`/*`)?``:e).split(ve).forEach(e=>{if(e){let n=e.split(ye);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function O(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;n<e.length;n++){let r=O(e[n]);r&&(t+=r+` `)}else if(x(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}function Se(e){if(!e)return null;let{class:t,style:n}=e;return t&&!y(t)&&(e.class=O(t)),n&&(e.style=_e(n)),e}var Ce=`itemscope,allowfullscreen,disablepictureinpicture,disableremoteplayback,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`,we=n(Ce);Ce+``;function Te(e){return!!e||e===``}function Ee(e,t,n){if(e.length!==t.length)return!1;let r=!0;for(let i=0;r&&i<e.length;i++)r=Ae(e[i],t[i],n);return r}function De(e,t,n){if(e.size!==t.size)return!1;let r=Array.from(t),i=new Uint8Array(r.length);for(let t of e){let e=-1;for(let a=0;a<r.length;a++)if(!i[a]&&Ae(t,r[a],n)){e=a;break}if(e<0)return!1;i[e]=1}return!0}function Oe(e,t,n){let r=m(e),i=m(t);if(r||i||(r=h(e),i=h(t),r||i))return r&&i?De(e,t,n):!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e){let i=f(e,r),a=f(t,r);if(i&&!a||!i&&a||!Ae(e[r],t[r],n))return!1}return Me(e)===Me(t)}function ke(e,t,n,r){n||=[new Map,new Map];let[i,a]=n;if(i.has(e)||a.has(t))return i.get(e)===t&&a.get(t)===e;i.set(e,t),a.set(t,e);let o=r(e,t,n);return i.delete(e),a.delete(t),o}function Ae(e,t,n){if(e===t)return!0;let r=g(e),i=g(t);return r||i?r&&i?e.getTime()===t.getTime():!1:(r=b(e),i=b(t),r||i?e===t:(r=p(e),i=p(t),r||i?r&&i?ke(e,t,n,Ee):!1:(r=x(e),i=x(t),r||i?!r||!i?!1:ke(e,t,n,Oe):String(e)===String(t))))}function je(e,t){return e.findIndex(e=>Ae(e,t))}function Me(e){return Object.getPrototypeOf(e)===null&&e[Symbol.toPrimitive]==null&&typeof e.toString!=`function`&&typeof e.valueOf!=`function`?C(e):String(e)}var Ne=e=>!!(e&&e.__v_isRef===!0),k=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===ee||!v(e.toString))?Ne(e)?k(e.value):JSON.stringify(e,Pe,2):String(e),Pe=(e,t)=>Ne(t)?Pe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Fe(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Fe(e))}:b(t)?Fe(t):x(t)&&!p(t)&&!w(t)?String(t):t,Fe=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Ie(e){return e==null?`initial`:typeof e==`string`?e===``?` `:e:String(e)}var Le,Re=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&Le&&(Le.active?(this.parent=Le,this.index=(Le.scopes||(Le.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return thLine truncated
|
||||
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
|
||||
`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ne(a)||a[0]===`.`||t&&!ne(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Rs(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ms(()=>{x&&Rs(x,n,t),l&&g.enter(e),h&&wr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u,d)=>{u||=!!t.dynamicChildren;let p=t.children,m=p.length,h=t.type===B,g=!1;for(let t=0;t<m;t++){let _=u?p[t]:p[t]=Ps(p[t]),v=_.type===_s;h&&e&&wi(e)&&e.data===`]`&&(d=e),e&&e!==d?(v&&!u&&t+1<m&&Ps(p[t+1]).type===_s&&(l(i(e.data.slice(_.children.length)),r,a(e)),e.data=_.children),e=f(e,_,o,s,c,u)):v&&!_.children?l(_.el=i(``),r,d):(g||(g=!0,Ai(r,1)||bi()),n(null,_,r,d,o,s,Ci(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,Ci(d),s),r&&r.vnode.el===e&&(r.vnode.el=t.el,wo(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=he().requestIdleCallback||(e=>setTimeout(e,1)),Ii=he().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var zi=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e),i=e=>{if(Ri(e))return t(),r.disconnect(),!1;if(getComputedStyle(e).display===`contents`){for(let t=0;t<e.children.length;t++)if(i(e.children[t])===!1)return!1}r.observe(e)};return n(e=>{if(e instanceof Element)return i(e)}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return L({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Us;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Yn(t,e,13,!r,!0)};if(s&&e.suspense||Xs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?K(r,{error:e}):null));let a=N(!1),c=N(),d=N(!!i),f,m;return Ve(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted|
Line truncated
|
||||
`))),e[cu]=au(i);let a=r||i.props&&i.props.type===`number`;xl(e,t?`change`:`input`,t=>{t.target.composing||e[cu](uu(e.value,n,a))}),(n||a)&&xl(e,`change`,()=>{e.value=uu(e.value,n,a)}),t||(xl(e,`compositionstart`,ou),xl(e,`compositionend`,su),xl(e,`change`,su))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[lu];delete e[lu],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[cu](uu(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[cu]=au(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?fe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},du={deep:!0,created(e,t,n){e[cu]=au(n),xl(e,`change`,()=>{let t=e._modelValue,n=_u(e),r=e.checked,i=e[cu];if(p(t)){let e=je(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(vu(e,r))})},mounted:fu,beforeUpdate(e,t,n){e[cu]=au(n),fu(e,t,n)}};function fu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=je(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=Ae(t,vu(e,!0))}e.checked!==i&&(e.checked=i)}var pu={created(e,{value:t},n){e.checked=Ae(t,n.props.value),e[cu]=au(n),xl(e,`change`,()=>{e[cu](_u(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[cu]=au(r),t!==n&&(e.checked=Ae(t,r.props.value))}},mu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,xl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?fe(_u(e)):_u(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[cu](i)}finally{ir(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[cu]=au(r)},mounted(e,{value:t,modifiers:{number:n}}){gu(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[cu]=au(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&hu(t,r[1],r[0])||gu(e,t,n)}};function hu(e,t,n){if(!n||p(e))return Ae(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function gu(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;a<o;a++){let o=e.options[a],s=_u(o);if(r){if(i){let e=typeof s;o.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(s)):je(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(fe(s))}else if(Ae(_u(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function _u(e){return`_value`in e?e._value:e.value}function vu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var yu={created(e,t,n){xu(e,t,n,null,`created`)},mounted(e,t,n){xu(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){xu(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){xu(e,t,n,r,`updated`)}};function bu(e,t){switch(e){case`SELECT`:return mu;case`TEXTAREA`:return Y;default:switch(t){case`checkbox`:return du;case`radio`:return pu;default:return Y}}}function xu(e,t,n,r,i){let a=bu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function Su(){Y.getSSRProps=({value:e})=>({value:e}),pu.getSSRProps=({value:e},t)=>{if(t.props&&Ae(t.props.value,e))return{checked:!0}},du.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&je(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},yu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=bu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var Cu=[`ctrl`,`shift`,`alt`,`meta`],wu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>Cu.some(n=>e[`${n}Key`]&&!t.includes(n))},Tu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=wu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Eu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`),i=n[r];if(i)return i;let a=t.some(e=>e===`left`||e===`right`);return n[r]=(n=>{if(!(`key`in n))return a?e(n):void 0;let r=se(n.key);if(t.some(e=>e===r||Eu[e]===r))return e(n)})},Ou=l({patchProp:Nl},kc),ku,Au=!1;function ju(){return ku||=Uo(Ou)}function Mu(){return ku=Au?ku:Wo(Ou),Au=!0,ku}var Nu=((...e)=>{ju().render(...e)}),Pu=((...e)=>{Mu().hydrate(...e)}),Fu=((...e)=>{let t=ju().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Ru(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType===
Line truncated
|
||||
`))),e[cu]=au(i);let a=r||i.props&&i.props.type===`number`;xl(e,t?`change`:`input`,t=>{t.target.composing||e[cu](uu(e.value,n,a))}),(n||a)&&xl(e,`change`,()=>{e.value=uu(e.value,n,a)}),t||(xl(e,`compositionstart`,ou),xl(e,`compositionend`,su),xl(e,`change`,su))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[lu];delete e[lu],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[cu](uu(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[cu]=au(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?fe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},du={deep:!0,created(e,t,n){e[cu]=au(n),xl(e,`change`,()=>{let t=e._modelValue,n=_u(e),r=e.checked,i=e[cu];if(p(t)){let e=je(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(vu(e,r))})},mounted:fu,beforeUpdate(e,t,n){e[cu]=au(n),fu(e,t,n)}};function fu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=je(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=Ae(t,vu(e,!0))}e.checked!==i&&(e.checked=i)}var pu={created(e,{value:t},n){e.checked=Ae(t,n.props.value),e[cu]=au(n),xl(e,`change`,()=>{e[cu](_u(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[cu]=au(r),t!==n&&(e.checked=Ae(t,r.props.value))}},mu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,xl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?fe(_u(e)):_u(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[cu](i)}finally{ir(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[cu]=au(r)},mounted(e,{value:t,modifiers:{number:n}}){gu(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[cu]=au(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&hu(t,r[1],r[0])||gu(e,t,n)}};function hu(e,t,n){if(!n||p(e))return Ae(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function gu(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;a<o;a++){let o=e.options[a],s=_u(o);if(r){if(i){let e=typeof s;o.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(s)):je(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(fe(s))}else if(Ae(_u(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function _u(e){return`_value`in e?e._value:e.value}function vu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var yu={created(e,t,n){xu(e,t,n,null,`created`)},mounted(e,t,n){xu(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){xu(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){xu(e,t,n,r,`updated`)}};function bu(e,t){switch(e){case`SELECT`:return mu;case`TEXTAREA`:return Y;default:switch(t){case`checkbox`:return du;case`radio`:return pu;default:return Y}}}function xu(e,t,n,r,i){let a=bu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function Su(){Y.getSSRProps=({value:e})=>({value:e}),pu.getSSRProps=({value:e},t)=>{if(t.props&&Ae(t.props.value,e))return{checked:!0}},du.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&je(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},yu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=bu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var Cu=[`ctrl`,`shift`,`alt`,`meta`],wu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>Cu.some(n=>e[`${n}Key`]&&!t.includes(n))},Tu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=wu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},Eu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},Du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`),i=n[r];if(i)return i;let a=t.some(e=>e===`left`||e===`right`);return n[r]=(n=>{if(!(`key`in n))return a?e(n):void 0;let r=se(n.key);if(t.some(e=>e===r||Eu[e]===r))return e(n)})},Ou=l({patchProp:Nl},kc),ku,Au=!1;function ju(){return ku||=Uo(Ou)}function Mu(){return ku=Au?ku:Wo(Ou),Au=!0,ku}var Nu=((...e)=>{ju().render(...e)}),Pu=((...e)=>{Mu().hydrate(...e)}),Fu=((...e)=>{let t=ju().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Ru(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType===
Line truncated
|
||||
`,t.selectionStart-1)+1,o=t.selectionEnd,s=n.modelValue.slice(a,o).split(`
|
||||
`).map(t=>e+t).join(`
|
||||
`);r(`update:modelValue`,n.modelValue.slice(0,a)+s+n.modelValue.slice(o)),requestAnimationFrame(()=>t.focus())}function f(e,t){c.value=!1;let a=(t?.alt||t?.name||``).replace(/[[\]]/g,``),o=i.value,s=o.selectionStart,l=``;r(`update:modelValue`,n.modelValue.slice(0,s)+l+n.modelValue.slice(o.selectionEnd)),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+l.length,s+l.length)})}async function p(e){if(a.value=e,e===`preview`){s.value=!0;try{o.value=(await Z.post(`${X.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(H(),U(`div`,null,[G(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":P(Q)(`Formatting`)},[G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:P(Q)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,P(Q)(`bold`))},`B`,8,Wd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:P(Q)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,P(Q)(`italic`))},`I`,8,Gd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,Kd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,qd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,Jd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,P(Q)(`text`))},`🔗`,8,Yd),P(l)?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,onClick:n[6]||=e=>c.value=!0},k(P(Q)(`Photo`)),9,Xd)):J(``,!0),G(`span`,Zd,[G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},k(P(Q)(`Write`)),3),G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},k(P(Q)(`Preview`)),3)])],8,Ud),I(G(`textarea`,{id:e.id,ref_key:`area`,ref:i,value:e.modelValue,rows:e.rows??14,required:e.required,maxlength:e.maxlength,class:`m-input font-mono`,onInput:n[9]||=e=>r(`update:modelValue`,e.target.value)},null,40,Qd),[[$c,a.value===`write`]]),a.value===`preview`?(H(),U(`div`,$d,[s.value?(H(),U(`p`,ef,k(P(Q)(`Loading…`)),1)):(H(),U(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,tf))])):J(``,!0),c.value?(H(),W(Hd,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):J(``,!0)]))}}),rf={class:`m-card mt-6 max-w-3xl p-5`},af={class:`font-display text-lg font-bold`},of={key:0,class:`mt-2 text-sm text-muted`},sf={key:1,class:`mt-2 text-sm text-muted`},cf={key:2,class:`mt-3 divide-y divide-line`},lf={class:`flex flex-wrap items-center justify-between gap-2`},uf=[`aria-expanded`,`onClick`],df={class:`font-semibold`},ff={key:0,class:`text-muted`},pf={key:1,class:`m-badge ml-2`},mf={class:`block text-xs text-muted`},hf=[`onClick`],gf={key:0,class:`mt-2 space-y-2 text-sm`},_f={class:`text-xs font-semibold uppercase tracking-wide text-muted`},vf={class:`whitespace-pre-wrap break-words`},yf=L({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=N([]),r=N(!1),i=N(null),a=N(!0),o=`${X.base}/revisions/${t.type}/${t.id}`;ia(async()=>{try{let e=await Z.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(Q(`Put this version back? The text now is kept in the history.`))&&(await Z.post(`${o}/${e.id}/restore`),B1(Q(`The earlier version is back.`)),await W1())}let c=e=>new Date(e).toLocaleString(X.locale||void 0);return(e,t)=>(H(),U(`section`,rf,[G(`h2`,af,k(P(Q)(`History`)),1),a.value?(H(),U(`p`,of,k(P(Q)(`Loading…`)),1)):n.value.length?(H(),U(`ul`,cf,[(H(!0),U(B,null,R(n.value,e=>(H(),U(`li`,{key:e.id,class:`py-3`},[G(`div`,lf,[G(`button`,{type:`button`,class:`text-left text-sm`,"aria-expanded":i.value===e.id,onClick:t=>i.value=i.value===e.id?null:e.id},[G(`span`,df,k(c(e.created_at)),1),e.user?(H(),U(`span`,ff,` · `+k(e.user),1)):J(``,!0),e.current?(H(),U(`span`,pf,k(P(Q)(`Now`)),1)):J(``,!0),G(`span`,mf,k(e.changed.join(`, `)),1)],8,uf),r.value&&!e.current?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},k(P(Q)(`Put back`)),9,hf)):J(``,!0)]),i.value===e.id?(H(),U(`dl`,gf,[(H(!0),U(B,null,R(e.values,(e,t)=>(H(),U(`div`,{key:t},[G(`dt`,_f,k(t),1),G(`dd`,vf,k(e),1)]))),128))])):J(``,!0)]))),128))])):(H(),U(`p`,sf,k(P(Q)(`Nothing here yet.`)),1))]))}}),bf={class:`mb-6 flex items-center justify-between gap-3`},xf={class:`font-display text-2xl font-bold`},Sf={for:`title`,class:`m-label`},Cf={key:0,class:`m-error`},wf={class:`grid gap-5 sm:grid-cols-2`},Tf={for:`slug`,class:`m-label`},Ef={key:0,class:`m-error`},Df={for:`category`,class:`m-label
Line truncated
|
||||
`);r(`update:modelValue`,n.modelValue.slice(0,a)+s+n.modelValue.slice(o)),requestAnimationFrame(()=>t.focus())}function f(e,t){c.value=!1;let a=(t?.alt||t?.name||``).replace(/[[\]]/g,``),o=i.value,s=o.selectionStart,l=``;r(`update:modelValue`,n.modelValue.slice(0,s)+l+n.modelValue.slice(o.selectionEnd)),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+l.length,s+l.length)})}async function p(e){if(a.value=e,e===`preview`){s.value=!0;try{o.value=(await qu.post(`${X.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(H(),U(`div`,null,[G(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":P(Z)(`Formatting`)},[G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:P(Z)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,P(Z)(`bold`))},`B`,8,Ld),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:P(Z)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,P(Z)(`italic`))},`I`,8,Rd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,zd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,Bd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,Vd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Z)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,P(Z)(`text`))},`🔗`,8,Hd),P(l)?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,onClick:n[6]||=e=>c.value=!0},k(P(Z)(`Photo`)),9,Ud)):J(``,!0),G(`span`,Wd,[G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},k(P(Z)(`Write`)),3),G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},k(P(Z)(`Preview`)),3)])],8,Id),I(G(`textarea`,{id:e.id,ref_key:`area`,ref:i,value:e.modelValue,rows:e.rows??14,required:e.required,maxlength:e.maxlength,class:`m-input font-mono`,onInput:n[9]||=e=>r(`update:modelValue`,e.target.value)},null,40,Gd),[[$c,a.value===`write`]]),a.value===`preview`?(H(),U(`div`,Kd,[s.value?(H(),U(`p`,qd,k(P(Z)(`Loading…`)),1)):(H(),U(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,Jd))])):J(``,!0),c.value?(H(),W(Fd,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):J(``,!0)]))}}),Xd={class:`m-card mt-6 max-w-3xl p-5`},Zd={class:`font-display text-lg font-bold`},Qd={key:0,class:`mt-2 text-sm text-muted`},$d={key:1,class:`mt-2 text-sm text-muted`},ef={key:2,class:`mt-3 divide-y divide-line`},tf={class:`flex flex-wrap items-center justify-between gap-2`},nf=[`aria-expanded`,`onClick`],rf={class:`font-semibold`},af={key:0,class:`text-muted`},of={key:1,class:`m-badge ml-2`},sf={class:`block text-xs text-muted`},cf=[`onClick`],lf={key:0,class:`mt-2 space-y-2 text-sm`},uf={class:`text-xs font-semibold uppercase tracking-wide text-muted`},df={class:`whitespace-pre-wrap break-words`},ff=L({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=N([]),r=N(!1),i=N(null),a=N(!0),o=`${X.base}/revisions/${t.type}/${t.id}`;ia(async()=>{try{let e=await qu.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(Z(`Put this version back? The text now is kept in the history.`))&&(await qu.post(`${o}/${e.id}/restore`),$(Z(`The earlier version is back.`)),await x1())}let c=e=>new Date(e).toLocaleString(X.locale||void 0);return(e,t)=>(H(),U(`section`,Xd,[G(`h2`,Zd,k(P(Z)(`History`)),1),a.value?(H(),U(`p`,Qd,k(P(Z)(`Loading…`)),1)):n.value.length?(H(),U(`ul`,ef,[(H(!0),U(B,null,R(n.value,e=>(H(),U(`li`,{key:e.id,class:`py-3`},[G(`div`,tf,[G(`button`,{type:`button`,class:`text-left text-sm`,"aria-expanded":i.value===e.id,onClick:t=>i.value=i.value===e.id?null:e.id},[G(`span`,rf,k(c(e.created_at)),1),e.user?(H(),U(`span`,af,` · `+k(e.user),1)):J(``,!0),e.current?(H(),U(`span`,of,k(P(Z)(`Now`)),1)):J(``,!0),G(`span`,sf,k(e.changed.join(`, `)),1)],8,nf),r.value&&!e.current?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},k(P(Z)(`Put back`)),9,cf)):J(``,!0)]),i.value===e.id?(H(),U(`dl`,lf,[(H(!0),U(B,null,R(e.values,(e,t)=>(H(),U(`div`,{key:t},[G(`dt`,uf,k(t),1),G(`dd`,df,k(e),1)]))),128))])):J(``,!0)]))),128))])):(H(),U(`p`,$d,k(P(Z)(`Nothing here yet.`)),1))]))}}),pf={class:`mb-6 flex items-center justify-between gap-3`},mf={class:`font-display text-2xl font-bold`},hf={for:`title`,class:`m-label`},gf={key:0,class:`m-error`},_f={class:`grid gap-5 sm:grid-cols-2`},vf={for:`slug`,class:`m-label`},yf={key:0,class:`m-error`},bf={for:`category`,class:`m-lab
Line truncated
|
||||
@@ -112,9 +112,5 @@
|
||||
"Put an earlier version of a post or page back": "Een eerdere versie van een bericht of pagina terugzetten",
|
||||
"Put an earlier version back": "Een eerdere versie teruggezet",
|
||||
"Opened the history of a text": "De geschiedenis van een tekst geopend",
|
||||
"Prove you are not a program, then log in again.": "Laat zien dat je geen programma bent en log dan opnieuw in.",
|
||||
"Finished or skipped the tour": "Rondleiding afgerond of overgeslagen",
|
||||
"Write and put news on your website": "Schrijf nieuws en zet het op je website",
|
||||
"Change the texts and photos of your pages": "Pas de teksten en foto's van je pagina's aan",
|
||||
"Your photos and files": "Je foto's en bestanden"
|
||||
"Prove you are not a program, then log in again.": "Laat zien dat je geen programma bent en log dan opnieuw in."
|
||||
}
|
||||
|
Before Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 79 KiB |
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 92 KiB |
|
Before Width: | Height: | Size: 79 KiB |
@@ -3,10 +3,8 @@
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\Http\Controllers\AssetController;
|
||||
use IriksIT\Manager\Http\Controllers\LoginController;
|
||||
use IriksIT\Manager\Http\Controllers\MascotController;
|
||||
|
||||
// Outside `auth`: the login of the manager (the page itself is the shell, the answer is JSON) and its built files.
|
||||
Route::get('/_assets/{file}', AssetController::class)->name('assets')->where('file', '[a-z.]+');
|
||||
Route::get('/_assets/mascot/{name}', MascotController::class)->name('mascot')->where('name', '[a-z]+');
|
||||
Route::get('/login', fn () => abort(404))->name('login'); // the shell answers browsers before this runs
|
||||
Route::post('/login', [LoginController::class, 'store'])->name('login.store')->middleware('throttle:manager-login');
|
||||
@@ -10,7 +10,6 @@ Route::get('/', DashboardController::class)->name('dashboard');
|
||||
Route::get('/profile', [ProfileController::class, 'show'])->name('profile.show');
|
||||
Route::put('/profile', [ProfileController::class, 'update'])->name('profile.update');
|
||||
Route::put('/profile/view', [ProfileController::class, 'view'])->name('profile.view');
|
||||
Route::put('/profile/tutorial', [ProfileController::class, 'tutorial'])->name('profile.tutorial');
|
||||
Route::post('/markdown', MarkdownController::class)->name('markdown.preview')->middleware('throttle:120,1');
|
||||
Route::post('/logout', [LoginController::class, 'destroy'])->name('logout');
|
||||
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Response;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
|
||||
/**
|
||||
* The pictures of the tour. A picture is `<name>.webp` or `<name>.png` in `manager.mascot.path` (default: resources/mascot of
|
||||
* the package); a site can give its own set by pointing the path at a folder of its own. A picture that is not there is
|
||||
* answered with a small paw, so the tour works before the pictures do.
|
||||
*/
|
||||
class MascotController
|
||||
{
|
||||
/** What the tour asks for. */
|
||||
public const NAMES = ['welcome', 'point', 'calm', 'write', 'photos', 'pages', 'undo', 'oops', 'party', 'profile', 'peek'];
|
||||
|
||||
private const TYPES = ['webp' => 'image/webp', 'png' => 'image/png'];
|
||||
|
||||
public function __invoke(string $name): BinaryFileResponse|Response
|
||||
{
|
||||
abort_unless(in_array($name, self::NAMES, true), 404);
|
||||
|
||||
$folder = rtrim((string) (config('manager.mascot.path') ?: __DIR__.'/../../../resources/mascot'), '/');
|
||||
|
||||
foreach (self::TYPES as $extension => $type) {
|
||||
if (is_file($path = "$folder/$name.$extension")) {
|
||||
return response()->file($path, ['Content-Type' => $type, 'Cache-Control' => 'public, max-age=86400', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
}
|
||||
|
||||
return response(self::paw(), 200, ['Content-Type' => 'image/svg+xml', 'Cache-Control' => 'public, max-age=300', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
/** A paw: the stand-in for every picture that is not there yet. */
|
||||
private static function paw(): string
|
||||
{
|
||||
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><g fill="#f43f7a">'
|
||||
.'<ellipse cx="64" cy="84" rx="26" ry="22"/><ellipse cx="26" cy="58" rx="11" ry="15" transform="rotate(-20 26 58)"/>'
|
||||
.'<ellipse cx="50" cy="38" rx="11" ry="15" transform="rotate(-8 50 38)"/><ellipse cx="78" cy="38" rx="11" ry="15" transform="rotate(8 78 38)"/>'
|
||||
.'<ellipse cx="102" cy="58" rx="11" ry="15" transform="rotate(20 102 58)"/></g></svg>';
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,6 @@ class ProfileController
|
||||
'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(),
|
||||
'groups' => method_exists($user, 'managerGroups') ? $user->managerGroups()->pluck('name')->values() : [],
|
||||
'theme' => $themes->keyFor($user),
|
||||
'locale' => UserSetting::value($user, 'locale') ?? app()->getLocale(),
|
||||
'locales' => UserSetting::LOCALES,
|
||||
'tutorial' => UserSetting::value($user, 'tutorial'),
|
||||
'themes' => config('manager.user_themes')
|
||||
? collect($themes->all())->map(fn (array $theme, string $key) => ['key' => $key, 'label' => __($theme['label']), 'colors' => $theme['colors']])->values()
|
||||
: [],
|
||||
@@ -39,20 +36,11 @@ class ProfileController
|
||||
abort_unless($menu->maySwitch($request->user()), 403);
|
||||
|
||||
$data = $request->validate(['view' => ['required', Rule::in([Menu::FULL, Menu::SIMPLE])]]);
|
||||
UserSetting::put($request->user(), ['view' => $data['view']]);
|
||||
UserSetting::query()->updateOrCreate(['user_id' => $request->user()->getKey()], ['view' => $data['view']]);
|
||||
|
||||
return response()->json(['view' => $data['view']]);
|
||||
}
|
||||
|
||||
/** Where the account stands with the tour: finished, skipped, or (to look at it again) pending. Any account may, for itself. */
|
||||
public function tutorial(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate(['state' => ['required', Rule::in(UserSetting::TUTORIAL)]]);
|
||||
UserSetting::put($request->user(), ['tutorial' => $data['state']]);
|
||||
|
||||
return response()->json(['tutorial' => $data['state']]);
|
||||
}
|
||||
|
||||
public function update(Request $request, Themes $themes): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
@@ -63,7 +51,6 @@ class ProfileController
|
||||
'current_password' => ['nullable', 'string', 'max:200'],
|
||||
'password' => ['nullable', 'string', 'min:12', 'max:200', 'confirmed'],
|
||||
'theme' => ['nullable', 'string', Rule::in(array_keys($themes->all()))],
|
||||
'locale' => ['nullable', 'string', Rule::in(UserSetting::LOCALES)],
|
||||
]);
|
||||
|
||||
if (($data['password'] ?? '') !== '' && ! Hash::check((string) ($data['current_password'] ?? ''), $user->getAuthPassword())) {
|
||||
@@ -75,11 +62,7 @@ class ProfileController
|
||||
$user->save();
|
||||
|
||||
if (config('manager.user_themes') && $request->has('theme')) {
|
||||
UserSetting::put($user, ['theme' => $data['theme'] ?: null]);
|
||||
}
|
||||
|
||||
if ($request->has('locale')) {
|
||||
UserSetting::put($user, ['locale' => $data['locale'] ?: null]);
|
||||
UserSetting::query()->updateOrCreate(['user_id' => $user->getKey()], ['theme' => $data['theme'] ?: null]);
|
||||
}
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
|
||||
@@ -10,8 +10,8 @@ use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The screens are one page that asks the JSON routes for its data. A browser that opens a manager address gets that
|
||||
* page; the page itself, and anything else that asks for JSON, gets the data. Downloads (route names `*.export`), the
|
||||
* built files and the pictures of the tour are left alone.
|
||||
* page; the page itself, and anything else that asks for JSON, gets the data. Downloads (route names `*.export`) and the
|
||||
* built files are left alone.
|
||||
*/
|
||||
class ServeShell
|
||||
{
|
||||
@@ -23,7 +23,7 @@ class ServeShell
|
||||
|
||||
$name = (string) $request->route()?->getName();
|
||||
|
||||
if (in_array($name, [Names::route('assets'), Names::route('mascot')], true) || str_ends_with($name, '.export')) {
|
||||
if ($name === Names::route('assets') || str_ends_with($name, '.export')) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* The language an account chose applies to everything the manager says to it (menu, messages, the shell), inside the
|
||||
* manager's routes only: the site's own pages keep the language of the site. Nothing chosen: the language of the app.
|
||||
*/
|
||||
class SetLocale
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$chosen = UserSetting::value($request->user(), 'locale');
|
||||
|
||||
if (in_array($chosen, UserSetting::LOCALES, true)) {
|
||||
app()->setLocale($chosen);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,6 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
|
||||
$this->app['router']->aliasMiddleware('manager.auth', Http\Middleware\Authenticate::class);
|
||||
$this->app['router']->aliasMiddleware('manager.shell', Http\Middleware\ServeShell::class);
|
||||
$this->app['router']->aliasMiddleware('manager.locale', Http\Middleware\SetLocale::class);
|
||||
RateLimiter::for('manager-login', fn (Request $request) => Limit::perMinute(5)->by(strtolower((string) $request->input('email')).'|'.$request->ip()));
|
||||
|
||||
foreach ($modules->active() as $module) {
|
||||
@@ -90,7 +89,7 @@ class ManagerServiceProvider extends ServiceProvider
|
||||
->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/guest.php'));
|
||||
}
|
||||
|
||||
Route::middleware([...$modules->middleware('before'), ...config('manager.middleware'), 'manager.locale', ...($screens ? ['manager.shell'] : []), ...$modules->middleware('after')])
|
||||
Route::middleware([...$modules->middleware('before'), ...config('manager.middleware'), ...($screens ? ['manager.shell'] : []), ...$modules->middleware('after')])
|
||||
->prefix(config('manager.path'))
|
||||
->name(Names::routePrefix())
|
||||
->group(function () use ($modules) {
|
||||
|
||||
@@ -5,28 +5,10 @@ namespace IriksIT\Manager\Models;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use IriksIT\Manager\Support\Names;
|
||||
|
||||
/** What one account chose for itself in the manager: its theme, which face of the manager it looks at, its language and where it stands with the tour. */
|
||||
/** What one account chose for itself in the manager (its theme and which face of the manager it looks at). */
|
||||
class UserSetting extends Model
|
||||
{
|
||||
protected $fillable = ['user_id', 'theme', 'view', 'locale', 'tutorial'];
|
||||
|
||||
/** The languages the screens come in. */
|
||||
public const LOCALES = ['en', 'nl'];
|
||||
|
||||
/** Where an account stands with the tour: `pending` shows it at the next load; `done` and `skipped` never again until it is set to pending. */
|
||||
public const TUTORIAL = ['pending', 'done', 'skipped'];
|
||||
|
||||
/** What this account chose (a row is made when it has none yet). */
|
||||
public static function put(object $user, array $values): void
|
||||
{
|
||||
static::query()->updateOrCreate(['user_id' => $user->getKey()], $values);
|
||||
}
|
||||
|
||||
/** One value of what this account chose, or null. */
|
||||
public static function value(?object $user, string $column): ?string
|
||||
{
|
||||
return $user === null || $user->getKey() === null ? null : static::query()->where('user_id', $user->getKey())->value($column);
|
||||
}
|
||||
protected $fillable = ['user_id', 'theme', 'view'];
|
||||
|
||||
public function getTable(): string
|
||||
{
|
||||
|
||||
@@ -55,18 +55,6 @@ abstract class BaseModule implements Module
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps this module adds to the tour. Each: `title` and `text` (English, translated through `__()`), an optional `image` (one of
|
||||
* the pictures of the tour, `MascotController::NAMES`), `menu` (the short route name of a menu item to point at, like `reviews.index`)
|
||||
* and `permission` (the step is left out for an account without it). The contract `Module` does not know this: a module without it adds none.
|
||||
*
|
||||
* @return list<array{title: string, text: string, image?: string, menu?: string, permission?: string}>
|
||||
*/
|
||||
public function tutorial(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function actions(): array
|
||||
{
|
||||
return [];
|
||||
|
||||
@@ -44,7 +44,7 @@ class MediaModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Media', 'route' => Names::route('media.index'), 'permission' => 'media.view', 'simple' => true, 'hint' => 'Your photos and files'],
|
||||
['label' => 'Media', 'route' => Names::route('media.index'), 'permission' => 'media.view'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ class PagesModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit', 'simple' => true, 'hint' => 'Change the texts and photos of your pages'],
|
||||
['label' => 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ class PostsModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return [
|
||||
['label' => 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view', 'simple' => true, 'hint' => 'Write and put news on your website'],
|
||||
['label' => 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view'],
|
||||
['label' => 'Categories and tags', 'route' => Names::route('labels.index'), 'permission' => 'posts.labels'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ class ResourcesModule extends BaseModule
|
||||
public function navigation(): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view', 'simple' => true, 'hint' => $resource['hint']],
|
||||
fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view'],
|
||||
Resources::all(),
|
||||
));
|
||||
}
|
||||
|
||||
@@ -7,12 +7,9 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use IriksIT\Manager\Models\Group;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
use IriksIT\Manager\Support\AuditTrail;
|
||||
use IriksIT\Manager\Support\Menu;
|
||||
|
||||
/**
|
||||
* The accounts of the manager and the groups each is in.
|
||||
@@ -39,8 +36,6 @@ class AccountController
|
||||
'email' => $user->email,
|
||||
'is_super_admin' => $user->isManagerSuperAdmin(),
|
||||
'is_you' => $user->is($me),
|
||||
'view' => UserSetting::value($user, 'view'),
|
||||
'tutorial' => UserSetting::value($user, 'tutorial'),
|
||||
'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name])->values(),
|
||||
'can_change' => $me->managerOutranks($user),
|
||||
'can_delete' => $me->managerOutranks($user) && ! $user->is($me),
|
||||
@@ -67,7 +62,6 @@ class AccountController
|
||||
$user = new $model;
|
||||
$user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save();
|
||||
$user->managerGroups()->sync($groups);
|
||||
$this->settings($request, $user);
|
||||
|
||||
return response()->json(['id' => $user->getKey()], 201);
|
||||
}
|
||||
@@ -98,8 +92,6 @@ class AccountController
|
||||
$user->managerGroups()->sync($groups);
|
||||
}
|
||||
|
||||
$this->settings($request, $user);
|
||||
|
||||
return response()->json(['saved' => true]);
|
||||
}
|
||||
|
||||
@@ -120,27 +112,6 @@ class AccountController
|
||||
return response()->json(['deleted' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which face of the manager the account looks at (`full`, `simple`, or empty for what its rights give) and whether
|
||||
* it gets the tour at its next load. Only what the form sent is changed.
|
||||
*/
|
||||
private function settings(Request $request, $user): void
|
||||
{
|
||||
$values = [];
|
||||
|
||||
if ($request->exists('view')) {
|
||||
$values['view'] = $request->input('view') ?: null;
|
||||
}
|
||||
|
||||
if ($request->exists('tutorial')) {
|
||||
$values['tutorial'] = $request->boolean('tutorial') ? 'pending' : (UserSetting::value($user, 'tutorial') === 'pending' ? 'skipped' : UserSetting::value($user, 'tutorial'));
|
||||
}
|
||||
|
||||
if ($values !== []) {
|
||||
UserSetting::put($user, $values);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return class-string<Authenticatable&Model> */
|
||||
private function model(): string
|
||||
{
|
||||
@@ -160,8 +131,6 @@ class AccountController
|
||||
'email' => ['required', 'string', 'email', 'max:255'],
|
||||
'groups' => ['array'],
|
||||
'groups.*' => ['integer'],
|
||||
'view' => ['nullable', Rule::in([Menu::FULL, Menu::SIMPLE])],
|
||||
'tutorial' => ['nullable', 'boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,7 @@ use Illuminate\Validation\Rule;
|
||||
* Types: `text` (one line), `textarea` (paragraphs), `markdown` (a long text in Markdown), `lines` (one item
|
||||
* per line), `media` (a picture from the media library; the value is its address), `url`, `number`, `date`,
|
||||
* `toggle` (a switch) and `select` (needs `options`: a list of values, or value => label). `required`, `default` and
|
||||
* `rules` (extra Laravel rules) are optional on every type. `help` is a line of explanation under the field; `advanced`
|
||||
* hides the field in the simple face of the manager (it keeps its value).
|
||||
* `rules` (extra Laravel rules) are optional on every type.
|
||||
*/
|
||||
final class Fields
|
||||
{
|
||||
@@ -27,7 +26,7 @@ final class Fields
|
||||
* The definitions in one shape, with a key, a label and a known type; what is wrong is dropped.
|
||||
*
|
||||
* @param array<array-key, mixed> $fields key => definition
|
||||
* @return array<string, array{key: string, label: string, type: string, help: ?string, advanced: bool, required: bool, default: mixed, options: array<string, string>, max: ?int, rules: list<mixed>}>
|
||||
* @return array<string, array{key: string, label: string, type: string, help: ?string, required: bool, default: mixed, options: array<string, string>, max: ?int, rules: list<mixed>}>
|
||||
*/
|
||||
public static function normalize(array $fields): array
|
||||
{
|
||||
@@ -56,7 +55,6 @@ final class Fields
|
||||
'label' => (string) ($field['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'type' => $type,
|
||||
'help' => isset($field['help']) ? (string) $field['help'] : null,
|
||||
'advanced' => (bool) ($field['advanced'] ?? false),
|
||||
'required' => (bool) ($field['required'] ?? false),
|
||||
'default' => $field['default'] ?? self::empty($type),
|
||||
'options' => $options,
|
||||
|
||||
@@ -8,9 +8,8 @@ use IriksIT\Manager\Models\UserSetting;
|
||||
/**
|
||||
* The menu one account sees, and the face of the manager it looks at: the full one, or (when config
|
||||
* `simple_view` is on) the simple one with only the items marked `simple`. An account with the permission
|
||||
* `manager.full` (and a super admin) gets the full face; everyone else the simple face, unless something is stored for
|
||||
* the account: an administrator sets it on the accounts screen, an account with `manager.switch` (or `manager.full`)
|
||||
* sets it itself. What is stored wins; only the account's own switch needs the permission.
|
||||
* `manager.full` (and a super admin) gets the full face; one with `manager.switch` starts in the simple
|
||||
* face and may change; everyone else always gets the simple face. What it chose is remembered per account.
|
||||
*/
|
||||
final class Menu
|
||||
{
|
||||
@@ -26,14 +25,17 @@ final class Menu
|
||||
return self::FULL;
|
||||
}
|
||||
|
||||
// What is stored wins: an administrator sets it for an account, an account that may switch sets it itself.
|
||||
$stored = UserSetting::value($user, 'view');
|
||||
$full = $this->hasFull($user);
|
||||
|
||||
if (in_array($stored, [self::FULL, self::SIMPLE], true)) {
|
||||
return $stored;
|
||||
if ($this->maySwitch($user)) {
|
||||
$chosen = $user->getKey() === null ? null : UserSetting::query()->where('user_id', $user->getKey())->value('view');
|
||||
|
||||
if (in_array($chosen, [self::FULL, self::SIMPLE], true)) {
|
||||
return $chosen;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->hasFull($user) ? self::FULL : self::SIMPLE;
|
||||
return $full ? self::FULL : self::SIMPLE;
|
||||
}
|
||||
|
||||
public function maySwitch(?object $user): bool
|
||||
@@ -67,7 +69,6 @@ final class Menu
|
||||
'label' => $item['label'],
|
||||
'href' => isset($item['route']) ? route($item['route'], $item['params'] ?? [], false) : (string) $item['url'],
|
||||
'section' => $item['section'] ?? null,
|
||||
'hint' => $item['hint'] ?? null,
|
||||
'icon' => $item['icon'] ?? null,
|
||||
'new_tab' => ($item['new_tab'] ?? false) ?: null,
|
||||
], fn ($value) => $value !== null);
|
||||
|
||||
@@ -5,7 +5,6 @@ namespace IriksIT\Manager\Support;
|
||||
use Illuminate\Support\Str;
|
||||
use IriksIT\Manager\Contracts\Module;
|
||||
use IriksIT\Manager\Exceptions\ModuleException;
|
||||
use IriksIT\Manager\Http\Controllers\MascotController;
|
||||
|
||||
/**
|
||||
* Knows which modules exist and which of them are on for this site.
|
||||
@@ -173,7 +172,6 @@ final class ModuleRegistry
|
||||
...$item,
|
||||
'label' => __($item['label']),
|
||||
...(isset($item['section']) ? ['section' => __($item['section'])] : []),
|
||||
...(isset($item['hint']) && $item['hint'] !== null ? ['hint' => __($item['hint'])] : []),
|
||||
'order' => (int) ($item['order'] ?? 100),
|
||||
'simple' => (bool) ($item['simple'] ?? false),
|
||||
], $items);
|
||||
@@ -184,34 +182,6 @@ final class ModuleRegistry
|
||||
return array_values($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* The steps the modules add to the tour, for an account with these permissions.
|
||||
*
|
||||
* @param list<string> $allowed
|
||||
* @return list<array{title: string, text: string, image: ?string, href: ?string}>
|
||||
*/
|
||||
public function tutorial(array $allowed): array
|
||||
{
|
||||
$steps = [];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
foreach (method_exists($module, 'tutorial') ? $module->tutorial() : [] as $step) {
|
||||
if (! isset($step['title'], $step['text']) || (isset($step['permission']) && ! in_array($step['permission'], $allowed, true))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$steps[] = [
|
||||
'title' => __($step['title']),
|
||||
'text' => __($step['text']),
|
||||
'image' => isset($step['image']) && in_array($step['image'], MascotController::NAMES, true) ? $step['image'] : null,
|
||||
'href' => isset($step['menu']) ? route(Names::route($step['menu']), [], false) : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Audit-log names of what is done: the modules' own plus the core's.
|
||||
*
|
||||
@@ -219,7 +189,7 @@ final class ModuleRegistry
|
||||
*/
|
||||
public function actions(): array
|
||||
{
|
||||
$actions = ['profile.update' => ['Changed own account'], 'profile.view' => ['Switched between the simple and the whole manager'], 'profile.tutorial' => ['Finished or skipped the tour']];
|
||||
$actions = ['profile.update' => ['Changed own account'], 'profile.view' => ['Switched between the simple and the whole manager']];
|
||||
|
||||
foreach ($this->active() as $module) {
|
||||
$actions = [...$actions, ...$module->actions()];
|
||||
|
||||
@@ -40,7 +40,6 @@ final class Resources
|
||||
$out[$key] = [
|
||||
'key' => $key,
|
||||
'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))),
|
||||
'hint' => isset($definition['hint']) ? (string) $definition['hint'] : null,
|
||||
'singular' => (string) ($definition['singular'] ?? $definition['label'] ?? $key),
|
||||
'model' => is_string($model) && is_subclass_of($model, Eloquent::class) ? $model : null,
|
||||
'fields' => $fields,
|
||||
|
||||
@@ -6,7 +6,6 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use IriksIT\Manager\ManagerServiceProvider;
|
||||
use IriksIT\Manager\Models\UserSetting;
|
||||
|
||||
/** What the first page of the screens needs to know: who, what they may do, the menu and the look. */
|
||||
class Shell
|
||||
@@ -53,12 +52,6 @@ class Shell
|
||||
'extensions' => $user === null ? [] : $extensions,
|
||||
'view' => $this->menu->view($user),
|
||||
'can_switch' => $this->menu->maySwitch($user),
|
||||
'simple_view' => (bool) config('manager.simple_view'),
|
||||
'tutorial' => UserSetting::value($user, 'tutorial') === 'pending',
|
||||
'tutorial_state' => UserSetting::value($user, 'tutorial'),
|
||||
'tutorial_steps' => $user === null ? [] : $this->modules->tutorial($allowed),
|
||||
'mascot' => '/'.trim((string) config('manager.path'), '/').'/_assets/mascot/',
|
||||
'locales' => UserSetting::LOCALES,
|
||||
'theme' => $key,
|
||||
'can_login' => Route::has(Names::route('login')),
|
||||
'login_fields' => $user === null ? $this->loginChecks->fields() : [],
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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** \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);
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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 "]);
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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']);
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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('');
|
||||
});
|
||||
@@ -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,');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
After Width: | Height: | Size: 70 B |
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Tests;
|
||||
|
||||
abstract class MediaOffTestCase extends TestCase
|
||||
{
|
||||
protected array $modules = ['media' => false];
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__.'/Helpers.php';
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Tests;
|
||||
|
||||
abstract class PostsOffTestCase extends TestCase
|
||||
{
|
||||
protected array $modules = ['posts' => false];
|
||||
}
|
||||
@@ -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']);
|
||||
}
|
||||
}
|
||||
@@ -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']],
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||