commit bf5c31169a5d9fa1f5e99d5189d12a42bcd05b74 Author: deploy-bot Date: Fri Dec 4 14:33:04 2026 +0000 v0.8.0 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..34d6f30 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,150 @@ +# Changelog + +Every release has a section here, named after its version (for example `v0.1.0 - 2026-12-04`, as a second-level +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.8.0 - 2026-12-04 + +- A site that had its own manager before the package keeps its own middleware aliases (`manager.auth`, `manager.shell`, `manager.locale`): the routes of the package + use the middleware classes themselves, so the alias of the site is never taken over, and the alias is only offered when the site has none. +- The settings screen has a "Try it" button per group that makes a connection (the IriksIT API: logs in; Turnstile: asks Cloudflare whether it knows the secret key). It tries what is saved, needs `settings.secrets`, and a site adds its own with `manager.settings.checks`. +- Features of the site: `manager.features` declares switches (services, projects, reviews, requests, a contact form) that show up as toggles in a group of their own on the settings screen. One switch is followed by the manager (a `resources` entry with `'feature' => 'services'` disappears completely: menu, permissions, screens, routes) and by the public site (`Features::on()`, `Features::flags()`, the route middleware `manager.feature:services`, and `@feature('services') … @endfeature` in Blade). Off hides; the data stays and comes back when the switch goes on. +- The requests module (`leads`, off by default; with a feature `leads` in `manager.features` that one switch turns it on and off): requests of visitors (callback requests, questions, quotes, a contact form) are screened into the folders inbox, other and spam (links, words of selling to a business, text in another language, a form that was open too short, a throwaway address, the same text twice, blocked senders; nothing is ever refused, every call is kept with its reasons), stored, mailed to an address of the settings screen, and handled on a screen of their own (waiting, handled, notes, outcome, call/WhatsApp/mail buttons; whoever manages also sees the folders and the reasons, moves requests and blocks senders). The forms stay the site's own and call `Support\Leads\Intake::take()`. `manager:leads-prune` removes old requests, old spam and expired blocks. New migration: `leads` and `lead_blocks`. +- The public forms of the requests module: `POST /requests/{form}` (path and forms in `manager.leads.form`) takes a callback request, a question or a quote in with the fields each form requires (`contact` is one box for a phone number or a mail address), only the questions and moments the site offers, a honeypot, the signed moment of the form, Turnstile when its keys are set and a limit per address and for everyone together. A visitor always gets the normal thank-you, whatever the screening thinks. `GET /requests/token` gives the signed moment to a form built by script. Where a visit came from comes from the statistics module by itself. +- The requests module gets a report for whoever manages it (the last 90 days: requests, ways in, pages, sources, subjects, how many became a job, how much the screening kept away), counting of taps on the phone number and the WhatsApp button (`POST /requests/tap`, a counter per day and page, nothing else; new migration `lead_taps`), and `manager:import leads|taps` for a site that had its own. +- Richer fields for pages and `manager.resources`: `slug` (an address part, made of the field named in `from` when left empty), `list` (a list of short texts, one per line), `media_list` (a gallery from the media library), `repeater` (a list of items with fields of their own, for example questions and answers), and a `select` that takes its choices from the rows of a table of the site (`source` => model, label, value). With these a site can describe services, projects and reviews without code, on its own models and tables. +- A site that already has tables for the same job (groups, pages, leads…) can keep them: point `manager.tables` at them and the migrations of the package skip a table that exists and only add a column it lacks (`groups.start`, `group_user.is_primary`, `pages.meta_description`, `pages.content`). The rows stay where they are. +- `manager:doctor` checks the columns of the tables of every active module, so a table of the site that the package adopted and that lacks a column the package writes is reported (`columns`) instead of failing at the first save. `Support\Tables::COLUMNS` lists them, and a test keeps that list equal to what the migrations make. +- The rights a site stored for its groups keep working after the package takes over: the names follow `.` and `.view`/`.manage`, and a stored `.manage` also lets the account see the list. Written down in the README ("A site with data and names of its own") and kept by a test. +- Ready-made lists for `manager.resources`: `Support\Presets::services()`, `projects()`, `testimonials()`, `menu()` and `socials()` (a service with a page, photos, points and questions; a project with a town, year and photos; a review; a menu; social links). A site points `model` at its own table or keeps the records in the package, sets a `feature`, and overrides single fields. +- A table of requests that a site already has can be adopted: a migration adds `subject` and `subject_id` to it and, when it has `service_id`, gives that id to `subject_id`. The revisions table of a site is not adopted (the package makes its own; the history of the site stays in its old table). +- `Support\Presets::business()`: the page of business details (name, owner, phone, WhatsApp, address, registration numbers, opening hours, towns) for `manager.pages.definitions`, so every site enters them once and reads them with `Page::contentFor('business')`. +- The updates module (`updates`, off by default, right `updates.view`): a screen with the releases of the CHANGELOG.md of the site, newest first, with or without a heading per kind of change. `manager.updates.changelog` points at another file and `limit` says how many releases show. No tables. +- A contact message with a subject is a request too: the form `contact` (kind `message`, `POST /requests/contact`) requires name, mail address, subject and message, and a form may now list `subject` in `require`. `Support\Presets::experience()` is the list of work and projects for a CV (title, role, period, story, points, links, technology). +- The sharing module (`sharing`, off by default, needs `posts`): connect the owner's LinkedIn account (OAuth with a session state and PKCE, tokens stored encrypted) and share a published post with the button "Share now" on its screen. Until the setting "Post for real" is on, a share is a dry run and nothing is sent. A site adds other networks with a class that implements `Contracts\Sharer`. Rights `sharing.view`, `sharing.publish` and `sharing.manage`; new migration: `social_connections` and `post_shares`. The two steps of a connection (route names `*.connect` and `*.callback`) are left alone by the screens, like downloads. +- The simple face has words of its own: a field, a resource and a defined page take `'simple' => [...]` (`label` and `help` for a field, `label` and `singular` for a resource and its menu item, `title` for a page), shown to accounts in the simple face while the full face keeps the usual words. The presets (services, projects, reviews, menu, social links, business details) bring plain-language words for it. +- Screens for the owner of a business: the module `numbers` (off by default, needs `statistics`, right `numbers.view`) shows how the site is doing in plain words: visitors against the period before, requests and what became of them, taps on the call and WhatsApp buttons, pages, how people found the site and the most read articles, over 7 days, 30 days or a year. +- The module `costs` (off by default, right `costs.view`, new migration `work_costs`) shows what the work on the site cost, from the table of its `TOKENS.md`: tokens in euros per piece of work and per release, hours at an hourly rate, hosting and a discount. A row is priced once and kept: by an invokable class of the site (`manager.costs.pricer`), else by the IriksIT API (`Support\IriksStorage\Client::tokenCosts()`, the account of `manager.media.iriksit`, permission `ai.pricing`), else by the fixed `manager.costs.rates`. `manager:costs-price` prices what is new. +- The simple start screen says what waits: a line under the button of the requests, the posts and the numbers (`Support\Tiles`), a badge with the new requests, a "Need help?" button (`manager.simple.help`) and a "View the site" button (`manager.simple.site_link`). + +## v0.7.0 - 2026-12-04 + +- Per account a primary group (and any number of secondary ones): the primary group is the label of the account and sets its start screen; what the + account may do stays the sum of all its groups. A group can name a start screen. New migration: `is_primary` on the group-user table and `start` on groups. +- The settings screen (module `settings`, whole face only): switch parts of the manager and features of the site on or off and set the keys and addresses of + integrations (the IriksIT API, Turnstile) from the manager, with the rights `settings.manage` and `settings.secrets`. Works at once (database plus one compiled + file laid over the config, also with `config:cache`), optionally written into `.env` too (`manager.settings.write_env`). Sites add their own with + `manager.settings.definitions`. New migration: `settings`. +- More commands: `manager:settings` (list, get, set, reset, refresh; secrets are typed hidden), `manager:users`, `manager:user-password`, `manager:media-prune` + (unused media, or files no row knows; nothing is deleted without `--delete`) and `manager:import media` (the rows of a site's own media table, with `--set` for a value every row gets). +- `php artisan manager:media-move `: moves the files of the media library to another disk (for example to `iriksit`), keeping their addresses, with `--dry-run`, `--from`, `--limit`, `--verify` and `--delete-source`. Safe to run again. +- The disk `iriksit`: media files at the IriksIT API (`MANAGER_MEDIA_DISK=iriksit`, `manager.media.iriksit`), with a table that remembers which + path is which id (new migration `storage_files`) and `php artisan manager:storage-check` to try it. New requirement: `league/flysystem`. + +## 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/.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`), + `IriksIT\Manager\Support\Names` to ask for either. The defaults are the names of every earlier version. +- `manager:import posts|pages|reviews` copies the rows of a table of the site into the package (read-only on the source, repeatable, + `--dry-run`, column mapping). +- Server texts are translatable: menu, permission labels and sections, theme names, audit summaries and the main messages go through `__()`, + and the package ships `resources/lang/nl.json`. A site's own `lang/.json` wins. +- Fix: the audit log and the bot counter strip the configured route-name prefix, not a fixed `manager.`. +- Menu: sections, icons and order, changeable from `manager.menu` (items and links of the site's own). The old item shape stays valid. +- Simple view (`simple_view`, off by default): permissions `manager.full` and `manager.switch`, a remembered choice per account (new migration + adds `view` to the user settings) and a switch in the menu. +- Pages with fields: definitions in `manager.pages.definitions` (types text, textarea, markdown, lines, media, url, number, date, toggle, + select), `Page::contentFor($slug)` for the public site, and screens to edit them and to make free pages (new migration: `meta_description` + and `content` on the pages table). The field definitions (`Support\Fields`) and the form component are shared with what comes next. +- Lists without code: `manager.resources` makes a menu item, list, form, validation and permissions (`.view`, `.manage`) from field + definitions, kept in a model of the site or in the new `manager_records` table (new module `resources`, on by default, nothing registered + without definitions). +- Screens of the site's own: `manager.extensions` loads JavaScript modules next to the manager; `window.IriksManager` offers `register`, `api`, + `Vue` and the shared components, and `resources/dist/vue.js` maps `import 'vue'` to the Vue of the screens. A browser that opens a manager + address without a route of the package gets the screens (an HTML request only). +- History: a new module `revisions` (on by default, `MANAGER_REVISIONS`) keeps the state of every saved post and page with who and what changed, + shows it on the screens and puts an earlier state back (`revisions.view`, `revisions.restore`; new table `manager_revisions`). More models can + join with `manager.revisions.types`. +- Editor: Markdown fields get a toolbar, photos from the media library and a server-rendered preview (`POST /manager/markdown`); the media + library gets a click-to-set focus point with a square preview. (No cropping or rotating: the file stays as uploaded.) +- Statistics: `` puts the counting script (`/pulse/pulse.js`, no cookies, honours Do Not Track) in the public pages of a site. +- Login checks: `manager.login.checks` (contract `LoginCheck`, base class `BaseLoginCheck`) adds fields and checks before and after the password; + Cloudflare Turnstile is built in (two env keys). No two-factor login in the package itself. +- Roles of the host: `manager.permissions` (`mode` groups/host/merge, `roles` map or a `resolver` implementing `PermissionResolver`) lets a site + with its own roles say what an account may do; groups stay the default. +- CI: nothing runs weekly any more, and Trivy no longer runs in the jobs (the runner disk filled up with its database). `composer audit` stays in every + pull request and every release; Trivy scans production from the homelab, every night and after every release. The nightly dependency round of the + homelab replaces the weekly *Dependency updates* workflow (and `update_dependencies.py`); its `renovate/*` pull requests may go to `production` and + become a patch release of their own (one a night at most, none while a release branch is open). +- `manager:doctor` has a `names` check: it warns when the site uses a route name or an address of the manager and says to set `route_name` or `path`. + +## v0.4.0 - 2026-12-04 + +- Screens in the package: a small Vue app on the JSON routes, built and served by the package (a site needs no Node). Login, logout and + profile for an app that has none, a dashboard and menu, and screens for accounts, groups, media (with a picker for covers), posts, + categories and tags, the audit log with bans, and statistics. Pages and reviews show a read-only list. `MANAGER_UI=none` keeps only the + JSON routes. The default middleware is now `['web', 'manager.auth']` (a published config that still says `auth` keeps working). +- Themes: `dark` and `light`, your own as a JSON file (`php artisan manager:make-theme`) or in the config, chosen per account in the + profile (new table `manager_user_settings`; `MANAGER_THEME`, `MANAGER_USER_THEMES`). Every value is checked before it reaches a page. +- For AI agents: `php artisan manager:install` (no questions), `php artisan manager:doctor --json` (checks the setup, says how to fix + it, non-zero exit on failure), a step-by-step guide (`resources/ai/INTEGRATION.md`) and a Laravel Boost guideline. Modules report + their tables with `tables()`. +- PR CI: a job that type-checks and builds the screens and fails when the committed `resources/dist` is out of date. + +## v0.3.0 - 2026-12-04 + +- The Packagist step submits the package itself when Packagist does not know it yet (the update call answered 404), instead + of failing until someone submits it by hand. + +## v0.2.0 - 2026-12-04 + +- CI: the composer cache and three tries for the install in every job, so a hiccup of a download no longer breaks a run. +- Audit log (module `audit`, off by default): logins and failed logins, changes, opened pages and refusals, with the + address and the browser. Modules name their routes with the new `actions()` and `views()`. +- Address bans: by hand, for a group of addresses, or by itself after too many failed logins; optionally for the + whole app. `manager:unban` and `manager:audit-prune`. +- Statistics (module `statistics`, off by default): page views and time on a page without cookies or stored addresses, sources, + devices, programs, comparisons and CSV export. Which pages count is up to the site. +- Breaking for a module that implements `Contract\Module` without extending `BaseModule`: the contract gained + `actions()`, `views()` and `middleware()`. +- Weekly workflow *Dependency updates*: widens the version constraints in `composer.json` for a new release of a dependency, as a pull request to the open release branch. +- `dev/token-usage-hermes.py`: the same rows per model for work done by a Hermes agent; the token script also counts the advisor. +- `CLAUDE.md` and the rules shared with the other IriksIT repos in `AGENTS.md`. + +## v0.1.0 - 2026-12-04 + +First version. + +- The module registry, with a switch per part of the manager. A part that is off has no routes, tables, menu + item or permissions. +- Users: accounts, groups and permissions (a permission can need another), and `manager:create-user`. +- Media: the library on a Laravel disk and the public file route `/media-files/{id}/{name}/view`. +- Posts: drafts, scheduling, Markdown, categories and tags. +- MIT license; the development cycle with release branches, tags and Packagist, and CI with tests, `composer audit` + and Trivy. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3dbecaf --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Iriks IT + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f3d6455 --- /dev/null +++ b/README.md @@ -0,0 +1,417 @@ +# iriks-it/laravel-manager + +A modular backend for Laravel sites. Install it, switch on the parts the site needs, done. + +```bash +composer require iriks-it/laravel-manager +php artisan vendor:publish --tag=manager-config +php artisan migrate +``` + +Put `IriksIT\Manager\Concerns\HasManagerAccess` on the `User` model. The manager lives at `/manager` +(`MANAGER_PATH`) behind the `web` and `auth` middleware (`config/manager.php`). + +## Set up with an AI agent + +```bash +php artisan manager:install --modules=users,media,posts --user-model="App\Models\User" +php artisan manager:doctor --json # non-zero exit when something is wrong; each problem has a `fix` +``` + +`resources/ai/INTEGRATION.md` is a step-by-step guide for an agent; `resources/boost/guidelines/core.blade.php` +is picked up by Laravel Boost. + +## Screens and themes + +The package brings its own screens (a small Vue app on the JSON routes, already built: your app needs no Node). They also +give an app without a login a login and a profile. `MANAGER_UI=none` turns them off, for an app that builds its own screens +on the JSON routes. A browser that opens a manager address gets the page; anything that asks for JSON gets the data. + +- **Looks.** Built in are `dark` and `light`. `MANAGER_THEME` is what everyone sees until they choose; with + `MANAGER_USER_THEMES=true` (default) each account picks its own in its profile. +- **The house style of the site.** `php artisan manager:make-theme acme --brand=#e4002b --name="Acme" --logo=/img/logo.svg --font="Inter, sans-serif"` + writes `resources/manager-themes/acme.json`; set `MANAGER_THEME=acme`. A theme is colours, a radius, fonts, a name and a logo, and every + value is checked, so a theme file can never put CSS or markup in the page. Themes can also be listed in `manager.themes`. +- **Not built yet:** a theme editor in the manager (themes are files for now), and screens for modules your own site adds (they show a notice). +- **Working on the screens:** the sources are in `ui/`; `npm ci && npm run build` there writes `resources/dist`, which is committed + (PR CI fails when it is out of date). + +## Modules + +| Key | What | Default | +|---|---|---| +| `users` | Accounts, groups and permissions | on | +| `media` | Media library | on | +| `pages` | Page texts | on | +| `posts` | Posts | on | +| `reviews` | Reviews | off | +| `audit` | Audit log and address bans | off | +| `statistics` | Visitor statistics | off | +| `resources` | Lists defined in config (`manager.resources`) | on (nothing without definitions) | +| `revisions` | History of posts and pages, with restore | on | +| `sharing` | Share a published post on LinkedIn with one button (`manager.sharing`); a site adds other networks with a `Sharer` class. Rights `sharing.view`, `sharing.publish`, `sharing.manage` | off | +| `updates` | What changed on the site: the releases of its `CHANGELOG.md` (`manager.updates`), right `updates.view` | off | + +Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANAGER_POSTS`, +`MANAGER_REVIEWS`, `MANAGER_AUDIT`, `MANAGER_STATISTICS`, `MANAGER_REVISIONS`, `MANAGER_UPDATES`, `MANAGER_SHARING`. A module that is off has **no routes, no tables, no menu item and no permissions**: +| `costs` | What the work on the site cost, from its `TOKENS.md`, priced once and kept (`manager.costs`), right `costs.view` | off | +| `numbers` | How the site is doing in plain words for an owner (needs `statistics`; uses `leads` when on), right `numbers.view` | off | +| `updates` | What changed on the site: the releases of its `CHANGELOG.md` (`manager.updates`), right `updates.view` | off | + +Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANAGER_POSTS`, +`MANAGER_REVIEWS`, `MANAGER_AUDIT`, `MANAGER_STATISTICS`, `MANAGER_REVISIONS`, `MANAGER_UPDATES`, `MANAGER_COSTS`, `MANAGER_NUMBERS`. A module that is off has **no routes, no tables, no menu item and no permissions**: +its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when +that one is off. + +## Language + +The texts the server makes (menu, permission and section labels, theme names, audit summaries and the messages of the JSON routes) go through Laravel's `__()` with the English text as the key. The package ships `resources/lang/nl.json`; the screens follow `app()->getLocale()`. A site translates more, or words things differently, with its own `lang/.json`: that file wins over the package. Audit lines are written in the language of the request that made them. + +## The menu and the simple view + +A module's menu item is `['label' =>, 'route' =>, 'permission' =>]` and may add `section` (a heading), `icon` (`home`, `file`, `image`, `users`, `group`, `chart`, `shield`, `star`, `tag`, `link`, `cog`), `order` (lower first, default 100), `simple` and `new_tab`. A site changes the menu without code in `config/manager.php`: `menu.items` by route name without the prefix (`'posts.index' => ['order' => 10, 'section' => 'Content', 'hidden' => false]`) and `menu.links` for items of its own (`['label' => 'Leads', 'url' => '/manager/leads', 'permission' => null]`). + +`simple_view` (`MANAGER_SIMPLE_VIEW=true`) adds a simple face next to the full one, for an owner who only needs a few screens. Two permissions appear in the group form: `manager.full` (everything; super admins have it) and `manager.switch` (starts simple and may switch; the choice is remembered per account and the menu has a button for it). Every other account always gets the simple face: only the items marked `simple`. It limits the menu, not the access: the routes still check their own permissions. Turning it on makes accounts without `manager.full` or `manager.switch` see only the simple items, so give the groups what they need first. + +## Your own lists and screens + +**Lists without code.** `manager.resources` turns a definition into a menu item, a list, a form, validation and the permissions `.view` and `.manage`, for things like a menu, socials, services, testimonials or leads: + +```php +'resources' => [ + 'services' => [ + 'label' => 'Services', 'singular' => 'Service', + 'model' => App\Models\Service::class, // the records live in a model of the site; leave it out to use the package's own table + 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], + 'fields' => ['name' => ['type' => 'text', 'required' => true], 'price' => ['type' => 'number'], 'photo' => ['type' => 'media']], + ], +], +``` + +**Ready-made lists.** `IriksIT\Manager\Support\Presets` has definitions for what a business site nearly always has: `services()`, `projects()`, `testimonials()`, `menu()` and `socials()`. Their field keys are the usual column names (`title`, `summary`, `is_active`, `sort_order`), so a site points `model` at its own table, or leaves it out to keep the records in the package's table. What the site passes wins, field by field: `'services' => Presets::services(['model' => Service::class, 'feature' => 'services', 'fields' => ['title' => ['label' => 'Name']]])`. `Presets::projects($override, serviceModel: Service::class)` adds the choice of a kind of work. `Presets::experience()` is work and projects for a CV (title, role, period, story, points, links, technology; `type` is `work` or `project` and the site may add kinds). `Presets::business()` is the page of business details (name, phone, address, registration numbers, opening hours, work area) for `manager.pages.definitions['business']`; read it with `Page::contentFor('business')`. + +The field keys are the attributes of the model (the definition is the whitelist: nothing else is written); without a model the values are kept as JSON in `manager_records`. Field types are the ones of the pages. Names that belong to a module (`posts`, `pages`, `media`, ...) are refused. + +**Screens of your own.** List a JavaScript module in `manager.extensions` (a path of your site, or https). The manager loads it before it shows anything and puts `window.IriksManager` in reach: `Vue`, `boot`, `api`, `t`, `flash`, `navigate`, `register` and the components `Link`, `FormFields`, `Icon` and `MediaPicker`. `register('^/leads$', Component, { data: true })` shows `Component` at `/manager/leads`, with the JSON of that same address (or of `source`) as props; an address of yours needs a route for the data, and a menu item through `manager.menu.links`. Build your bundle with `vue` left external (`build.rollupOptions.external: ['vue']`): the manager points `import 'vue'` at its own Vue, so your components share its reactivity. A browser that opens a manager address without a route of the package gets the screens (which show yours, or "no screen yet"); a request for data gets a plain 404. + +## A site with data and names of its own + +The package never maps its queries onto other columns: every screen assumes its own columns. What it does give you is room to coexist, a way to take over the tables of a site that had a manager before, and a way to move data in. + +- `route_name` (default `manager`): the prefix of the route names. A site that already has `manager.*` routes sets, for example, `'route_name' => 'cms'`; the menu and the screens follow. Use `IriksIT\Manager\Support\Names::route('posts.index')` in code of your own. +- `table_prefix` (default `manager_`) and `tables` (`['media' => 'site_files']`): the names of the tables. Set them before the first `migrate`; the package does not rename a table that exists. +- Taking over the manager of a site: point `tables` at the tables the site already has (`['groups' => 'groups', 'group_user' => 'group_user', 'pages' => 'pages']`). A migration of the package skips a table that exists and adds only a column it lacks, so rows stay where they are; `php artisan manager:doctor` lists columns that are still missing (`columns`). The names of the rights stay as they were when they follow `.` (`posts.write`, `pages.edit`, `leads.handle`) and, for a list of your own (`manager.resources`), `.view` and `.manage`: a group stored with only `services.manage` may also see the list, because the package adds what a right needs when it checks. +- `php artisan manager:import posts --table=articles --map=title=headline --map=body=content [--dry-run] [--connection=...] [--limit=...]` copies the rows of a table of the site into `posts`, `pages` or `reviews`. The source is only read, and running it again updates the rows it made (found by slug, or by author and text for reviews). `--map` is `package_column=source_column`. Put the settings in `manager.import.` (`table`, `connection`, `map`) to run it without options. Tags may be JSON or a comma separated list; a row without the required text is skipped and reported. + +## Your own module + +Implement `IriksIT\Manager\Contracts\Module` (or extend `Modules\BaseModule`), keep `routes.php` and a +`migrations/` folder next to the class, and add the class to `available` in the config. + +## Users module + +Accounts and groups. `HasManagerAccess` on the host `User` model gives it `managerGroups()`, +`managerPermissions()`, `hasManagerPermission()`, `managerOutranks()` and `managerMayGive()`. +Keep `is_super_admin` out of `$fillable`: nobody becomes a super admin through a form. + +```bash +php artisan manager:create-user # the only way to make a super admin +``` + +- A group is a name plus permissions; a permission that needs another one (`posts.publish` needs + `posts.write`) brings it along. Permissions of a module that is off are ignored. +- Whoever manages accounts only touches accounts that need nothing more than their own rights, and + only hands out groups that give nothing they lack themselves. +- `groups.manage` is a gate for super admins only, not a permission of a group. +- The package defines one gate per permission and **no `Gate::before`**: it never answers for the + abilities of your own app. +- **A site with roles of its own** (decided in 0.5.0: groups stay the default, the site's roles are added next to them). + `manager.permissions.mode` is `groups` (default), `host` (the groups are ignored) or `merge` (both). The site says what a role may do + with `roles` (`['editor' => ['posts.view', 'posts.write'], 'owner' => ['*']]`, read from the attribute `role_attribute`: a string, a + list or a relation with a `name`) or with a `resolver` class that implements `IriksIT\Manager\Contracts\PermissionResolver`. Values + that are no permission of an active module are ignored and what a permission needs is added. A super admin may always do everything. + The group screens still work in `host` mode but give nothing. +- The migration adds `is_super_admin` to your users table (the table of `manager.user_model`). It + promotes nobody. + +## Checks on the login + +The login of the screens can ask for more. Write a class that extends `IriksIT\Manager\Support\Login\BaseLoginCheck` (the contract is `IriksIT\Manager\Contracts\LoginCheck`) and list it in `manager.login.checks`: + +- `fields()`: extra inputs on the form (`['name' => 'code', 'type' => 'text', 'label' => 'Code', 'autocomplete' => 'one-time-code']`); +- `before($request)`: runs before the password is looked at: a captcha; +- `after($request, $user)`: runs when the email and password are right and before anyone is logged in: a second factor. Refuse by throwing a `ValidationException`; the attempt then counts as a failed login, so the audit log and the bans see it. + +**Cloudflare Turnstile** is built in: set `MANAGER_TURNSTILE_SITE_KEY` and `MANAGER_TURNSTILE_SECRET` and the widget appears and is checked (a token that cannot be checked refuses the login). The widget loads a script from `challenges.cloudflare.com`; a strict Content-Security-Policy has to allow it. **There is no two-factor login in the package itself**: `after()` is the place for it, the code to make and keep the secrets is the site's. These checks belong to the login of the screens (`MANAGER_UI=package`); an app with its own login keeps its own. + +## Media module + +Files live on a Laravel filesystem disk (`manager.media.disk`); each row remembers its own disk. + +- Manager (behind `manager.middleware`): `GET /manager/media`, `/manager/media/items`, `POST`, + `PUT /{id}`, `DELETE /{id}`. Limits (total room, file size, extensions) are in `manager.media.*`. +- Visitors: `GET /media-files/{id}/{filename}/view`, outside the manager, no session. ETag, byte + ranges, `nosniff`, and only images, video and PDF are shown inline. Rate limiter `media-files`. +- Where a file is used: other modules or your app register a source with + `app(IriksIT\Manager\Support\MediaUsage::class)->register(fn () => $texts)`. Posts and Pages do. +- No SVG: it can carry scripts. +- **Files at the IriksIT API** (the disk `iriksit`): set `MANAGER_MEDIA_DISK=iriksit` and `MANAGER_IRIKSIT_URL` (the address of the + API with its version, for example `https://api.iriks-it.nl/v1`), `MANAGER_IRIKSIT_EMAIL` and `MANAGER_IRIKSIT_PASSWORD`. The account needs + the permissions `storage.read` and `storage.write`. Run the migrations (table `storage_files`), then `php artisan manager:storage-check` + writes, reads and deletes a test file and says what fails. The API keeps a file under an id of its own; the table remembers + which path of the disk is which id, and a location without a slash that is not in the table is taken for an id (a row of a site's older code + keeps working). Tokens are kept encrypted in the cache of the app. There are no folders and no listing on this disk. + +## Commands + +| Command | What it does | +|---|---| +| `manager:install`, `manager:doctor [--json]` | Set the manager up, and check that it is wired in (for people and agents). | +| `manager:create-user` | A super admin. | +| `manager:users [--json]` | The accounts with their groups. | +| `manager:user-password [--generate]` | A new password for an account (typed hidden, never an argument). | +| `manager:settings list|get|set|reset|refresh` | The settings screen in the terminal; a secret is typed hidden or read from `--stdin`. | +| `manager:import posts|pages|reviews|media` | Copy the rows of a site's own table (`--map`, `--set=disk=iriksit`, `--dry-run`). | +| `manager:storage-check [--disk]` | Write, read and delete a test file on the disk of the media library. | +| `manager:media-move ` | Move the library to another disk, keeping every address (`--dry-run`, `--verify`, `--delete-source`). | +| `manager:media-prune` | List media nothing uses any more (`--older-than`), or files no row knows (`--orphans`); `--delete` removes. | +| `manager:audit-prune`, `manager:unban`, `manager:make-theme` | Housekeeping of the audit log, bans and themes. | + +## Field types + +`text`, `textarea`, `markdown`, `lines`, `media`, `url`, `number`, `date`, `toggle`, `select`, and for richer records: `slug` (`'from' => 'title'` fills it when empty), `list` (an array of short texts), +`media_list` (a gallery), `repeater` (`'items' => ['question' => ['type' => 'text'], 'answer' => ['type' => 'textarea']]`, an array of items) and a `select` with `'source' => ['model' => Service::class, 'label' => 'title', 'value' => 'id']`. +**Words for the simple face.** A field, a resource and a defined page can have words of their own for the simple face of the manager, for someone who is not a webmaster: `'phone' => ['label' => 'Phone number', 'help' => 'Shown on every page.', 'simple' => ['label' => 'Your phone number', 'help' => 'As you want people to read it.']]`; on a resource `'simple' => ['label' => 'What customers say', 'singular' => 'Customer review']` (also the menu item), on a page `'simple' => ['title' => 'About your business']`. A part left out falls back to the usual one, and the full face always shows the usual words. The presets (`Support\Presets`) bring plain-language words, which a site overrides like any other field. + +Used by pages and by `manager.resources`; a resource with a `model` writes straight into the site's own table (give JSON columns an `array` cast). + +## Features of the site + +A site that lists parts of itself that its owner may want to switch off (services, projects, reviews, requests, a contact form) declares them once: + +```php +'features' => ['services' => ['label' => 'Services', 'hint' => 'What you offer', 'enabled' => true, 'env' => 'SITE_SERVICES']], +'resources' => ['services' => ['feature' => 'services', 'label' => 'Services', 'fields' => [...]]], +``` + +Each feature is a toggle on the settings screen (group "Features of the site"). While it is off, the manager has no menu item, permission, screen or route for a resource with that +`feature`, and the public site follows the same switch: `Features::on('services')`, `Route::get(...)->middleware('manager.feature:services')` (a 404 while off), +`@feature('services') ... @endfeature` in Blade and `Features::flags()` to hand all of them to a page (links, sitemap, structured data). Off hides and never deletes: the data stays and comes back when the switch goes on. + +## Screens for the owner (`numbers`, `costs`, the simple start screen) + +For someone who owns the business and does not build sites. They show up as big buttons on the simple start screen (`manager.simple_view`). + +- **`numbers`** (needs `statistics`): visitors, the contact buttons, requests (when `leads` is on and the account has `leads.view`), pages, how people found the site, in plain words, with three periods to choose from. Right `numbers.view`. +- **`costs`**: the table of the site's `TOKENS.md` with the tokens of each piece of work in euros, per release, next to hours at an hourly rate, hosting and a discount (`manager.costs`). Right `costs.view`. A row is priced once and the price is kept in `work_costs`, by a pricer of the site (`manager.costs.pricer`, an invokable class), else by the IriksIT API with the account of `manager.media.iriksit` (needs `ai.pricing`), else by the fixed `manager.costs.rates`. `php artisan manager:costs-price` prices what is new, for example after a deploy. A site with no `TOKENS.md` shows an empty screen. +- **The start screen** says more than a fixed line under a button: how many requests wait (and how many are new, as a badge on the button), how many posts wait, how many visitors came this week. `manager.simple.help` (`name`, `link`) adds a "Need help?" button, and `manager.simple.site_link` a "View the site" button. + +## Requests module (`leads`) + +A request of a visitor (a callback request, a question, a quote, a contact form) is stored, screened and shown on the screen **Requests**. The forms are the site's own (their +fields, words and thank-you page); a form validates what it got and then calls the package: + +```php +use IriksIT\Manager\Support\Leads\Intake; + +// in the form: , and a honeypot field the visitor never sees +$lead = app(Intake::class)->take( + ['kind' => 'question', 'name' => $name, 'phone' => $phone, 'email' => $email, 'message' => $message, 'about' => 'job', 'subject' => 'Roofing', 'page' => $path], + Intake::secondsOpen($request->string('form_token')->toString()), // how long the form was open, null when the token says nothing + (string) $request->ip(), + (string) $request->userAgent(), +); +// always show the normal thank-you, whatever folder it landed in +``` + +- **Screening** puts a request in the inbox, "other" (acquisition, or the visitor ticked "something else") or spam, with the reasons kept next to it. Nothing is refused; one signal alone + is rarely enough. The rules and thresholds are `manager.leads` (`acquisition_words`, `throwaway_domains`, `spam_from`, `other_from`, `min_seconds`, `language`). +- **Forms without code:** `POST /requests/{form}` (`manager.leads.form`) takes the request in: a form is a name with the kind it makes and the fields it requires (`name`, `phone`, `email`, `contact` for one + box that takes either, `message`, `location`); `questions` and `moments` are what a visitor may tap. A honeypot field (`website`), the signed `form_token` (`Intake::formToken()`, or `GET /requests/token`), + Turnstile (when its keys are set; send its token as `turnstile`) and a limit per address and for all addresses (`per_hour`, `per_hour_all`) keep programs out. JSON gets `201 {ok: true}`, a form in a page is + redirected to `thanks` (or back). Name your own: `'terugbellen' => ['kind' => 'callback', 'require' => ['name', 'phone']]`. +- **Told:** a real request is mailed to `manager.leads.notify` (a setting) with call, WhatsApp and mail buttons; the visitor is the Reply-To. A confirmation to the visitor is `manager.leads.confirm`. + Replace the mail views by putting your own in `resources/views/vendor/manager/mail/`. +- **Report and taps:** whoever has `leads.manage` sees what it brought in on the screen. A page counts a press on the number or the WhatsApp button with `POST /requests/tap` (`kind` call or whatsapp, `path`). + A site with its own table moves it over with `php artisan manager:import leads --table=...` and `manager:import taps --table=...`. A contact form with a subject is the form `contact` (`kind` `message`; name, mail address, subject and message are required): `POST /requests/contact`. Contact messages a site stored in a table of its own come over with `manager:import leads --table=contact_messages --set=kind=message --map=opened_at=read_at`. +- **Permissions:** `leads.view`, `leads.handle`, `leads.manage` (folders, reasons, blocking), `leads.delete`. +- **Kept:** `php artisan manager:leads-prune` (schedule it daily) removes requests after `keep_days`, spam after `keep_spam_days` and expired blocks, and never a request with the outcome "won". +- With a feature `leads` in `manager.features` the module follows that one switch instead of `manager.modules.leads`. + +## Sharing module (`sharing`) + +Connects the owner's account of a social network (OAuth) and posts a published post there with the button **Share now** on the screen of the post. Off by default; it needs the posts module. + +- **LinkedIn** comes with the package. Create an app at LinkedIn with the products "Share on LinkedIn" and "Sign In with LinkedIn using OpenID Connect", put the address shown on the Sharing screen ("Return address for the app") in the app's redirect addresses, and fill in the client id and client secret on the settings screen (group "Sharing"; the secret is never shown again). Then press **Connect** under Sharing. +- `manager.sharing.post_url` says where a post lives (`https://example.test/blog/{slug}`); the shared address gets `?via=linkedin`, so the statistics know where a reader came from. +- **Dry run**: until the setting "Post for real" (`manager.sharing.live`) is on, a share is only written down (marked "dry run") and nothing is sent. Keep it off on a test site. +- A site adds a network by writing a class that implements `IriksIT\Manager\Contracts\Sharer` and listing it: `'platforms' => ['linkedin' => LinkedInSharer::class, 'mastodon' => App\Sharing\MastodonSharer::class]`. +- Tokens are stored encrypted and never leave the server; the connect step checks a session state and uses a PKCE verifier; what a platform says in an error is shown, a token never. +- Not in the package: planning a share for later, X, Facebook and Instagram, and fetching recommendations from LinkedIn (see ADR-0010 in the repository). + +## Settings module + +A screen (`/manager/settings`, only in the whole face of the manager) where an account with `settings.manage` switches parts of the manager on and off and +changes settings, and an account with `settings.secrets` also changes keys, passwords and addresses (the IriksIT API, Turnstile, the disk of the media). + +- A change is kept in the table `settings` (secrets encrypted) and in one compiled file, `bootstrap/cache/manager-settings.php`, that is laid over the config while + the app starts. So it works at once, on every server that shares the database, with or without `config:cache`, and a request reads one file from opcache, not the + database. "Refresh now" writes that file again and empties the caches. Without the file the table is read. +- `manager.settings.write_env` (`MANAGER_SETTINGS_WRITE_ENV`, off by default): also write the changed value into `.env`, when that file may be written. The old + one is kept as `.env.manager-backup`. Only variables that a definition names are ever written. +- Only what is defined can be set: the parts of the manager, the integrations of the package, and the site's own in `manager.settings.definitions` + (`'site.contact_form' => ['label' => 'Contact form', 'type' => 'toggle', 'group' => 'Site']`; the key is the config path it overrides, so + `config('site.contact_form')` has the answer). A module of your own can add some with a `settings()` method. +- What can send a password or a file elsewhere (secrets, addresses, accounts, disks) needs `settings.secrets` and the password of whoever saves it. A secret is + never sent to a browser; it is only said to be set. Clearing one is "back to what the config says". +- A part that is switched on and misses its tables is named: run `php artisan migrate`. + +## Pages module + +Pages are texts with keys, so the public site reads them and the owner edits them without code. Define a page in `config/manager.php`: + +```php +'pages' => ['definitions' => ['home' => ['title' => 'Home', 'fields' => [ + 'hero_title' => ['label' => 'Title on the photo', 'type' => 'text', 'default' => 'Welcome', 'max' => 120], + 'intro' => ['label' => 'Story', 'type' => 'markdown'], + 'photo' => ['label' => 'Photo', 'type' => 'media'], +]]]], +``` + +and read it with `IriksIT\Manager\Models\Page::contentFor('home')`: the stored values over the defaults, so a page that was never saved still has all its keys. Field types: `text`, `textarea`, `markdown`, `lines`, `media`, `url`, `number`, `date`, `toggle` and `select` (with `options`); `required`, `default`, `max`, `help` and `rules` work on all. The screens make the form, and the server validates and cleans every value by its type (a media or url value must be an address of the site or http(s)). A page without a definition is a free page with one Markdown text, a description for search engines and a publish switch; it can be made and removed in the screens. Permission: `pages.edit`. The definitions are shared code (`IriksIT\Manager\Support\Fields`), so other records can use them. + +## Posts module + +Posts written in Markdown, with drafts, scheduling, categories and tags. + +- Routes under `/manager`: `posts` (list, `create`, `{id}/edit`, `{id}/preview`, update, `{id}/online`, + delete) and `labels` (categories and tags: make, rename, merge, remove). Rights: `posts.view`, `write`, + `publish`, `delete`, `labels`. +- Who may not publish only saves drafts, and cannot change or delete a post that is live or scheduled. +- A post is a draft (`published_at` null), scheduled (in the future) or published. For your public pages: + `IriksIT\Manager\Models\Post::published()`, `toCard()` and `IriksIT\Manager\Support\Markdown::toHtml()` + (raw HTML is escaped, external links open in a new window). The package has no public post routes: the + host decides what a visitor sees. +- Categories offered in the form: `manager.posts.categories`, the ones in use, the ones made by hand and + whatever your site adds with + `app(IriksIT\Manager\Modules\Posts\PostLabels::class)->suggestCategories(fn () => $titles)`. +- Covers and bodies count as use of a media file. + +## The editor + +Texts in Markdown (posts, free pages and `markdown` fields) have a toolbar (bold, italic, heading, list, quote, link), a **Photo** button that puts a picture from the media library into the text, and a **Preview** that is rendered by the server the way the site renders it (raw HTML is escaped; `POST /manager/markdown`, not written in the audit log). In the media library a click on a picture sets its **focus point** (`focus_x`, `focus_y`, 0 to 1): the part that must stay in view when the site crops it, shown in a square preview. There is no cropping or rotating in the manager: the file is kept as it was uploaded, and the site crops with the focus point. + +## History module + +Every save of a post or a page keeps its state (`manager_revisions`, the newest 50 per record, `manager.revisions.keep`), with who saved it and which fields changed; saving the same state again keeps nothing. The post and page screens show the history, and `revisions.restore` puts an earlier state back, which is a save like any other (so what was there is in the history too). Whether a post is on the site (`published_at`) and whether a page is published is not part of the history: going back in time never publishes or hides anything. A live post can only be put back by someone who may publish. Permissions: `revisions.view` (and the permission to see that kind of text) and `revisions.restore` (and the permission to write it). A site adds its own models with `manager.revisions.types`, e.g. `'services' => ['model' => App\\Models\\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']`. `MANAGER_REVISIONS=false` turns the module off. + +## Audit module + +Off by default: it stores IP addresses and browser lines, so a site switches it on knowingly and says so in its +privacy policy (`MANAGER_AUDIT=true`). + +- **The log**: logins, logouts and failed logins (from Laravel's own `Login`, `Logout` and `Failed` events, so it + works with any login the host has), every change in the manager, every page that is opened (not twice within + five minutes) and every refusal. Only the account, the address and the browser line are kept, and for an action + the fields its module listed, never what was typed into a form. The log is read with `audit.view`. +- **Names**: a module says what its routes are called in the log with `actions()` and `views()`; a test fails on a + manager route without a name. +- **Bans** (`audit.manage`): ban an address by hand, for a time or until lifted, or a whole group of addresses + (notes put addresses in a group). After too many failed logins an address is banned by itself (the rules are set + in the manager). A banned address gets a 403 (429 for an automatic ban) on every manager route. Put the + `manager.not-banned` middleware on the login routes of your app too. A site that is locked out lifts the ban + with `php artisan manager:unban {ip}`. +- **Behind a proxy**: set up trusted proxies (or `MANAGER_NEVER_BAN`) before switching the module on. Without + them every visitor shares one address, and one bad actor can lock the whole manager out. Failed logins on any + guard count towards the automatic ban. +- **Whole-site bans**: with `MANAGER_AUDIT_WHOLE_SITE_BANS=true` a ban can also keep an address off the whole app. + That adds a global middleware that is answered from the cache. +- **Config** (`manager.audit`): `never_ban` (`MANAGER_NEVER_BAN`, comma-separated: your own addresses), and + `max_keep_days` (`MANAGER_AUDIT_MAX_KEEP_DAYS`, 90): the longest the log may be kept, which your privacy policy + has to agree with. `manager:audit-prune` runs daily and deletes old lines and ended bans; notes stay until removed. + +## Statistics module + +Off by default (`MANAGER_STATISTICS=true`). The site's own visitor statistics, with no cookie and no stored IP address: +a visitor is a code made of the address, the browser and a random key that is deleted after a day (`manager:forget-visitor-keys`, +scheduled daily), so a code cannot be traced back afterwards. A browser that sends `DNT` or `Sec-GPC` is not counted. + +- **The script**: put `` once in the layout of the public site (`:spa="true"` for a site with a client-side router). It loads `/pulse/pulse.js` (about 2 kB, plain JavaScript, no cookies or storage), reports the page and the time it was in view, and does nothing for a browser with Do Not Track or Global Privacy Control. With the module off the component prints nothing. Behind a Content-Security-Policy allow that one script address. +- **Reporting** (what the script does, for a site that wants to do it itself): the pages of your site `POST` to `/pulse/view` (`{path, referrer, via, campaign}`, answers `{token}`) and, when the + visitor leaves, `/pulse/leave` (`{token, seconds}`). No session, rate limited (`manager.statistics.per_minute`). +- **Which pages count**: only addresses you name, so nobody can fill the statistics with made-up ones: + `manager.statistics.pages`, the posts under `manager.statistics.posts_path` (published ones only), and anything else through + `app(IriksIT\Manager\Modules\Statistics\CountedPages::class)->register(fn (string $path) => ...)`. +- **Programs**: the pages served to search engines, crawlers and previews are counted per day, program and page (no address, no browser + line), by a middleware the module adds to the `web` group (`manager.statistics.count_bots`). +- **The report** (`statistics.view`): visitors, visits, page views, time, bounce rate, a comparison with another period, pages, posts, + sources and channels, devices, heatmap, programs; `GET /manager/statistics?range=30d` and a CSV per sheet + (`/manager/statistics/export?sheet=days|pages|sources|bots`). +- **Country** only when `manager.statistics.country_header` names a header (Cloudflare: `CF-IPCountry`). + +## State of this version + +Done: module registry and switches, permissions per module, users (accounts, groups, command, roles of the host), media (library and +public file route, focus point), posts (with categories and tags), pages with fields, lists defined in config, the history with restore, +the audit log with bans, the statistics (with the counting script), the built-in screens for all of these (with a login, checks on the +login, a profile and the simple view), an editor, themes, translations, a site's own bundle of screens, the import of existing data, and +the install and doctor commands for AI agents. `composer test` runs the tests. + +Reviews are still a read-only list. The answers of every action are JSON in the shape the screens use, so an app can build its own screens +with `MANAGER_UI=none`. Not in the package: two-factor login (the login checks are the place for it), cropping or rotating pictures, a theme editor. + +## Development cycle + +``` +develop ── feature/*, fix/* ──► release/vX.Y.Z ──► production ──► tag vX.Y.Z ──► Packagist + ▲ (pull request, (collects the (pull request, │ + │ merges by itself) features) merged by hand) │ + └──────────────────────── sync: production into develop ◄─────────────────────────┘ +``` + +1. **Start a release:** Actions → *Start release* → version (`0.2.0`). That makes `release/v0.2.0` from `develop`. +2. **Features:** branch `feature/…` or `fix/…` from `develop`, open a pull request to the release branch. It + merges by itself when *PR CI* is green. Every pull request adds its row to `TOKENS.md`. +3. **Ready:** add a section `## v0.2.0 - date` to `CHANGELOG.md` and open a pull request from the release branch + to `production`. A person merges it. +4. **Release (automatic, on the merge):** tests and audit once more, the tag `v0.2.0` and a Gitea release with the + changelog text, Packagist is told, and `production` is merged into `develop`. + +Nobody opens a pull request to `develop`, and `production` and the release branches take no direct pushes. + +| 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 | +| 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) | + +### Security and updates + +Nothing here runs on a weekly schedule; the checks hang on the moments that matter, and the homelab does the rest every night. + +- **Every pull request:** `composer audit` (it fails on any advisory). +- **Every release:** `composer audit` again on the merge to `production`. +- **After every release to production:** Trivy scans `production` from the homelab (LXC 120, no database to download in a job). +- **Every night:** Trivy scans every repository of the organisation (03:00), and the dependency round (04:00) opens a pull request + `renovate/deps-DATE` straight to `production` for updates that have been public for 48 hours. PR CI tests it, and when it is + 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. + +## What Composer installs + +`.gitattributes` leaves what only belongs to the repository out of the package (`export-ignore`): `.gitea/`, +`dev/`, `scripts/`, `tests/`, `TOKENS.md`, `AGENTS.md`, `phpunit.xml` and the dotfiles. They stay in the repository. +Packagist builds the archive from `git archive`, so what a site installs is `src/`, `config/`, `routes/`, +`resources/`, `composer.json`, `README.md` and `CHANGELOG.md`. Check it with `git archive HEAD | tar -t`. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..41dec73 --- /dev/null +++ b/composer.json @@ -0,0 +1,59 @@ +{ + "name": "iriks-it/laravel-manager", + "description": "A modular backend (manager) for Laravel sites: users, media, pages, posts, reviews. Every part can be switched on or off.", + "type": "library", + "license": "MIT", + "keywords": ["laravel", "manager", "cms", "admin", "modules"], + "require": { + "php": "^8.4", + "illuminate/auth": "^13.0", + "illuminate/cache": "^13.0", + "illuminate/console": "^13.0", + "illuminate/contracts": "^13.0", + "illuminate/database": "^13.0", + "illuminate/filesystem": "^13.0", + "illuminate/http": "^13.0", + "illuminate/routing": "^13.0", + "illuminate/support": "^13.0", + "illuminate/validation": "^13.0", + "league/commonmark": "^2.6", + "league/flysystem": "^3.0" + }, + "require-dev": { + "orchestra/testbench": "^11.0", + "pestphp/pest": "^5.0", + "laravel/pint": "^1.15" + }, + "autoload": { + "psr-4": { + "IriksIT\\Manager\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "IriksIT\\Manager\\Tests\\": "tests/" + } + }, + "extra": { + "laravel": { + "providers": [ + "IriksIT\\Manager\\ManagerServiceProvider" + ], + "aliases": { + "Manager": "IriksIT\\Manager\\Facades\\Manager" + } + } + }, + "scripts": { + "test": "pest", + "lint": "pint --test" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true + } + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/config/manager.php b/config/manager.php new file mode 100644 index 0000000..367634b --- /dev/null +++ b/config/manager.php @@ -0,0 +1,396 @@ + env('MANAGER_PATH', 'manager'), + + /* + | Middleware around every manager route. Authentication of the manager itself + | is left to the host app: use the guard it already has. + */ + 'middleware' => ['web', 'manager.auth'], + + /* + | The screens. `package`: the manager brings its own (a Vue app, built, served by the package; it also gives a login and + | a profile when the app has none). `none`: only the JSON API, for an app that builds its own screens. + */ + 'ui' => env('MANAGER_UI', 'package'), + + /* + | The name in the menu and on the login screen. + */ + 'name' => env('MANAGER_NAME'), + + /* + | Looks. `theme` is what everyone gets until they choose; `user_themes` lets each account pick its own (profile). + | A theme is a set of colours, a radius and fonts: built in are `dark` and `light`; the site's own live as JSON files in + | `themes_path` (make one with `php artisan manager:make-theme`) or here in `themes`, by key. + */ + 'theme' => env('MANAGER_THEME', 'dark'), + 'user_themes' => (bool) env('MANAGER_USER_THEMES', true), + 'themes_path' => null, // default: resources/manager-themes of the app + 'themes' => [], + + /* + | The Eloquent model of the people who log in. Must use IriksIT\Manager\Concerns\HasManagerAccess. + */ + 'user_model' => env('MANAGER_USER_MODEL', 'App\\Models\\User'), + + /* + | The modules this manager knows. Add your own class here to give a site its own part. + */ + 'available' => [ + Modules\Users\UsersModule::class, + Modules\Media\MediaModule::class, + Modules\Pages\PagesModule::class, + Modules\Posts\PostsModule::class, + Modules\Reviews\ReviewsModule::class, + Modules\Audit\AuditModule::class, + Modules\Statistics\StatisticsModule::class, + Modules\Resources\ResourcesModule::class, + Modules\Revisions\RevisionsModule::class, + Modules\Settings\SettingsModule::class, + Modules\Leads\LeadsModule::class, + Modules\Updates\UpdatesModule::class, + Modules\Sharing\SharingModule::class, + Modules\Costs\CostsModule::class, + Modules\Numbers\NumbersModule::class, + ], + + /* + | Switch a part on or off per site. A key left out falls back to the default of the + | module: users and media are on, everything else is off. A module that is off has no + | routes, no tables (its migrations are not loaded), no menu item and no permissions. + */ + 'modules' => [ + 'users' => true, + 'media' => true, + 'pages' => env('MANAGER_PAGES', true), + 'posts' => env('MANAGER_POSTS', true), + 'reviews' => env('MANAGER_REVIEWS', false), + 'audit' => env('MANAGER_AUDIT', false), + 'statistics' => env('MANAGER_STATISTICS', false), + 'resources' => true, + 'revisions' => env('MANAGER_REVISIONS', true), + 'updates' => env('MANAGER_UPDATES', false), + 'sharing' => env('MANAGER_SHARING', false), + 'costs' => env('MANAGER_COSTS', false), + 'numbers' => env('MANAGER_NUMBERS', false), + 'settings' => true, + 'leads' => env('MANAGER_LEADS', false), + ], + + /* + | Features of the site that the settings screen switches on and off: one switch that the manager and the public site both follow. + | 'services' => ['label' => 'Services', 'hint' => 'The page with what you offer', 'enabled' => true, 'env' => 'SITE_SERVICES'] + | In the manager: a `resources` entry with `'feature' => 'services'` is left out while the feature is off. In the site: `Features::on('services')`, + | the route middleware `manager.feature:services` (404 while off) and `@feature('services') … @endfeature`. Off hides, it never deletes data. + */ + 'features' => [], + + /* + | The media library. Files live on a Laravel filesystem disk; each media row remembers + | its own disk, so a file stays where it was uploaded when `disk` changes later. + */ + 'media' => [ + 'disk' => env('MANAGER_MEDIA_DISK', 'public'), + + // How much room the library has in total, in GB. An upload that would go over it is refused. + 'max_total_gb' => (float) env('MANAGER_MEDIA_MAX_TOTAL_GB', 15), + + // Largest single upload in MB. PHP and the web server must allow it too + // (upload_max_filesize, post_max_size, client_max_body_size). + 'max_file_mb' => (int) env('MANAGER_MEDIA_MAX_FILE_MB', 40), + + // File extensions the library accepts. SVG is deliberately missing: it can carry scripts. + 'extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'mp4', 'webm'], + + // The disk `iriksit` keeps files at the IriksIT API (set `disk` to `iriksit`). The account needs the permissions + // `storage.read` and `storage.write`. Leave this empty for any other disk. + 'iriksit' => [ + 'url' => env('MANAGER_IRIKSIT_URL'), + 'email' => env('MANAGER_IRIKSIT_EMAIL'), + 'password' => env('MANAGER_IRIKSIT_PASSWORD'), + 'timeout' => 300, + ], + + // Visitors loading files per minute per address (the `media-files` rate limiter). + 'per_minute' => 600, + ], + + /* + | Posts. `categories` are always offered in the post form, next to the ones in use and the + | ones made by hand; a site can offer more through PostLabels::suggestCategories(). + */ + 'posts' => [ + 'categories' => ['General'], + ], + + /* + | Markdown in posts: hosts besides APP_URL whose links do not open in a new window. + */ + 'markdown' => [ + 'internal_hosts' => [], + ], + + /* + | The audit log and the bans (module `audit`). + */ + 'audit' => [ + // Addresses that are never banned, by hand or by themselves: your own, so a slip or a rule + // that is too strict never locks you out. Comma-separated in MANAGER_NEVER_BAN. + 'never_ban' => array_values(array_filter(array_map('trim', explode(',', (string) env('MANAGER_NEVER_BAN', ''))))), + + // The longest the log may be kept, in days. Set it to what your privacy policy promises. + 'max_keep_days' => (int) env('MANAGER_AUDIT_MAX_KEEP_DAYS', 90), + + // Let a ban "for the whole site" work: the middleware then runs on every request of the app. + 'whole_site_bans' => (bool) env('MANAGER_AUDIT_WHOLE_SITE_BANS', false), + ], + + /* + | The visitor statistics (module `statistics`). + */ + 'statistics' => [ + // The addresses of the public site that count as a page. Anything else is ignored, so + // nobody can fill the statistics with made-up addresses. Posts and other kinds of pages + // come from `posts_path` or a resolver: app(CountedPages::class)->register(fn ($path) => ...). + 'pages' => ['/'], + + // The address under which the posts live (`/blog` for `/blog/my-post`); null: posts are not counted. + 'posts_path' => null, + + // Where the public pages report a view (POST {pulse_path}/view and {pulse_path}/leave). + 'pulse_path' => 'pulse', + + // Reports per minute per address. + 'per_minute' => 120, + + // The request header with the country code of the visitor, e.g. CF-IPCountry behind Cloudflare. Null: no country. + 'country_header' => env('MANAGER_STATISTICS_COUNTRY_HEADER'), + + // Count the pages served to programs (search engines, crawlers) by adding a middleware to the `web` group. + 'count_bots' => (bool) env('MANAGER_STATISTICS_COUNT_BOTS', true), + ], + + /* + | Pages with fields (module `pages`): per slug a title and the fields the screens make a form of, and the + | public site reads with `IriksIT\Manager\Models\Page::contentFor('home')`: + | 'definitions' => ['home' => ['title' => 'Home', 'fields' => [ + | 'hero_title' => ['label' => 'Title on the photo', 'type' => 'text'], + | 'intro' => ['label' => 'Story', 'type' => 'markdown'], + | 'photo' => ['label' => 'Photo', 'type' => 'media'], + | ]]]. + | Types: text, textarea, markdown, lines, media, url, number, date, toggle, select (with `options`). + */ + 'pages' => ['definitions' => [], 'checks' => []], + + /* + | Lists the site manages without code of its own: a form, a list, permissions (`.view`, `.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, + | 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => ['name' => ['type' => 'text', 'required' => true], ...]] + */ + 'resources' => [], + + /* + | A bundle of the site's own screens: JavaScript modules (a path of the site, or https) the manager loads next to its own, + | after it has started. They add screens with `IriksManager.register('^/leads$', Component, { data: true })`, and may + | `import { ref } from 'vue'` when the build leaves `vue` external. See README, "Your own screens". + */ + 'extensions' => [], + + /* + | The history of posts and pages (module `revisions`): `keep` states per record, more `types` of the site's own + | (['services' => ['model' => App\Models\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']]), + | and `skip` for model classes that should not have one. + */ + 'revisions' => ['keep' => 50, 'types' => [], 'skip' => []], + + /* + | More a login asks for. `checks`: classes that implement IriksIT\Manager\Contracts\LoginCheck (extend + | IriksIT\Manager\Support\Login\BaseLoginCheck): a field of the form, something to check before the password is + | tried (a captcha) or after it was right (a second factor). Cloudflare Turnstile is built in and turns itself on + | when both of its keys are set. These apply to the login of the manager's own screens. + */ + 'login' => [ + 'checks' => [], + 'turnstile' => ['site_key' => env('MANAGER_TURNSTILE_SITE_KEY'), 'secret' => env('MANAGER_TURNSTILE_SECRET')], + ], + + /* + | Who may do what. `groups` (default): the groups of the package. A site that has roles of its own can say it itself: + | `host` takes the permissions only from the site, `merge` adds them to what the groups give. The site's side is a + | `resolver` class (IriksIT\Manager\Contracts\PermissionResolver), or, simpler, `roles` per role name (`*` is + | everything) read from the attribute `role_attribute` of the account (a string, a list or a relation with a `name`). + | 'roles' => ['editor' => ['posts.view', 'posts.write'], 'owner' => ['*']]. A super admin may always do everything. + */ + 'permissions' => ['mode' => env('MANAGER_PERMISSIONS', 'groups'), 'resolver' => null, 'roles' => [], 'role_attribute' => 'role'], + + /* + | The menu. `items` changes what a module gives, by the route name without the prefix: + | 'posts.index' => ['order' => 10, 'section' => 'Content', 'icon' => 'file', 'simple' => true, 'hidden' => false]. + | `links` adds items of the site's own: ['label' => 'Leads', 'url' => '/manager/leads', 'permission' => null, + | 'section' => ..., 'icon' => ..., 'order' => ..., 'simple' => ..., 'new_tab' => ...]. + | Icons: home, file, image, users, group, chart, shield, star, tag, link, cog. + */ + 'menu' => ['items' => [], 'links' => []], + + /* + | A simple face of the manager next to the full one. With this on, the permissions `manager.full` and + | `manager.switch` exist: an account with the first (or a super admin) gets everything; one with the + | second starts simple and may switch; all others always get the simple face, which shows only the + | menu items marked `simple`. Off: everyone sees the whole menu. + */ + 'simple_view' => (bool) env('MANAGER_SIMPLE_VIEW', false), + + /* + | What the simple start screen shows under its big buttons: `help` is a way to ask for help, a name and a link (for example a WhatsApp + | link), and `site_link` the address of the site ("View the site"; null leaves it out). + */ + 'simple' => ['help' => ['name' => env('MANAGER_HELP_NAME'), 'link' => env('MANAGER_HELP_LINK')], 'site_link' => '/'], + + /* + | 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], + + /* + | The settings screen (module `settings`, whole face of the manager only). Changes are kept in the database and in one compiled file + | and work at once. `write_env` also writes the changed value into .env, when that file may be written (it is left alone otherwise). + | `definitions` adds settings of the site's own, by the config path they override: + | 'site.contact_form' => ['label' => 'Contact form', 'type' => 'toggle', 'group' => 'Site', 'env' => 'CONTACT_FORM']. + | Types: toggle, text, url, number, select (with `options`), secret (never shown again). A definition with `sensitive` => true needs the + | right `settings.secrets` and the password of whoever saves it. `checks` adds a "try it" button to a group of settings: + | `'Group name' => SomeClass::class`, invokable, returns what worked and throws when it did not. + */ + 'settings' => ['write_env' => (bool) env('MANAGER_SETTINGS_WRITE_ENV', false), 'definitions' => [], 'checks' => []], + + /* + | Sharing posts on social networks (module `sharing`). `platforms` is name => class of a `Contracts\Sharer`; LinkedIn comes with the + | package, a site adds its own. `post_url` says where a post lives on the site (`{slug}` is its address), `live` is whether a + | share is sent for real (off: a dry run, nothing leaves the site). The keys of the app of a platform are settings (secrets). + */ + 'sharing' => [ + 'platforms' => ['linkedin' => Modules\Sharing\LinkedInSharer::class], + 'post_url' => env('MANAGER_SHARING_POST_URL'), + 'live' => (bool) env('MANAGER_SHARING_LIVE', false), + 'linkedin' => [ + 'client_id' => env('MANAGER_LINKEDIN_CLIENT_ID'), + 'client_secret' => env('MANAGER_LINKEDIN_CLIENT_SECRET'), + 'auth_url' => 'https://www.linkedin.com/oauth/v2', + 'userinfo_url' => 'https://api.linkedin.com/v2/userinfo', + 'base_url' => 'https://api.linkedin.com/rest', + 'version' => '202511', + ], + ], + + /* + | What changed on the site (module `updates`): the releases of a CHANGELOG.md, newest first. `changelog` is the file (default: the + | CHANGELOG.md in the root of the site) and `limit` how many releases the screen shows. + */ + 'updates' => ['changelog' => env('MANAGER_UPDATES_CHANGELOG'), 'limit' => 20], + + /* + | What the work on the site has cost (module `costs`): the table of the site's TOKENS.md (`ledger`, default the TOKENS.md in the root of the + | site) with the tokens of each piece of work in euros. A row is priced once and the price is kept. Who prices it: `pricer` (an invokable + | class of the site that gets the rows to price and returns ['row-0' => ['usd' => ..., 'eur' => ..., 'usd_per_eur' => ...]]), else the IriksIT + | API when `media.iriksit` is set (switch it off with `use_api`; the account needs `ai.pricing`), else the fixed `rates` (US dollars per + | million tokens per model: ['model' => ['input' => ..., 'cache_write' => ..., 'cache_read' => ..., 'output' => ...]]) with `usd_to_eur`. + | `hourly_rate` turns the hours of a row into euros, `hosting` is a yearly amount from a day on, `discount` a share of the work and the AI + | costs before a day. `assign_open_to_newest` puts a row without a release in the newest release (right on a site where everything that + | is deployed is released). + */ + 'costs' => [ + 'ledger' => env('MANAGER_COSTS_LEDGER'), + 'hourly_rate' => (float) env('MANAGER_COSTS_HOURLY_RATE', 0), + 'hosting' => ['per_year' => 0, 'from' => null], + 'discount' => ['percent' => 0, 'until' => null], + 'pricer' => null, + 'use_api' => true, + 'rates' => [], + 'usd_to_eur' => null, + 'assign_open_to_newest' => false, + ], + + /* + | The requests of visitors (module `leads`): how they are screened and kept. Every rule is a setting; nothing is ever refused on score, + | the worst that happens to a real request is the folder "other". `kinds` names the forms of the site (kind => label), `notify` is where a + | real request is mailed to (a setting on the settings screen), `confirm` mails the visitor a short confirmation, `source` is an invokable + | class that tells where a visit came from (returns ['channel' => ..., 'source' => ...]), `language` (nl, en or null) marks text in another + | language as spam, `country_code` is the home country for phone numbers. + */ + 'leads' => [ + 'kinds' => ['callback' => 'Callback request', 'question' => 'Question', 'quote' => 'Quote request', 'message' => 'Message'], + 'notify' => env('MANAGER_LEADS_NOTIFY'), + 'confirm' => false, + 'source' => null, + 'language' => null, + 'country_code' => '31', + // The public forms (`POST /{path}/{form}`, see Modules\Leads\LeadFormController): a form is a name with the kind it makes and the fields it + // requires (name, phone, email, contact = one box for either, message, location). `questions` and `moments` are what a visitor may tap. + // `thanks` is where a visitor lands after sending (null: back to the page). A honeypot field and Turnstile (when its keys are set) keep programs out. + 'form' => [ + 'path' => 'requests', + 'honeypot' => 'website', + 'turnstile' => true, + 'thanks' => null, + 'per_hour' => 6, + 'per_hour_all' => 120, + 'forms' => [ + 'callback' => ['kind' => 'callback', 'require' => ['name', 'phone']], + 'question' => ['kind' => 'question', 'require' => ['name', 'contact', 'message']], + 'quote' => ['kind' => 'quote', 'require' => ['name', 'phone', 'location']], + 'contact' => ['kind' => 'message', 'require' => ['name', 'email', 'subject', 'message']], + ], + 'questions' => [], + 'moments' => [], + ], + 'min_seconds' => 3, + 'max_hours' => 24, + 'spam_from' => 5, + 'other_from' => 3, + 'keep_days' => 365, + 'keep_spam_days' => 30, + 'acquisition_words' => [ + 'seo', 'backlinks', 'backlink', 'linkbuilding', 'lead generation', 'more leads', 'more customers', 'web design', 'webdesign', 'web development', + 'digital marketing', 'online marketing', 'marketing agency', 'social media management', 'free analysis', 'our offer', 'we offer', 'partnership', + 'guest post', 'sponsored', 'crypto', 'investment', 'loan', 'traffic', 'ranking', + ], + 'throwaway_domains' => [ + 'mailinator.com', 'guerrillamail.com', 'guerrillamail.net', 'sharklasers.com', '10minutemail.com', 'tempmail.com', 'temp-mail.org', 'yopmail.com', + 'trashmail.com', 'getnada.com', 'dispostable.com', 'maildrop.cc', 'mailnesia.com', 'throwawaymail.com', 'fakeinbox.com', 'mohmal.com', 'emailondeck.com', + ], + ], + + /* + | Prefix for the tables of the package. + */ + 'table_prefix' => 'manager_', + + /* + | A table with a name of its own, by short name (`posts`, `pages`, `media`, ...): wins over the prefix. + | Set it before the first migrate; the package never renames a table that exists. + */ + 'tables' => [], + + /* + | Prefix of the route names (`manager.posts.index`). Change it when the site already has `manager.*` + | routes; menu items and screens follow by themselves. + */ + 'route_name' => 'manager', + + /* + | Where `php artisan manager:import ` reads from, so it needs no options: + | 'posts' => ['table' => 'articles', 'connection' => null, 'map' => ['title' => 'headline']]. + */ + 'import' => [], +]; diff --git a/database/migrations/2026_12_05_000001_create_manager_user_settings.php b/database/migrations/2026_12_05_000001_create_manager_user_settings.php new file mode 100644 index 0000000..614d985 --- /dev/null +++ b/database/migrations/2026_12_05_000001_create_manager_user_settings.php @@ -0,0 +1,27 @@ +getTable(); + + Tables::create(Names::table('user_settings'), function (Blueprint $table) use ($users) { + $table->id(); + $table->foreignId('user_id')->unique()->constrained($users)->cascadeOnDelete(); + $table->string('theme', 60)->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('user_settings')); + } +}; diff --git a/database/migrations/2026_12_06_000001_add_view_to_manager_user_settings.php b/database/migrations/2026_12_06_000001_add_view_to_manager_user_settings.php new file mode 100644 index 0000000..df4cecb --- /dev/null +++ b/database/migrations/2026_12_06_000001_add_view_to_manager_user_settings.php @@ -0,0 +1,24 @@ +string('view', 10)->nullable()->after('theme'); + }); + } + + public function down(): void + { + Schema::table(Names::table('user_settings'), function (Blueprint $table) { + $table->dropColumn('view'); + }); + } +}; diff --git a/database/migrations/2026_12_07_000001_add_locale_and_tutorial_to_manager_user_settings.php b/database/migrations/2026_12_07_000001_add_locale_and_tutorial_to_manager_user_settings.php new file mode 100644 index 0000000..9ca6724 --- /dev/null +++ b/database/migrations/2026_12_07_000001_add_locale_and_tutorial_to_manager_user_settings.php @@ -0,0 +1,25 @@ +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']); + }); + } +}; diff --git a/resources/ai/INTEGRATION.md b/resources/ai/INTEGRATION.md new file mode 100644 index 0000000..8f8e750 --- /dev/null +++ b/resources/ai/INTEGRATION.md @@ -0,0 +1,39 @@ +# Integrating iriks-it/laravel-manager (guide for AI agents) + +Goal: the manager runs in this Laravel app and `php artisan manager:doctor --json` says `"ok": true`. Do the steps in +order and never edit files inside `vendor/`. + +1. `composer require iriks-it/laravel-manager` + (A version that is not on Packagist yet: first `composer config repositories.manager --json '{"type":"path","url":"/path/to/laravel-manager","options":{"symlink":false}}'`, then require `@dev`.) +2. Pick the modules. `users` and `media` are on; `pages` and `posts` are on by default; `reviews`, `audit` and `statistics` are off + (audit and statistics store visitor data: only switch them on when the owner says so). +3. `php artisan manager:install --modules=users,media,posts --user-model="App\Models\User"` + It writes the `MANAGER_*` switches to `.env` and publishes `config/manager.php`. Add `--path=admin` to move the URL. + It does not run the check itself (this process still has the old config): that is step 7. +4. Add the trait to the user model: `use \IriksIT\Manager\Concerns\HasManagerAccess;`. Never put `is_super_admin` in `$fillable`. +5. `php artisan config:clear && php artisan migrate && php artisan storage:link` (a new process, so it sees the switches of step 3). +6. Create the first super admin: `php artisan manager:create-user --name="..." --email="..." --password="<12+ chars>"`. +7. `php artisan manager:doctor --json`. Every check must be `ok` or an understood `warn`; each `fail` and `warn` has a `fix`. + Repeat until `"ok": true`. + +Facts that matter: +- A site that already has `manager.*` route names, `manager_*` tables or its own posts and pages: `manager:doctor` has a `names` check that says + so. Set `route_name`, `table_prefix` or `tables` in `config/manager.php` before the first `migrate`, then copy what exists with + `php artisan manager:import posts|pages|reviews --table= --map== --dry-run` (the source is only read). +- What the site's own content looks like is configuration, not code: `manager.pages.definitions` (texts with keys, read with `Page::contentFor('slug')`), + `manager.resources` (lists such as services or testimonials, in a model of the site or the package's table) and `manager.menu` (order, sections, + icons, own links). A screen that needs code is a JavaScript module in `manager.extensions`; it registers with `IriksManager.register`. +- Who may do what: the groups of the package, or the roles of the site (`manager.permissions`); more on the login: `manager.login.checks`, Turnstile + with two env keys. The public pages count visits with `` when `statistics` is on. +- The screens are part of the package (`MANAGER_UI=package`, the default): open `/manager` in a browser. The app does not need a + login of its own: when it has no route named `login`, the manager's own login at `/manager/login` is used. With + `MANAGER_UI=none` there are only the JSON routes. +- A browser address gets the screens, a request with `Accept: application/json` gets the data. To call the JSON routes from a + script: `GET /manager/login` once for the `XSRF-TOKEN` cookie, then `POST /manager/login` with header `X-XSRF-TOKEN` (the cookie + value, URL-decoded), `Accept: application/json` and body `{"email": "...", "password": "..."}`; the answer is `{"redirect": "/manager"}`. +- The look: `MANAGER_THEME=dark|light` or your own (`php artisan manager:make-theme acme --brand=#e4002b --name="Acme" --logo=/img/logo.svg`, + then `MANAGER_THEME=acme`). Each account can pick its own in its profile (`MANAGER_USER_THEMES=false` stops that). +- Anything that is off has no routes, tables or permissions. A module that needs another one fails at boot when that one is off. +- Do not add site-specific code to the package: a site's own part is its own module class (`Contracts\Module`, extend + `Modules\BaseModule`, add it to `manager.available`). +- Behind a proxy set trusted proxies before switching `audit` on. diff --git a/resources/boost/guidelines/core.blade.php b/resources/boost/guidelines/core.blade.php new file mode 100644 index 0000000..59914dd --- /dev/null +++ b/resources/boost/guidelines/core.blade.php @@ -0,0 +1,10 @@ +## iriks-it/laravel-manager + +A modular backend (users, media, pages, posts, reviews, audit, statistics, resources, revisions) installed as a package. + +- To integrate it, follow `vendor/iriks-it/laravel-manager/resources/ai/INTEGRATION.md` step by step. +- Set it up with `php artisan manager:install --modules=... --user-model=...`, then `config:clear`, `migrate`, `storage:link`; verify in a new process with `php artisan manager:doctor --json` (non-zero exit on failure, every problem has a `fix`). +- The screens come with the package (`MANAGER_UI`), including a login when the app has none; themes: `php artisan manager:make-theme`, `MANAGER_THEME`. +- The user model needs the `HasManagerAccess` trait; `is_super_admin` is never mass assignable. The first super admin comes from `php artisan manager:create-user`. +- The site's content is configuration: `manager.pages.definitions`, `manager.resources`, `manager.menu`, `manager.permissions`, `manager.login.checks`; code only as a JavaScript module in `manager.extensions`. Existing data comes in with `php artisan manager:import`. +- Switch parts with `MANAGER_=true|false`; never edit `vendor/`. Site-specific parts are your own `Module` class. diff --git a/resources/dist/manager.css b/resources/dist/manager.css new file mode 100644 index 0000000..0ef2528 --- /dev/null +++ b/resources/dist/manager.css @@ -0,0 +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-base:1rem;--text-base--line-height:calc(1.5 / 1);--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);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--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-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-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components{.m-card{background:var(--m-panel);border:1px solid var(--m-line);border-radius:var(--m-radius,.5rem)}.m-btn{border-radius:var(--m-radius,.5rem);cursor:pointer;border:1px solid #0000;align-items:center;gap:.4rem;padding:.5rem .9rem;font-size:.875rem;font-weight:600;transition:filter .15s;display:inline-flex}.m-btn:disabled{opacity:.5;cursor:not-allowed}.m-btn-primary{background:var(--m-brand);color:#fff}.m-btn-primary:hover:not(:disabled){filter:brightness(1.1)}.m-btn-secondary{background:var(--m-panel-2);border-color:var(--m-line);color:var(--m-text)}.m-btn-secondary:hover:not(:disabled){filter:brightness(1.15)}.m-btn-danger{color:#ef4444;background:0 0;border-color:#ef444466}.m-label{color:var(--m-muted);margin-bottom:.25rem;font-size:.8rem;font-weight:600;display:block}.m-input{border-radius:var(--m-radius,.5rem);border:1px solid var(--m-line);background:var(--m-ink);width:100%;color:var(--m-text);padding:.5rem .7rem;font-size:.9rem}.m-input:focus{outline:2px solid var(--m-brand);outline-offset:1px}.m-error{color:#ef4444;margin-top:.25rem;font-size:.8rem}.m-prose{overflow-wrap:anywhere;line-height:1.6}.m-prose>*+*{margin-top:.75rem}.m-prose h1,.m-prose h2,.m-prose h3{font-family:var(--m-font-display,inherit);font-weight:700;line-height:1.25}.m-prose h1{font-size:1.5rem}.m-prose h2{font-size:1.25rem}.m-prose h3{font-size:1.1rem}.m-prose ul{padding-left:1.25rem;list-style:outside}.m-prose ol{padding-left:1.25rem;list-style:decimal}.m-prose blockquote{border-left:3px solid var(--m-line);color:var(--m-muted);padding-left:.75rem}.m-prose a{text-decoration:underline}.m-prose img{border-radius:.5rem;max-width:100%;height:auto}.m-prose code{font-family:ui-monospace,monospace;font-size:.9em}.m-help{color:var(--m-muted);margin-top:.25rem;font-size:.75rem}.m-badge{background:var(--m-panel-2);border:1px solid var(--m-line);border-radius:999px;padding:.1rem .55rem;font-size:.7rem;font-weight:600;display:inline-block}}@layer utilities{.pointer-events-none{pointer-events:none}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.inset-0{inset:0}.inset-x-0{inset-inline:0}.inset-y-0{inset-block:0}.top-0{top:0}.top-3{top:calc(var(--spacing) * 3)}.right-3{right:calc(var(--spacing) * 3)}.right-5{right:calc(var(--spacing) * 5)}.bottom-4{bottom:calc(var(--spacing) * 4)}.bottom-5{bottom:calc(var(--spacing) * 5)}.left-0{left:0}.left-1\/2{left:50%}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.col-span-2{grid-column:span 2/span 2}.float-right{float:right}.mx-auto{margin-inline:auto}.my-3{margin-block:calc(var(--spacing) * 3)}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mt-10{margin-top:calc(var(--spacing) * 10)}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-5{margin-bottom:calc(var(--spacing) * 5)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.mb-8{margin-bottom:calc(var(--spacing) * 8)}.-ml-1{margin-left:calc(var(--spacing) * -1)}.ml-1{margin-left:var(--spacing)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.aspect-square{aspect-ratio:1}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-2\.5{height:calc(var(--spacing) * 2.5)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-12{height:calc(var(--spacing) * 12)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-36{height:calc(var(--spacing) * 36)}.h-40{height:calc(var(--spacing) * 40)}.h-full{height:100%}.max-h-\[85vh\]{max-height:85vh}.min-h-40{min-height:calc(var(--spacing) * 40)}.min-h-screen{min-height:100vh}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2\.5{width:calc(var(--spacing) * 2.5)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-32{width:calc(var(--spacing) * 32)}.w-60{width:calc(var(--spacing) * 60)}.w-\[min\(24rem\,calc\(100vw-2rem\)\)\]{width:min(24rem,100vw - 2rem)}.w-auto{width:auto}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-5xl{max-width:var(--container-5xl)}.max-w-\[12rem\]{max-width:12rem}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:0}.min-w-3{min-width:calc(var(--spacing) * 3)}.min-w-\[10rem\]{min-width:10rem}.min-w-px{min-width:1px}.flex-1{flex:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-x-full{--tw-translate-x:-100%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-0{--tw-translate-x:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-scale-x-100{--tw-scale-x:calc(100% * -1);scale:var(--tw-scale-x) var(--tw-scale-y)}.cursor-crosshair{cursor:crosshair}.cursor-pointer{cursor:pointer}.resize{resize:both}.list-disc{list-style-type:disc}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-px{gap:1px}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-line>:not(:last-child)){border-color:var(--m-line)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-t{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.border{border-style:var(--tw-border-style);border-width:1px}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-4{border-left-style:var(--tw-border-style);border-left-width:4px}.border-brand{border-color:var(--m-brand)}.border-line{border-color:var(--m-line)}.border-white{border-color:var(--color-white)}.border-l-emerald-500{border-left-color:var(--color-emerald-500)}.border-l-red-500{border-left-color:var(--color-red-500)}.bg-black\/60{background-color:#0009}@supports (color:color-mix(in lab, red, red)){.bg-black\/60{background-color:color-mix(in oklab, var(--color-black) 60%, transparent)}}.bg-brand,.bg-brand\/15{background-color:var(--m-brand)}@supports (color:color-mix(in lab, red, red)){.bg-brand\/15{background-color:color-mix(in oklab, var(--m-brand) 15%, transparent)}}.bg-brand\/60{background-color:var(--m-brand)}@supports (color:color-mix(in lab, red, red)){.bg-brand\/60{background-color:color-mix(in oklab, var(--m-brand) 60%, transparent)}}.bg-line{background-color:var(--m-line)}.bg-panel{background-color:var(--m-panel)}.bg-panel-2{background-color:var(--m-panel-2)}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-7{padding:calc(var(--spacing) * 7)}.\!px-2{padding-inline:calc(var(--spacing) * 2)!important}.\!px-3{padding-inline:calc(var(--spacing) * 3)!important}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.\!py-1{padding-block:var(--spacing)!important}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-14{padding-top:calc(var(--spacing) * 14)}.pt-20{padding-top:calc(var(--spacing) * 20)}.pr-6{padding-right:calc(var(--spacing) * 6)}.pb-1{padding-bottom:var(--spacing)}.pb-16{padding-bottom:calc(var(--spacing) * 16)}.pl-5{padding-left:calc(var(--spacing) * 5)}.text-left{text-align:left}.font-display{font-family:var(--m-font-display,var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif))}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading:var(--leading-snug);line-height:var(--leading-snug)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-pre-line{white-space:pre-line}.whitespace-pre-wrap{white-space:pre-wrap}.text-brand{color:var(--m-brand)}.text-emerald-500{color:var(--color-emerald-500)}.text-muted{color:var(--m-muted)}.text-red-500{color:var(--color-red-500)}.text-text{color:var(--m-text)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.underline{text-decoration-line:underline}.opacity-50{opacity:.5}.opacity-75{opacity:.75}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){:is(:where(.group):hover .group-hover\:text-brand){color:var(--m-brand)}}.first\:border-0:first-child{border-style:var(--tw-border-style);border-width:0}.first\:pt-0:first-child{padding-top:0}@media (hover:hover){.hover\:border-brand:hover{border-color:var(--m-brand)}.hover\:bg-text\/5:hover{background-color:var(--m-text)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-text\/5:hover{background-color:color-mix(in oklab, var(--m-text) 5%, transparent)}}.hover\:bg-text\/10:hover{background-color:var(--m-text)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-text\/10:hover{background-color:color-mix(in oklab, var(--m-text) 10%, transparent)}}.hover\:text-text:hover{color:var(--m-text)}}@media (width>=40rem){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:w-64{width:calc(var(--spacing) * 64)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-\[1fr_1fr_auto\]{grid-template-columns:1fr 1fr auto}.sm\:items-end{align-items:flex-end}}@media (width>=48rem){.md\:top-1\/2{top:50%}.md\:bottom-auto{bottom:auto}.md\:ml-60{margin-left:calc(var(--spacing) * 60)}.md\:flex{display:flex}.md\:hidden{display:none}.md\:translate-x-0{--tw-translate-x:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.md\:-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:px-8{padding-inline:calc(var(--spacing) * 8)}.md\:pt-0{padding-top:0}.md\:pt-8{padding-top:calc(var(--spacing) * 8)}}@media (width>=64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}}}html,body{background:var(--m-ink);color:var(--m-text);font-family:var(--font-sans)}html.is-simple{font-size:112.5%}html.is-simple .m-btn{padding:.7rem 1.2rem;font-size:1rem}html.is-simple .m-input{padding:.7rem .9rem;font-size:1rem}html.is-simple .m-label{margin-bottom:.35rem;font-size:.95rem}html.is-simple .m-help{font-size:.85rem}html.is-simple main{line-height:1.6}.m-tile{flex-direction:column;gap:.5rem;padding:1.5rem;transition:border-color .15s,transform .15s;display:flex}.m-tile:hover{border-color:var(--m-brand);transform:translateY(-2px)}.m-spot{box-shadow:0 0 0 9999px #0009, 0 0 0 2px var(--m-brand)}@media (prefers-reduced-motion:no-preference){.m-bob{animation:2.6s ease-in-out infinite m-bob}@keyframes m-bob{0%,to{transform:translateY(0)}50%{transform:translateY(-4px)}}}.m-glow{background:radial-gradient(circle at 50% 55%, var(--m-brand), transparent 68%)}@supports (color:color-mix(in lab, red, red)){.m-glow{background:radial-gradient(circle at 50% 55%, color-mix(in srgb, var(--m-brand) 30%, transparent), transparent 68%)}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000} +/*$vite$:1*/ \ No newline at end of file diff --git a/resources/dist/manager.js b/resources/dist/manager.js new file mode 100644 index 0000000..ff4dfac --- /dev/null +++ b/resources/dist/manager.js @@ -0,0 +1,9 @@ +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)}`:``),ue=(e,t)=>!Object.is(e,t),de=(e,...t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},pe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},me=e=>{let t=y(e)?Number(e):NaN;return isNaN(t)?e:t},he,ge=()=>he||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},_e=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 ve(e){if(p(e)){let t={};for(let n=0;ne.startsWith(`/*`)?``:e).split(ye).forEach(e=>{if(e){let n=e.split(be);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function D(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;nje(e,t))}function Ne(e){return Object.getPrototypeOf(e)===null&&e[Symbol.toPrimitive]==null&&typeof e.toString!=`function`&&typeof e.valueOf!=`function`?C(e):String(e)}var Pe=e=>!!(e&&e.__v_isRef===!0),O=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===ee||!v(e.toString))?Pe(e)?O(e.value):JSON.stringify(e,Fe,2):String(e),Fe=(e,t)=>Pe(t)?Fe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Ie(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Ie(e))}:b(t)?Ie(t):x(t)&&!p(t)&&!w(t)?String(t):t,Ie=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Le(e){return e==null?`initial`:typeof e==`string`?e===``?` `:e:String(e)}var Re,ze=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&&Re&&(Re.active?(this.parent=Re,this.index=(Re.scopes||(Re.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let e,t;if(this.scopes){let n=this.scopes.slice();for(e=0,t=n.length;e0&&--this._on===0){if(Re===this)Re=this.prevScope;else{let e=Re;for(;e;){if(e.prevScope===this){e.prevScope=this.prevScope;break}e=e.prevScope}}this.prevScope=void 0}}stop(e){if(this._active){this._active=!1;let t,n;for(t=0,n=this.effects.length;t0)return;if(qe){let e=qe;for(qe=void 0;e;){let t=e.next;e.next=void 0,e.flags&=-9,e=t}}let e;for(;Ke;){let t=Ke;for(Ke=void 0;t;){let n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(t){e||=t}t=n}}if(e)throw e}function Ze(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Qe(e){let t,n=e.depsTail,r=n;for(;r;){let e=r.prevDep;r.version===-1?(r===n&&(n=e),tt(r),nt(r)):t=r,r.dep.activeLink=r.prevActiveLink,r.prevActiveLink=void 0,r=e}e.deps=t,e.depsTail=n}function $e(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(et(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function et(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===ut)||(e.globalVersion=ut,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!$e(e))))return;e.flags|=2;let t=e.dep,n=k,r=at;k=e,at=!0;try{Ze(e);let n=e.fn(e._value);(t.version===0||ue(n,e._value))&&(e.flags|=128,e._value=n,t.version++)}catch(e){throw t.version++,e}finally{k=n,at=r,Qe(e),e.flags&=-3}}function tt(e,t=!1){let{dep:n,prevSub:r,nextSub:i}=e;if(r&&(r.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=r,e.nextSub=void 0),n.subs===e&&(n.subs=r,!r&&n.computed)){n.computed.flags&=-5;for(let e=n.computed.deps;e;e=e.nextDep)tt(e,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function nt(e){let{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}function rt(e,t){e.effect instanceof We&&(e=e.effect.fn);let n=new We(e);t&&l(n,t);try{n.run()}catch(e){throw n.stop(),e}let r=n.run.bind(n);return r.effect=n,r}function it(e){e.effect.stop()}var at=!0,ot=[];function st(){ot.push(at),at=!1}function ct(){let e=ot.pop();at=e===void 0||e}function lt(e){let{cleanup:t}=e;if(e.cleanup=void 0,t){let e=k;k=void 0;try{t()}finally{k=e}}}var ut=0,dt=class{constructor(e,t){this.sub=e,this.dep=t,this.version=t.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}},ft=class{constructor(e){this.computed=e,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(e){if(!k||!at||k===this.computed)return;let t=this.activeLink;if(t===void 0||t.sub!==k)t=this.activeLink=new dt(k,this),k.deps?(t.prevDep=k.depsTail,k.depsTail.nextDep=t,k.depsTail=t):k.deps=k.depsTail=t,pt(t);else if(t.version===-1&&(t.version=this.version,t.nextDep)){let e=t.nextDep;e.prevDep=t.prevDep,t.prevDep&&(t.prevDep.nextDep=e),t.prevDep=k.depsTail,t.nextDep=void 0,k.depsTail.nextDep=t,k.depsTail=t,k.deps===t&&(k.deps=e)}return t}trigger(e){this.version++,ut++,this.notify(e)}notify(e){Ye();try{for(let e=this.subs;e;e=e.prevSub)e.sub.notify()&&e.sub.dep.notify()}finally{Xe()}}};function pt(e){if(e.dep.sc++,e.sub.flags&4){let t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let e=t.deps;e;e=e.nextDep)pt(e)}let n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}var mt=new WeakMap,ht=Symbol(``),gt=Symbol(``),_t=Symbol(``);function vt(e,t,n){if(at&&k){let t=mt.get(e);t||mt.set(e,t=new Map);let r=t.get(n);r||(t.set(n,r=new ft),r.map=t,r.key=n),r.track()}}function yt(e,t,n,r,i,a){let o=mt.get(e);if(!o){ut++;return}let s=e=>{e&&e.trigger()};if(Ye(),t===`clear`)o.forEach(s);else{let i=p(e),a=i&&T(n);if(i&&n===`length`){let e=Number(r);o.forEach((t,n)=>{(n===`length`||n===_t||!b(n)&&n>=e)&&s(t)})}else switch((n!==void 0||o.has(void 0))&&s(o.get(n)),a&&s(o.get(_t)),t){case`add`:i?a&&s(o.get(`length`)):(s(o.get(ht)),m(e)&&s(o.get(gt)));break;case`delete`:i||(s(o.get(ht)),m(e)&&s(o.get(gt)));break;case`set`:m(e)&&s(o.get(ht))}}Xe()}function bt(e,t){let n=mt.get(e);return n&&n.get(t)}function xt(e){let t=A(e);return t===e||(vt(t,`iterate`,_t),fn(e))?t:dn(e)?un(e)?t.map(e=>gn(hn(e))):t.map(gn):t.map(hn)}function St(e){return vt(e=A(e),`iterate`,_t),e}var Ct=e=>gn(hn(e));function wt(e){return dn(e)?un(e)?Ct:gn:hn}var Tt={__proto__:null,[Symbol.iterator](){return Et(this,Symbol.iterator,wt(this))},concat(...e){return xt(this).concat(...e.map(e=>p(e)?xt(e):e))},entries(){let e=wt(this);return Et(this,`entries`,t=>(t[1]=e(t[1]),t))},every(e,t){return kt(this,`every`,e,t,void 0,arguments)},filter(e,t){return kt(this,`filter`,e,t,e=>e.map(wt(this)),arguments)},find(e,t){return kt(this,`find`,e,t,e=>wt(this)(e),arguments)},findIndex(e,t){return kt(this,`findIndex`,e,t,void 0,arguments)},findLast(e,t){return kt(this,`findLast`,e,t,e=>wt(this)(e),arguments)},findLastIndex(e,t){return kt(this,`findLastIndex`,e,t,void 0,arguments)},forEach(e,t){return kt(this,`forEach`,e,t,void 0,arguments)},includes(...e){return jt(this,`includes`,e)},indexOf(...e){return jt(this,`indexOf`,e)},join(e){return xt(this).join(e)},lastIndexOf(...e){return jt(this,`lastIndexOf`,e)},map(e,t){return kt(this,`map`,e,t,void 0,arguments)},pop(){return Mt(this,`pop`)},push(...e){return Mt(this,`push`,e)},reduce(e,...t){return At(this,`reduce`,e,t)},reduceRight(e,...t){return At(this,`reduceRight`,e,t)},shift(){return Mt(this,`shift`)},some(e,t){return kt(this,`some`,e,t,void 0,arguments)},splice(...e){return Mt(this,`splice`,e)},toReversed(){return xt(this).toReversed()},toSorted(e){return xt(this).toSorted(e)},toSpliced(...e){return xt(this).toSpliced(...e)},unshift(...e){return Mt(this,`unshift`,e)},values(){return Et(this,`values`,wt(this))}};function Et(e,t,n){let r=St(e),i=r[t],a=i.call(r);if(r!==e&&!fn(e)){if(a[Symbol.toStringTag]===`Array Iterator`){let e=Object.create(Object.getPrototypeOf(a));return e.next=()=>Dt(a.next(),n),i!==Ot[t]&&Object.defineProperties(e,{return:{get(){let e=a.return;return typeof e==`function`?e.bind(a):e}},throw:{get(){let e=a.throw;return typeof e==`function`?e.bind(a):e}}}),e}a._next=a.next,a.next=()=>Dt(a._next(),n)}return a}function Dt(e,t){return e.done||(e.value=t(e.value)),e}var Ot=Array.prototype;function kt(e,t,n,r,i,a){let o=St(e),s=o!==e&&!fn(e),c=o[t];if(c!==Ot[t]){let t=c.apply(e,a);return s?hn(t):t}let l=n;if(o!==e){if(s){let t=wt(e);l=function(r,i){return n.call(this,t(r),i,e)}}else n.length>2&&(l=function(t,r){return n.call(this,t,r,e)})}let u=c.call(o,l,r);return s&&i?i(u):u}function At(e,t,n,r){let i=St(e),a=i!==e&&!fn(e),o=n,s=!1;if(i!==e){if(a){let t=wt(e);s=r.length===0,o=function(r,i,a){return s&&(s=!1,r=t(r)),n.call(this,r,t(i),a,e)}}else n.length>3&&(o=function(t,r,i){return n.call(this,t,r,i,e)})}let c=i[t](o,...r);return s?wt(e)(c):c}function jt(e,t,n){let r=A(e);vt(r,`iterate`,_t);let i=r[t](...n);return(i===-1||i===!1)&&pn(n[0])?(n[0]=A(n[0]),r[t](...n)):i}function Mt(e,t,n=[]){st(),Ye();let r=A(e)[t].apply(e,n);return Xe(),ct(),r}var Nt=n(`__proto__,__v_isRef,__isVue`),Pt=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!==`arguments`&&e!==`caller`).map(e=>Symbol[e]).filter(b));function Ft(e){b(e)||(e=String(e));let t=A(this);return vt(t,`has`,e),t.hasOwnProperty(e)}var It=class{constructor(e=!1,t=!1){this._isReadonly=e,this._isShallow=t}get(e,t,n){if(t===`__v_skip`)return e.__v_skip;let r=this._isReadonly,i=this._isShallow;if(t===`__v_isReactive`)return!r;if(t===`__v_isReadonly`)return r;if(t===`__v_isShallow`)return i;if(t===`__v_raw`)return n===(r?i?nn:tn:i?en:$t).get(e)||Object.getPrototypeOf(e)===Object.getPrototypeOf(n)?e:void 0;let a=p(e);if(!r){let e;if(a&&(e=Tt[t]))return e;if(t===`hasOwnProperty`)return Ft}let o=Reflect.get(e,t,j(e)?e:n);if((b(t)?Pt.has(t):Nt(t))||(r||vt(e,`get`,t),i))return o;if(j(o)){let e=a&&T(t)?o:o.value;return r&&x(e)?sn(e):e}return x(o)?r?sn(o):an(o):o}},Lt=class extends It{constructor(e=!1){super(!1,e)}set(e,t,n,r){let i=e[t],a=p(e)&&T(t);if(!this._isShallow){let e=dn(i);if(!fn(n)&&!dn(n)&&(i=A(i),n=A(n)),!a&&j(i)&&!j(n))return e||(i.value=n),!0}let o=a?Number(t)e,Wt=e=>Reflect.getPrototypeOf(e);function Gt(e,t,n){return function(...r){let i=this.__v_raw,a=A(i),o=m(a),s=e===`entries`||e===Symbol.iterator&&o,c=e===`keys`&&o,u=i[e](...r),d=n?Ut:t?gn:hn;return!t&&vt(a,`iterate`,c?gt:ht),l(Object.create(u),{next(){let{value:e,done:t}=u.next();return t?{value:e,done:t}:{value:s?[d(e[0]),d(e[1])]:d(e),done:t}}})}}function Kt(e){return function(...t){return e===`delete`?!1:e===`clear`?void 0:this}}function qt(e,t){let n={get(n){let r=this.__v_raw,i=A(r),a=A(n);e||(ue(n,a)&&vt(i,`get`,n),vt(i,`get`,a));let{has:o}=Wt(i),s=t?Ut:e?gn:hn;if(o.call(i,n))return s(r.get(n));if(o.call(i,a))return s(r.get(a));r!==i&&r.get(n)},get size(){let t=this.__v_raw;return!e&&vt(A(t),`iterate`,ht),t.size},has(t){let n=this.__v_raw,r=A(n),i=A(t);return e||(ue(t,i)&&vt(r,`has`,t),vt(r,`has`,i)),t===i?n.has(t):n.has(t)||n.has(i)},forEach(n,r){let i=this,a=i.__v_raw,o=A(a),s=t?Ut:e?gn:hn;return!e&&vt(o,`iterate`,ht),a.forEach((e,t)=>n.call(r,s(e),s(t),i))}};return l(n,e?{add:Kt(`add`),set:Kt(`set`),delete:Kt(`delete`),clear:Kt(`clear`)}:{add(e){let n=A(this),r=Wt(n),i=A(e),a=!t&&!fn(e)&&!dn(e)?i:e;return r.has.call(n,a)||ue(e,a)&&r.has.call(n,e)||ue(i,a)&&r.has.call(n,i)||(n.add(a),yt(n,`add`,a,a)),this},set(e,n){t||fn(n)||dn(n)||(n=A(n));let r=A(this),{has:i,get:a}=Wt(r),o=i.call(r,e);o||=(e=A(e),i.call(r,e));let s=a.call(r,e);return r.set(e,n),o?ue(n,s)&&yt(r,`set`,e,n,s):yt(r,`add`,e,n),this},delete(e){let t=A(this),{has:n,get:r}=Wt(t),i=n.call(t,e);i||=(e=A(e),n.call(t,e));let a=r?r.call(t,e):void 0,o=t.delete(e);return i&&yt(t,`delete`,e,void 0,a),o},clear(){let e=A(this),t=e.size!==0,n=e.clear();return t&&yt(e,`clear`,void 0,void 0,void 0),n}}),[`keys`,`values`,`entries`,Symbol.iterator].forEach(r=>{n[r]=Gt(r,e,t)}),n}function Jt(e,t){let n=qt(e,t);return(r,i,a)=>i===`__v_isReactive`?!e:i===`__v_isReadonly`?e:i===`__v_isShallow`?t:i===`__v_raw`?r:Reflect.get(f(n,i)&&i in r?n:r,i,a)}var Yt={get:Jt(!1,!1)},Xt={get:Jt(!1,!0)},Zt={get:Jt(!0,!1)},Qt={get:Jt(!0,!0)},$t=new WeakMap,en=new WeakMap,tn=new WeakMap,nn=new WeakMap;function rn(e){switch(e){case`Object`:case`Array`:return 1;case`Map`:case`Set`:case`WeakMap`:case`WeakSet`:return 2;default:return 0}}function an(e){return dn(e)?e:ln(e,!1,zt,Yt,$t)}function on(e){return ln(e,!1,Vt,Xt,en)}function sn(e){return ln(e,!0,Bt,Zt,tn)}function cn(e){return ln(e,!0,Ht,Qt,nn)}function ln(e,t,n,r,i){if(!x(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;let a=i.get(e);if(a)return a;let o=rn(te(e));if(o===0)return e;let s=new Proxy(e,o===2?r:n);return i.set(e,s),s}function un(e){return dn(e)?un(e.__v_raw):!!(e&&e.__v_isReactive)}function dn(e){return!!(e&&e.__v_isReadonly)}function fn(e){return!!(e&&e.__v_isShallow)}function pn(e){return e?!!e.__v_raw:!1}function A(e){let t=e&&e.__v_raw;return t?A(t):e}function mn(e){return!f(e,`__v_skip`)&&Object.isExtensible(e)&&fe(e,`__v_skip`,!0),e}var hn=e=>x(e)?an(e):e,gn=e=>x(e)?sn(e):e;function j(e){return e?e.__v_isRef===!0:!1}function M(e){return vn(e,!1)}function _n(e){return vn(e,!0)}function vn(e,t){return j(e)?e:new yn(e,t)}var yn=class{constructor(e,t){this.dep=new ft,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=t?e:A(e),this._value=t?e:hn(e),this.__v_isShallow=t}get value(){return this.dep.track(),this._value}set value(e){let t=this._rawValue,n=this.__v_isShallow||fn(e)||dn(e);e=n?e:A(e),ue(e,t)&&(this._rawValue=e,this._value=n?e:hn(e),this.dep.trigger())}};function bn(e){e.dep&&e.dep.trigger()}function N(e){return j(e)?e.value:e}function xn(e){return v(e)?e():N(e)}var Sn={get:(e,t,n)=>t===`__v_raw`?e:N(Reflect.get(e,t,n)),set:(e,t,n,r)=>{let i=e[t];return j(i)&&!j(n)?(i.value=n,!0):Reflect.set(e,t,n,r)}};function Cn(e){return un(e)?e:new Proxy(e,Sn)}var wn=class{constructor(e){this.__v_isRef=!0,this._value=void 0;let t=this.dep=new ft,{get:n,set:r}=e(t.track.bind(t),t.trigger.bind(t));this._get=n,this._set=r}get value(){return this._value=this._get()}set value(e){this._set(e)}};function Tn(e){return new wn(e)}function En(e){let t=p(e)?Array(e.length):{};for(let n in e)t[n]=An(e,n);return t}var Dn=class{constructor(e,t,n){this._object=e,this._defaultValue=n,this.__v_isRef=!0,this._value=void 0,this._key=b(t)?t:String(t),this._raw=A(e);let r=!0,i=e;if(!p(e)||b(this._key)||!T(this._key))do r=!pn(i)||fn(i);while(r&&(i=i.__v_raw));this._shallow=r}get value(){let e=this._object[this._key];return this._shallow&&(e=N(e)),this._value=e===void 0?this._defaultValue:e}set value(e){if(this._shallow&&j(this._raw[this._key])){let t=this._object[this._key];if(j(t)){t.value=e;return}}this._object[this._key]=e}get dep(){return bt(this._raw,this._key)}},On=class{constructor(e){this._getter=e,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}};function kn(e,t,n){return j(e)?e:v(e)?new On(e):x(e)&&arguments.length>1?An(e,t,n):M(e)}function An(e,t,n){return new Dn(e,t,n)}var jn=class{constructor(e,t,n){this.fn=e,this.setter=t,this._value=void 0,this.dep=new ft(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=ut-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!t,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&k!==this)return Je(this,!0),!0}get value(){let e=this.dep.track();return et(this),e&&(e.version=this.dep.version),this._value}set value(e){this.setter&&this.setter(e)}};function Mn(e,t,n=!1){let r,i;return v(e)?r=e:(r=e.get,i=e.set),new jn(r,i,n)}var Nn={GET:`get`,HAS:`has`,ITERATE:`iterate`},Pn={SET:`set`,ADD:`add`,DELETE:`delete`,CLEAR:`clear`},Fn={},In=new WeakMap,Ln=void 0;function Rn(){return Ln}function zn(e,t=!1,n=Ln){if(n){let t=In.get(n);t||In.set(n,t=[]),t.push(e)}}function Bn(e,t,n=r){let{immediate:i,deep:o,once:s,scheduler:c,augmentJob:l,call:d,onStop:f}=n,m=e=>o?e:fn(e)||o===!1||o===0?Vn(e,1):Vn(e),h,g,_,y,b=!1,x=!1;if(j(e)?(g=()=>e.value,b=fn(e)):un(e)?(g=()=>m(e),b=!0):p(e)?(x=!0,b=e.some(e=>un(e)||fn(e)),g=()=>e.map(e=>{if(j(e))return e.value;if(un(e))return m(e);if(v(e))return d?d(e,2):e()})):g=v(e)?t?d?()=>d(e,2):e:()=>{if(_){st();try{_()}finally{ct()}}let t=Ln;Ln=h;try{return d?d(e,3,[y]):e(y)}finally{Ln=t}}:a,t&&o){let e=g,t=o===!0?1/0:o;g=()=>Vn(e(),x?t+1:t)}let S=Ve(),ee=()=>{h.stop(),S&&S.active&&u(S.effects,h)},C=!1;if(s&&t){let e=t;t=(...t)=>{C=!0;try{return e(...t)}finally{ee()}}}let te=x?Array(e.length).fill(Fn):Fn,w=e=>{if(!C&&h.flags&1&&(h.dirty||e)){if(t){let n=h.run();if(e||o||b||(x?n.some((e,t)=>ue(e,te[t])):ue(n,te))){let e=Ln;st();try{_&&_(),Ln=h;let e=[n,te===Fn?void 0:x&&te[0]===Fn?[]:te,y];te=n,d?d(t,3,e):t(...e)}finally{Ln=e,ct()}}}else h.run()}};return l&&l(w),h=new We(g),h.scheduler=c?()=>c(w,!1):w,y=e=>zn(e,!1,h),_=h.onStop=()=>{let e=In.get(h);if(e){if(d)d(e,4);else for(let t of e)t();In.delete(h)}},f&&(h.onStop=()=>{_(),f()}),t?i?w(!0):te=h.run():c?c(w.bind(null,!0),!0):h.run(),ee.pause=h.pause.bind(h),ee.resume=h.resume.bind(h),ee.stop=ee,ee}function Vn(e,t=1/0,n){if(t<=0||!x(e)||e.__v_skip||(n||=new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,j(e))Vn(e.value,t,n);else if(p(e)){if(un(e)&&!dn(e)&&!fn(e)){let r=A(e);vt(r,`iterate`,_t);for(let e=0;e{Vn(e,t,n)});else if(w(e)){for(let r in e)Vn(e[r],t,n);let r=A(e);for(let i of Object.getOwnPropertySymbols(r))Object.prototype.propertyIsEnumerable.call(r,i)&&Vn(e[i],t,n)}return e}var Hn=[];function Un(e){Hn.push(e)}function Wn(){Hn.pop()}function Gn(e,t){}var Kn={SETUP_FUNCTION:0,0:`SETUP_FUNCTION`,RENDER_FUNCTION:1,1:`RENDER_FUNCTION`,NATIVE_EVENT_HANDLER:5,5:`NATIVE_EVENT_HANDLER`,COMPONENT_EVENT_HANDLER:6,6:`COMPONENT_EVENT_HANDLER`,VNODE_HOOK:7,7:`VNODE_HOOK`,DIRECTIVE_HOOK:8,8:`DIRECTIVE_HOOK`,TRANSITION_HOOK:9,9:`TRANSITION_HOOK`,APP_ERROR_HANDLER:10,10:`APP_ERROR_HANDLER`,APP_WARN_HANDLER:11,11:`APP_WARN_HANDLER`,FUNCTION_REF:12,12:`FUNCTION_REF`,ASYNC_COMPONENT_LOADER:13,13:`ASYNC_COMPONENT_LOADER`,SCHEDULER:14,14:`SCHEDULER`,COMPONENT_UPDATE:15,15:`COMPONENT_UPDATE`,APP_UNMOUNT_CLEANUP:16,16:`APP_UNMOUNT_CLEANUP`},qn={sp:`serverPrefetch hook`,bc:`beforeCreate hook`,c:`created hook`,bm:`beforeMount hook`,m:`mounted hook`,bu:`beforeUpdate hook`,u:`updated`,bum:`beforeUnmount hook`,um:`unmounted hook`,a:`activated hook`,da:`deactivated hook`,ec:`errorCaptured hook`,rtc:`renderTracked hook`,rtg:`renderTriggered hook`,0:`setup function`,1:`render function`,2:`watcher getter`,3:`watcher callback`,4:`watcher cleanup function`,5:`native event handler`,6:`component event handler`,7:`vnode hook`,8:`directive hook`,9:`transition hook`,10:`app errorHandler`,11:`app warnHandler`,12:`ref function`,13:`async component loader`,14:`scheduler flush`,15:`component update`,16:`app unmount cleanup function`};function Jn(e,t,n,r){try{return r?e(...r):e()}catch(e){Xn(e,t,n)}}function Yn(e,t,n,r){if(v(e)){let i=Jn(e,t,n,r);return i&&S(i)&&i.catch(e=>{Xn(e,t,n,void 0,!0)}),i}if(p(e)){let i=[];for(let a=0;a>>1,i=Qn[r],a=mr(i);a=mr(n)?Qn.push(e):Qn.splice(or(t),0,e),e.flags|=1,cr()}}function cr(){ir||=rr.then(hr)}function lr(e){if(!p(e))tr&&e.id===-1?tr.splice(nr+1,0,e):e.flags&1||(er.push(e),e.flags|=1);else for(let t=0;t=t))continue;Qn.splice(r,1),r=e?r-1:$n,n.flags&4&&(n.flags&=-2),n(),n.flags&4||(n.flags&=-2)}}}function dr(e,t,n=0){if(er.length){let e=er,r=0;if(t){e=[];for(let i=0;imr(e)-mr(t));if(er.length=r,tr){for(let e=0;ee.id==null?e.flags&2?-1:1/0:e.id;function hr(e){try{for($n=0;$ngr.emit(e,...t)),_r=[]):typeof window<`u`&&window.HTMLElement&&!(window.navigator?.userAgent)?.includes(`jsdom`)?((t.__VUE_DEVTOOLS_HOOK_REPLAY__=t.__VUE_DEVTOOLS_HOOK_REPLAY__||[]).push(e=>{vr(e,t)}),setTimeout(()=>{gr||(t.__VUE_DEVTOOLS_HOOK_REPLAY__=null,_r=[])},3e3)):_r=[]}var yr=null,br=null;function xr(e){let t=yr;return yr=e,br=e&&e.type.__scopeId||null,t}function Sr(e){br=e}function Cr(){br=null}var wr=e=>P;function P(e,t=yr,n){if(!t||e._n)return e;let r=(...n)=>{r._d&&Ts(-1);let i=xr(t),a=xs.length,o;try{o=e(...n)}finally{for(let e=xs.length;e>a;e--)Cs();xr(i),r._d&&Ts(1)}return o};return r._n=!0,r._c=!0,r._d=!0,r}function F(e,t){if(yr===null)return e;let n=uc(yr),i=e.dirs||=[];for(let e=0;e1)return n&&v(t)?t.call(r&&r.proxy):t}}function Or(){return!!(Ks()||uo)}var kr=Symbol.for(`v-scx`),Ar=()=>Dr(kr);function jr(e,t){return Fr(e,null,t)}function Mr(e,t){return Fr(e,null,{flush:`post`})}function Nr(e,t){return Fr(e,null,{flush:`sync`})}function Pr(e,t,n){return Fr(e,t,n)}function Fr(e,t,n=r){let{immediate:i,deep:o,flush:s,once:c}=n,u=l({},n),d=t&&i||!t&&s!==`post`,f;if(Qs){if(s===`sync`){let e=Ar();f=e.__watcherHandles||=[]}else if(!d){let e=()=>{};return e.stop=a,e.resume=a,e.pause=a,e}}let p=Gs,m;if(p&&Ve()!==p.scope){if(p.scope.active){let e=p.scope.run(()=>new ze);e.run(()=>He(()=>Promise.resolve().then(()=>{p=null,m&&(m.i=null)}))),u.onStop=()=>e.stop()}else p=null}u.call=(e,t,n)=>Yn(e,p,t,n);let h=!1;s===`post`?u.scheduler=e=>{e.i=p,Wo(e,p&&p.suspense)}:s!==`sync`&&(h=!0,u.scheduler=(e,t)=>{t?e():sr(e)}),u.augmentJob=e=>{m=e,t&&(e.flags|=4),h&&(e.flags|=2,p&&(e.id=p.uid,e.i=p))};let g=Bn(e,t,u);return Qs&&(f?f.push(g):d&&g()),g}function Ir(e,t,n){let r=this.proxy,i=y(e)?e.includes(`.`)?Lr(r,e):()=>r[e]:e.bind(r,r),a;v(t)?a=t:(a=t.handler,n=t);let o=Ys(this),s=Fr(i,a.bind(r),n);return o(),s}function Lr(e,t){let n=t.split(`.`);return()=>{let t=e;for(let e=0;ee.__isTeleport,Vr=e=>e&&(e.disabled||e.disabled===``),Hr=e=>e&&(e.defer||e.defer===``),Ur=e=>typeof SVGElement<`u`&&e instanceof SVGElement,Wr=e=>typeof MathMLElement==`function`&&e instanceof MathMLElement,Gr=(e,t)=>{let n=e&&e.to;return y(n)?t?t(n):null:n},Kr={name:`Teleport`,__isTeleport:!0,process(e,t,n,r,i,a,o,s,c,l){let{mc:u,pc:d,pbc:f,o:{insert:p,querySelector:m,createText:h,createComment:g,parentNode:_}}=l,v=Vr(t.props),{dynamicChildren:y}=t,b=(e,t,n)=>{e.shapeFlag&16&&u(e.children,t,n,i,a,o,s,c)},x=(e=t)=>{let n=Vr(e.props),r=e.target=Gr(e.props,m),a=Zr(r,e,h,p);r&&(o!==`svg`&&Ur(r)?o=`svg`:o!==`mathml`&&Wr(r)&&(o=`mathml`),i&&i.isCE&&(i.ce._teleportTargets||(i.ce._teleportTargets=new Set)).add(r),n||(b(e,r,a),Xr(e,!1)))},S=e=>{let t=()=>{if(Rr.get(e)===t){if(Rr.delete(e),Vr(e.props)){let t=_(e.el)||n;b(e,t,e.anchor),Xr(e,!0)}x(e)}};Rr.set(e,t),Wo(t,a)};if(e==null){let e=t.el=h(``),i=t.anchor=h(``);if(p(e,n,r),p(i,n,r),Hr(t.props)||a&&a.pendingBranch){S(t);return}v&&(b(t,n,i),Xr(t,!0)),x()}else{t.el=e.el;let r=t.anchor=e.anchor,u=Rr.get(e);if(u){u.flags|=8,Rr.delete(e),S(t);return}t.targetStart=e.targetStart;let p=t.target=e.target,h=t.targetAnchor=e.targetAnchor,g=Vr(e.props),_=g?n:p,b=g?r:h;if(o===`svg`||Ur(p)?o=`svg`:(o===`mathml`||Wr(p))&&(o=`mathml`),y?(f(e.dynamicChildren,y,_,i,a,o,s),Zo(e,t,!0)):c||d(e,t,_,b,i,a,o,s,!1),v)g?t.props&&e.props&&t.props.to!==e.props.to&&(t.props.to=e.props.to):qr(t,n,r,l,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){let e=Gr(t.props,m);e&&(t.target=e,qr(t,e,null,l,0))}else g&&qr(t,p,h,l,1);Xr(t,v)}},remove(e,t,n,{um:r,o:{remove:i}},a){let{shapeFlag:o,children:s,anchor:c,targetStart:l,targetAnchor:u,target:d,props:f}=e,p=Vr(f),m=a||!p,h=Rr.get(e);if(h&&(h.flags|=8,Rr.delete(e)),d&&(i(l),i(u)),a&&i(c),!h&&(p||d)&&o&16)for(let e=0;e{e.isMounted=!0}),ca(()=>{e.isUnmounting=!0}),e}var ti=[Function,Array],ni={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:ti,onEnter:ti,onAfterEnter:ti,onEnterCancelled:ti,onBeforeLeave:ti,onLeave:ti,onAfterLeave:ti,onLeaveCancelled:ti,onBeforeAppear:ti,onAppear:ti,onAfterAppear:ti,onAppearCancelled:ti},ri={name:`BaseTransition`,props:ni,setup(e,{slots:t}){let n=Ks(),r=ei();return()=>{let i=t.default&&di(t.default(),!0),a=i&&i.length?ii(i):n.subTree?K():void 0;if(!a)return;let o=A(e),{mode:s}=o;if(r.isLeaving)return ci(a);let c=li(a);if(!c)return ci(a);let l=si(c,o,r,n);c.type!==z&&ui(c,l);let u=n.subTree&&li(n.subTree);if(u&&u.type!==z&&!Os(u,c)&&fi(n.subTree)){let e=si(u,o,r,n);if(ui(u,e),s===`out-in`&&c.type!==z)return r.isLeaving=!0,e.afterLeave=()=>{if(r.isLeaving=!1,!(n.job.flags&8)){if(n.effect.flags&2){let e=()=>{n.job.flags&8||n.update()};e.i=n,sr(e)}else n.update()}delete e.afterLeave,u=void 0},ci(a);s===`in-out`&&c.type!==z?e.delayLeave=(t,n,i)=>{let a=oi(r,u);a[String(u.key)]=u,t[Qr]=()=>{n(),t[Qr]=void 0,delete l.delayedLeave,delete e.delayLeave,u=void 0},l.delayedLeave=()=>{i(),delete l.delayedLeave,delete e.delayLeave,u=void 0}}:u=void 0}else u&&=void 0;return a}}};function ii(e){let t=e[0];if(e.length>1){for(let n of e)if(n.type!==z){t=n;break}}return t}var ai=ri;function oi(e,t){let{leavingVNodes:n}=e,r=n.get(t.type);return r||(r=Object.create(null),n.set(t.type,r)),r}function si(e,t,n,r){let{appear:i,mode:a,persisted:o=!1,onBeforeEnter:s,onEnter:c,onAfterEnter:l,onEnterCancelled:u,onBeforeLeave:d,onLeave:f,onAfterLeave:m,onLeaveCancelled:h,onBeforeAppear:g,onAppear:_,onAfterAppear:v,onAppearCancelled:y}=t,b=String(e.key),x=oi(n,e),S=(e,t)=>{e&&Yn(e,r,9,t)},ee=(e,t)=>{let n=t[1];S(e,t),p(e)?e.every(e=>e.length<=1)&&n():e.length<=1&&n()},C={mode:a,persisted:o,beforeEnter(t){let r=s;if(!n.isMounted){if(i)r=g||s;else return}t[Qr]&&t[Qr](!0);let a=x[b];if(a&&Os(e,a)){let e=a.el[Qr];if(!e){let t=fi(a);e=t&&t.el[Qr]}e&&e()}S(r,[t])},enter(e){if(e[Qr]){C.delayedLeave&&C.delayedLeave();return}let t=c,r=l,a=u;if(!n.isMounted){if(i)t=_||c,r=v||l,a=y||u;else return}let o=!1;e[$r]=t=>{o||(o=!0,S(t?a:r,[e]),C.delayedLeave&&C.delayedLeave(),e[$r]=void 0)};let s=e[$r].bind(null,!1);t?ee(t,[e,s]):s()},leave(t,r){let i=String(e.key);if(t[$r]&&t[$r](!0),n.isUnmounting)return r();S(d,[t]);let a=!1;t[Qr]=n=>{a||(a=!0,r(),S(n?h:m,[t]),t[Qr]=void 0,x[i]===e&&delete x[i])};let o=t[Qr].bind(null,!1);x[i]=e,f?ee(f,[t,o]):o()},clone(e){let i=si(e,t,n,r);return i.afterLeave=()=>{C.afterLeave&&C.afterLeave()},i.delayLeave=(e,t,n)=>{C.delayLeave?C.delayLeave(e,t,n):n()},i.delayedLeave=()=>{C.delayedLeave&&C.delayedLeave()},i}};return C}function ci(e){if(qi(e))return e=Ps(e),e.children=null,e}function li(e){if(!qi(e))return Br(e.type)&&e.children?ii(e.children):e;if(e.component)return e.component.subTree;let{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&v(n.default))return n.default()}}function ui(e,t){if(e.shapeFlag&6&&e.component){e.transition=t;let n=e.component.subTree;ui(Br(n.type)&&li(n)||n,t)}else if(e.shapeFlag&128){let n=e.suspense;if(n){let e=n.isHydrating?n.pendingBranch:n.activeBranch;e&&ui(e,t.clone(e))}else e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)}else if(e.transition=t,e.type===R&&p(e.children)){let n=yo(e.children,!1);n&&ui(n,t)}}function di(e,t=!1,n){let r=[],i=0;for(let a=0;a1)for(let e=0;en.value,set:e=>n.value=e})}return n}function gi(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}var _i=new WeakMap;function vi(e,t,n,i,a=!1){if(p(e)){e.forEach((e,r)=>vi(e,t&&(p(t)?t[r]:t),n,i,a));return}if(Wi(i)&&!a){i.shapeFlag&512&&i.type.__asyncResolved&&i.component.subTree.component&&vi(e,t,n,i.component.subTree);return}let s=i.shapeFlag&4?uc(i.component):i.el,c=a?null:s,{i:l,r:d}=e,m=t&&t.r,h=l.refs===r?l.refs={}:l.refs,g=l.setupState,_=A(g),b=g===r?o:e=>!gi(h,e)&&f(_,e),x=(e,t)=>!(t&&gi(h,t));if(m!=null&&m!==d){if(yi(t),y(m))h[m]=null,b(m)&&(g[m]=null);else if(j(m)){let e=t;x(m,e.k)&&(m.value=null),e.k&&(h[e.k]=null)}}if(v(d))Jn(d,l,12,[c,h]);else{let t=y(d),r=j(d);if(t||r){let i=()=>{if(e.f){let n=t?b(d)?g[d]:h[d]:x(d)||!e.k?d.value:h[e.k];if(a)p(n)&&u(n,s);else if(p(n))n.includes(s)||n.push(s);else if(t)h[d]=[s],b(d)&&(g[d]=h[d]);else{let t=[s];x(d,e.k)&&(d.value=t),e.k&&(h[e.k]=t)}}else t?(h[d]=c,b(d)&&(g[d]=c)):r&&(x(d,e.k)&&(d.value=c),e.k&&(h[e.k]=c))};if(c){let t=()=>{i(),_i.delete(e)};t.id=-1,_i.set(e,t),Wo(t,n)}else yi(e),i()}}}function yi(e){let t=_i.get(e);t&&(t.flags|=8,_i.delete(e))}var bi=!1,xi=()=>{bi||=(console.error(`Hydration completed but contains mismatches.`),!0)},Si=e=>e.namespaceURI.includes(`svg`)&&e.tagName!==`foreignObject`,Ci=e=>e.namespaceURI.includes(`MathML`),wi=e=>{if(e.nodeType===1){if(Si(e))return`svg`;if(Ci(e))return`mathml`}},Ti=e=>e.nodeType===8;function Ei(e){let{mt:t,p:n,o:{patchProp:r,createText:i,nextSibling:a,parentNode:o,remove:c,insert:l,createComment:u}}=e,d=(e,t)=>{t.hasChildNodes()?(f(t.firstChild,e,null,null,null),dr(),t._vnode=e):(n(null,e,t),dr(),t._vnode=e)},f=(n,r,s,c,u,d=!1)=>{d||=!!r.dynamicChildren;let b=Ti(n)&&n.data===`[`,x=()=>g(n,r,s,c,u,b),{type:S,ref:ee,shapeFlag:C,patchFlag:te}=r,w=n.nodeType;r.el=n,te===-2&&(d=!1,r.dynamicChildren=null);let T=null;switch(S){case ys:w===3?(n.data!==r.children&&(xi(),n.data=r.children),T=a(n)):r.children===``?(l(r.el=i(``),o(n),n),T=n):T=x();break;case z:y(n)?(T=a(n),v(r.el=n.content.firstChild,n,s)):T=w!==8||b?x():a(n);break;case bs:if(b&&(n=a(n),w=n.nodeType),w===1||w===3){T=n;let e=!r.children.length;for(let t=0;t{o||=!!t.dynamicChildren;let{type:l,dynamicProps:u,props:d,patchFlag:f,shapeFlag:p,dirs:h,transition:g}=t,_=l===`input`||l===`option`,b=!!u;if(_||b||f!==-1||g&&l!==`template`&&y(e)){h&&Tr(t,null,n,`created`);let l=!1;if(y(e)){l=Xo(null,g)&&n&&n.vnode.props&&n.vnode.props.appear;let r=e.content.firstChild;if(l){let e=r.getAttribute(`class`);e&&(r.$cls=e),g.beforeEnter(r)}v(r,e,n),t.el=e=r}if(p&16&&!(d&&(d.innerHTML||d.textContent))){let r=m(e.firstChild,t,e,n,i,a,o);for(r&&!ji(e,1)&&xi();r;){let e=r;r=r.nextSibling,c(e)}}else if(p&8){let n=t.children;n[0]===` +`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,` +`)&&(ji(e,0)||xi(),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(Oi(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&&un(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Bs(x,n,t),h&&Tr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&gs(()=>{x&&Bs(x,n,t),l&&g.enter(e),h&&Tr(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===R,g=!1;for(let t=0;t{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&&Ti(f)&&f.data===`]`?a(t.anchor=f):(xi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Ni(e,t)||xi(),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,wi(d),s),r&&r.vnode.el===e&&(r.vnode.el=t.el,To(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&Ti(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 Di=new Set([`src`,`srcset`,`href`,`poster`]);function Oi(e,t,n){return Di.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var ki=`data-allow-mismatch`,Ai={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function ji(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(ki);)e=e.parentElement;return Mi(e&&e.getAttribute(ki),t)}function Mi(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(Ai[t])}}function Ni(e,t){return ji(e.parentElement,1)||Pi(e)||Fi(t)}function Pi(e){return e.nodeType===1&&Mi(e.getAttribute(ki),1)}function Fi({props:e}){let t=e&&e[ki];return typeof t==`string`&&Mi(t,1)}var Ii=ge().requestIdleCallback||(e=>setTimeout(e,1)),Li=ge().cancelIdleCallback||(e=>clearTimeout(e)),Ri=(e=1e4)=>t=>{let n=Ii(t,{timeout:e});return()=>Li(n)};function zi(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t0&&r0&&n0&&i(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e),i=e=>{if(zi(e))return t(),r.disconnect(),!1;if(getComputedStyle(e).display===`contents`){for(let t=0;t{if(e instanceof Element)return i(e)}),()=>r.disconnect()},Vi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Hi=(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 Ui(e,t){if(Ti(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(Ti(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Wi=e=>!!e.type.__asyncLoader;function Gi(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 I({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=>Ui(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Gs;if(mi(e),u)return()=>Ki(u,e);let t=t=>{l=null,Xn(t,e,13,!r,!0)};if(s&&e.suspense||Qs)return p().then(t=>()=>Ki(t,e)).catch(e=>(t(e),()=>r?W(r,{error:e}):null));let a=M(!1),c=M(),d=M(!!i),f,m;return He(()=>{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||(a.value=!0,e.parent&&qi(e.parent.vnode)&&e.parent.update())}).catch(n=>{e.isUnmounted?l=null:(t(n),c.value=n)}),()=>{if(a.value&&u)return Ki(u,e);if(c.value&&r)return W(r,{error:c.value});if(n&&!d.value)return Ki(n,e)}}})}function Ki(e,t){let{ref:n,props:r,children:i,ce:a}=t.vnode,o=W(e,r,i);return o.ref=n,o.ce=a,delete t.vnode.ce,o}var qi=e=>e.type.__isKeepAlive,Ji={name:`KeepAlive`,__isKeepAlive:!0,props:{include:[String,RegExp,Array],exclude:[String,RegExp,Array],max:[String,Number]},setup(e,{slots:t}){let n=Ks(),r=n.ctx;if(!r.renderer)return()=>{let e=t.default&&t.default();return e&&e.length===1?e[0]:e};let i=new Map,a=new Set,o=null,s=n.suspense,{renderer:{p:c,m:l,um:u,o:{createElement:d}}}=r,f=d(`div`);r.activate=(e,t,n,r,i)=>{let a=e.component;l(e,t,n,0,s),c(a.vnode,e,t,n,a,s,r,e.slotScopeIds,i),Wo(()=>{a.isDeactivated=!1,a.a&&de(a.a);let t=e.props&&e.props.onVnodeMounted;t&&Bs(t,a.parent,e)},s)},r.deactivate=e=>{let t=i.get(e.key==null?e.type:e.key);if(!t||t.component!==e.component)return!1;let n=e.component;return es(n.m),es(n.a),l(e,f,null,1,s),Wo(()=>{n.da&&de(n.da);let t=e.props&&e.props.onVnodeUnmounted;t&&Bs(t,n.parent,e),n.isDeactivated=!0},s),!0};function p(e){ea(e),u(e,n,s,!0)}function m(e){i.forEach((t,n)=>{let r=dc(Wi(t)?t.type.__asyncResolved||{}:t.type);r&&!e(r)&&h(n)})}function h(e){let t=i.get(e);t&&(!o||!Os(t,o))?p(t):o&&(o.key==null?o.type:o.key)===e&&(ea(o),t&&ea(t)),i.delete(e),a.delete(e)}Pr(()=>[e.include,e.exclude],([e,t])=>{e&&m(t=>Yi(e,t)),t&&m(e=>!Yi(t,e))},{flush:`post`,deep:!0});let g=null,_=()=>{if(g!=null){if(ns(n.subTree.type)){let e=()=>{let e=ta(n.subTree);e.component&&i.set(g,e)};n.subTree.suspense.pendingBranch?Wo(e,n.subTree.suspense):e()}else i.set(g,ta(n.subTree))}};return aa(_),sa(_),ca(()=>{i.forEach(e=>{let{subTree:t,suspense:r}=n,i=ta(t);if(e.type===i.type&&e.key===i.key){ea(i);let e=i.component.da;e&&Wo(e,r)}else p(e)})}),()=>{if(g=null,!t.default)return o=null;let n=t.default(),r=n[0];if(n.length>1)return o=null,n;if(!Ds(r)||!(r.shapeFlag&4)&&!(r.shapeFlag&128))return o=null,r;let s=ta(r);if(s.type===z)return o=null,s;let c=s.type,l=dc(Wi(s)?s.type.__asyncResolved||{}:c),{include:u,exclude:d,max:f}=e;if(u&&(!l||!Yi(u,l))||d&&l&&Yi(d,l))return s.shapeFlag&=-257,o=s,r;let p=s.key==null?c:s.key,m=i.get(p);return s.el&&(s=Ps(s),r.shapeFlag&128&&(r.ssContent=s)),g=p,m?(s.el=m.el,s.component=m.component,s.transition&&ui(s,s.transition),s.shapeFlag|=512,a.delete(p),a.add(p)):(a.add(p),f&&a.size>parseInt(f,10)&&h(a.values().next().value)),s.shapeFlag|=256,o=s,ns(r.type)?r:s}}};function Yi(e,t){return p(e)?e.some(e=>Yi(e,t)):y(e)?e.split(`,`).includes(t):_(e)?(e.lastIndex=0,e.test(t)):!1}function Xi(e,t){Qi(e,`a`,t)}function Zi(e,t){Qi(e,`da`,t)}function Qi(e,t,n=Gs){let r=e.__wdc||=()=>{let t=n;for(;t;){if(t.isDeactivated)return;t=t.parent}return e()};if(na(t,r,n),n){let e=n.parent;for(;e&&e.parent;)qi(e.parent.vnode)&&$i(r,t,n,e),e=e.parent}}function $i(e,t,n,r){let i=na(t,e,r,!0),a=na(`um`,()=>u(r[t],i),n);a.flags=16}function ea(e){e.shapeFlag&=-257,e.shapeFlag&=-513}function ta(e){return e.shapeFlag&128?e.ssContent:e}function na(e,t,n=Gs,r=!1){if(n){let i=n[e]||(n[e]=[]),a=t.__weh||=(...r)=>{st();let i=Ys(n),a=Yn(t,n,e,r);return i(),ct(),a};return r?i.unshift(a):i.push(a),a}}var ra=e=>(t,n=Gs)=>{Qs&&e!==`sp`||na(e,(...e)=>t(...e),n)},ia=ra(`bm`),aa=ra(`m`),oa=ra(`bu`),sa=ra(`u`),ca=ra(`bum`),la=ra(`um`),ua=ra(`sp`),da=ra(`rtg`),fa=ra(`rtc`);function pa(e,t=Gs){na(`ec`,e,t)}var ma=`components`,ha=`directives`;function ga(e,t){return ba(ma,e,!0,t)||e}var _a=Symbol.for(`v-ndc`);function va(e){return y(e)?ba(ma,e,!1)||e:e||_a}function ya(e){return ba(ha,e)}function ba(e,t,n=!0,r=!1){let i=yr||Gs;if(i){let n=i.type;if(e===ma){let e=dc(n,!1);if(e&&(e===t||e===E(t)||e===ce(E(t))))return n}let a=xa(i[e]||n[e],t)||xa(i.appContext[e],t);return!a&&r?n:a}}function xa(e,t){return e&&(e[t]||e[E(t)]||e[ce(E(t))])}function L(e,t,n,r){let i,a=n&&n[r],o=p(e);if(o||y(e)){let n=o&&un(e),r=!1,s=!1;n&&(r=!fn(e),s=dn(e),e=St(e)),i=Array(e.length);for(let n=0,o=e.length;nt(e,n,void 0,a&&a[n]));else{let n=Object.keys(e);i=Array(n.length);for(let r=0,o=n.length;r{let t=r.fn(...e);return t&&(t.key=r.key),t}:r.fn)}return e}function Ca(e,t,n,r,i,a){if(n??={},yr.ce||yr.parent&&Wi(yr.parent)&&yr.parent.ce){let e=a!=null&&n.key==null?l({},n,{key:a}):n,i=Object.keys(e).length>0;return t!=="default"&&(e.name=t),B(),H(R,null,[W(`slot`,e,r&&r())],i?-2:64)}let o=e[t];o&&o._c&&(o._d=!1);let s=xs.length;B();let c;try{let i=o&&wa(o(n)),s=n.key||a||i&&i.key;c=H(R,{key:(s&&!b(s)?s:`_${t}`)+(!i&&r?`_fb`:``)},i||(r?r():[]),i&&e._===1?64:-2)}catch(e){for(let e=xs.length;e>s;e--)Cs();throw e}finally{o&&o._c&&(o._d=!0)}return!i&&c.scopeId&&(c.slotScopeIds=[c.scopeId+`-s`]),c}function wa(e){return e.some(e=>!Ds(e)||!(e.type===z||e.type===R&&!wa(e.children)))?e:null}function Ta(e,t){let n={};for(let r in e)n[t&&/[A-Z]/.test(r)?`on:${r}`:le(r)]=e[r];return n}var Ea=e=>e?Zs(e)?uc(e):Ea(e.parent):null,Da=l(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>Ea(e.parent),$root:e=>Ea(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Za(e),$forceUpdate:e=>e.f||=()=>{sr(e.update)},$nextTick:e=>e.n||=ar.bind(e.proxy),$watch:e=>Ir.bind(e)}),Oa=(e,t)=>e!==r&&!e.__isScriptSetup&&f(e,t),ka={get({_:e},t){if(t===`__v_skip`)return!0;let{ctx:n,setupState:i,data:a,props:o,accessCache:s,type:c,appContext:l}=e;if(t[0]!==`$`){let e=s[t];if(e!==void 0)switch(e){case 1:return i[t];case 2:return a[t];case 4:return n[t];case 3:return o[t]}else if(Oa(i,t))return s[t]=1,i[t];else if(a!==r&&f(a,t))return s[t]=2,a[t];else if(f(o,t))return s[t]=3,o[t];else if(n!==r&&f(n,t))return s[t]=4,n[t];else Ka&&(s[t]=0)}let u=Da[t],d,p;if(u)return t===`$attrs`&&vt(e.attrs,`get`,``),u(e);if((d=c.__cssModules)&&(d=d[t]))return d;if(n!==r&&f(n,t))return s[t]=4,n[t];if(p=l.config.globalProperties,f(p,t))return p[t]},set({_:e},t,n){let{data:i,setupState:a,ctx:o}=e;return Oa(a,t)?(a[t]=n,!0):i!==r&&f(i,t)?(i[t]=n,!0):f(e.props,t)||t[0]===`$`&&t.slice(1)in e?!1:(o[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:i,appContext:a,props:o,type:s}},c){let l;return!!(n[c]||e!==r&&c[0]!==`$`&&f(e,c)||Oa(t,c)||f(o,c)||f(i,c)||f(Da,c)||f(a.config.globalProperties,c)||(l=s.__cssModules)&&l[c])},defineProperty(e,t,n){return n.get==null?f(n,`value`)&&this.set(e,t,n.value,null):e._.accessCache[t]=0,Reflect.defineProperty(e,t,n)}},Aa=l({},ka,{get(e,t){if(t!==Symbol.unscopables)return ka.get(e,t,e)},has(e,t){return t[0]!==`_`&&!_e(t)}});function ja(){return null}function Ma(){return null}function Na(e){}function Pa(e){}function Fa(){return null}function Ia(){}function La(e,t){return null}function Ra(){return Ba(`useSlots`).slots}function za(){return Ba(`useAttrs`).attrs}function Ba(e){let t=Ks();return t.setupContext||=lc(t)}function Va(e){return p(e)?e.reduce((e,t)=>(e[t]=null,e),{}):e}function Ha(e,t){let n=Va(e);for(let e in t){if(e.startsWith(`__skip`))continue;let r=n[e];r?p(r)||v(r)?r=n[e]={type:r,default:t[e]}:r.default=t[e]:r===null&&(r=n[e]={default:t[e]}),r&&t[`__skip_${e}`]&&(r.skipFactory=!0)}return n}function Ua(e,t){return!e||!t?e||t:p(e)&&p(t)?e.concat(t):l({},Va(e),Va(t))}function Wa(e,t){let n={};for(let r in e)t.includes(r)||Object.defineProperty(n,r,{enumerable:!0,get:()=>e[r]});return n}function Ga(e){let t=Ks(),n=Qs,r=e();Xs(),n&&Js(!1);let i=()=>{Ys(t),n&&Js(!0)},a=()=>{Ks()!==t&&t.scope.off(),Xs(),n&&Js(!1)};return S(r)&&(r=r.catch(e=>{throw i(),Promise.resolve().then(()=>Promise.resolve().then(a)),e})),[r,()=>{i(),Promise.resolve().then(a)}]}var Ka=!0;function qa(e){let t=Za(e),n=e.proxy,r=e.ctx;Ka=!1,t.beforeCreate&&Ya(t.beforeCreate,e,`bc`);let{data:i,computed:o,methods:s,watch:c,provide:l,inject:u,created:d,beforeMount:f,mounted:m,beforeUpdate:h,updated:g,activated:_,deactivated:y,beforeDestroy:b,beforeUnmount:S,destroyed:ee,unmounted:C,render:te,renderTracked:w,renderTriggered:T,errorCaptured:ne,serverPrefetch:re,expose:ie,inheritAttrs:ae,components:E,directives:oe,filters:se}=t;if(u&&Ja(u,r,null),s)for(let e in s){let t=s[e];v(t)&&(r[e]=t.bind(n))}if(i){let t=i.call(n,n);x(t)&&(e.data=an(t))}if(Ka=!0,o)for(let e in o){let t=o[e],i=pc({get:v(t)?t.bind(n,n):v(t.get)?t.get.bind(n,n):a,set:!v(t)&&v(t.set)?t.set.bind(n):a});Object.defineProperty(r,e,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e})}if(c)for(let e in c)Xa(c[e],r,n,e);if(l){let e=v(l)?l.call(n):l;Reflect.ownKeys(e).forEach(t=>{Er(t,e[t])})}d&&Ya(d,e,`c`);function ce(e,t){p(t)?t.forEach(t=>e(t.bind(n))):t&&e(t.bind(n))}if(ce(ia,f),ce(aa,m),ce(oa,h),ce(sa,g),ce(Xi,_),ce(Zi,y),ce(pa,ne),ce(fa,w),ce(da,T),ce(ca,S),ce(la,C),ce(ua,re),p(ie)){if(ie.length){let t=e.exposed||={};ie.forEach(e=>{Object.defineProperty(t,e,{get:()=>n[e],set:t=>n[e]=t,enumerable:!0})})}else e.exposed||={}}te&&e.render===a&&(e.render=te),ae!=null&&(e.inheritAttrs=ae),E&&(e.components=E),oe&&(e.directives=oe),re&&mi(e)}function Ja(e,t,n=a){p(e)&&(e=no(e));for(let n in e){let r=e[n],i;i=x(r)?`default`in r?Dr(r.from||n,r.default,!0):Dr(r.from||n):Dr(r),j(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e}):t[n]=i}}function Ya(e,t,n){Yn(p(e)?e.map(e=>e.bind(t.proxy)):e.bind(t.proxy),t,n)}function Xa(e,t,n,r){let i=r.includes(`.`)?Lr(n,r):()=>n[r];if(y(e)){let n=t[e];v(n)&&Pr(i,n)}else if(v(e))Pr(i,e.bind(n));else if(x(e)){if(p(e))e.forEach(e=>Xa(e,t,n,r));else{let r=v(e.handler)?e.handler.bind(n):t[e.handler];v(r)&&Pr(i,r,e)}}}function Za(e){let t=e.type,{mixins:n,extends:r}=t,{mixins:i,optionsCache:a,config:{optionMergeStrategies:o}}=e.appContext,s=a.get(t),c;return s?c=s:!i.length&&!n&&!r?c=t:(c={},i.length&&i.forEach(e=>Qa(c,e,o,!0)),Qa(c,t,o)),x(t)&&a.set(t,c),c}function Qa(e,t,n,r=!1){let{mixins:i,extends:a}=t;a&&Qa(e,a,n,!0),i&&i.forEach(t=>Qa(e,t,n,!0));for(let i in t)if(!(r&&i===`expose`)){let r=$a[i]||n&&n[i];e[i]=r?r(e[i],t[i]):t[i]}return e}var $a={data:eo,props:ao,emits:ao,methods:io,computed:io,beforeCreate:ro,created:ro,beforeMount:ro,mounted:ro,beforeUpdate:ro,updated:ro,beforeDestroy:ro,beforeUnmount:ro,destroyed:ro,unmounted:ro,activated:ro,deactivated:ro,errorCaptured:ro,serverPrefetch:ro,components:io,directives:io,watch:oo,provide:eo,inject:to};function eo(e,t){return t?e?function(){return l(v(e)?e.call(this,this):e,v(t)?t.call(this,this):t)}:t:e}function to(e,t){return io(no(e),no(t))}function no(e){if(p(e)){let t={};for(let n=0;n{let l,u=r,d;return Nr(()=>{let t=e[a];ue(l,t)&&(l=t,c())}),{get(){return s(),n.get?n.get(l):l},set(e){let s=n.set?n.set(e):e;if(!ue(s,l)&&!(u!==r&&ue(e,u)))return;let f=i.vnode.props,p=!!(f&&(t in f||a in f||o in f)&&(`onUpdate:${t}`in f||`onUpdate:${a}`in f||`onUpdate:${o}`in f));p||(l=e,c()),i.emit(`update:${t}`,s),ue(e,u)&&(ue(e,s)&&!ue(s,d)||p&&u!==r&&!ue(s,l))&&c(),u=e,d=s}}});return c[Symbol.iterator]=()=>{let e=0;return{next(){return e<2?{value:e++?s||r:c,done:!1}:{done:!0}}}},c}var po=(e,t)=>t===`modelValue`||t===`model-value`?e.modelModifiers:e[`${t}Modifiers`]||e[`${E(t)}Modifiers`]||e[`${se(t)}Modifiers`];function mo(e,t,...n){if(e.isUnmounted)return;let i=e.vnode.props||r,a=n,o=t.startsWith(`update:`),s=o&&po(i,t.slice(7));s&&(s.trim&&(a=n.map(e=>y(e)?e.trim():e)),s.number&&(a=a.map(pe)));let c,l=i[c=le(t)]||i[c=le(E(t))];!l&&o&&(l=i[c=le(se(t))]),l&&Yn(l,e,6,a);let u=i[c+`Once`];if(u){if(!e.emitted)e.emitted={};else if(e.emitted[c])return;e.emitted[c]=!0,Yn(u,e,6,a)}}var ho=new WeakMap;function go(e,t,n=!1){let r=n?ho:t.emitsCache,i=r.get(e);if(i!==void 0)return i;let a=e.emits,o={},s=!1;if(!v(e)){let r=e=>{let n=go(e,t,!0);n&&(s=!0,l(o,n))};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}return!a&&!s?(x(e)&&r.set(e,null),null):(p(a)?a.forEach(e=>o[e]=null):l(o,a),x(e)&&r.set(e,o),o)}function _o(e,t){return!e||!s(t)?!1:(t=t.slice(2),t=t===`Once`?t:t.replace(/Once$/,``),f(e,t[0].toLowerCase()+t.slice(1))||f(e,se(t))||f(e,t))}function vo(e){let{type:t,vnode:n,proxy:r,withProxy:i,propsOptions:[a],slots:o,attrs:s,emit:l,render:u,renderCache:d,props:f,data:p,setupState:m,ctx:h,inheritAttrs:g}=e,_=xr(e),v,y;try{if(n.shapeFlag&4){let e=i||r,t=e;v=Is(u.call(t,e,d,f,m,p,h)),y=s}else{let e=t;v=Is(e.length>1?e(f,{attrs:s,slots:o,emit:l}):e(f,null)),y=t.props?s:bo(s)}}catch(t){xs.length=0,Xn(t,e,1),v=W(z)}let b=v;if(y&&g!==!1){let e=Object.keys(y),{shapeFlag:t}=b;e.length&&t&7&&(a&&e.some(c)&&(y=xo(y,a)),b=Ps(b,y,!1,!0))}return n.dirs&&(b=Ps(b,null,!1,!0),b.dirs=b.dirs?b.dirs.concat(n.dirs):n.dirs),n.transition&&ui(Br(b.type)&&li(b)||b,n.transition),v=b,xr(_),v}function yo(e,t=!0){let n;for(let t=0;t{let t;for(let n in e)(n===`class`||n===`style`||s(n))&&((t||={})[n]=e[n]);return t},xo=(e,t)=>{let n={};for(let r in e)c(r)&&r.slice(9)in t||(n[r]=e[r]);return n};function So(e,t,n){let{props:r,children:i,component:a}=e,{props:o,children:s,patchFlag:c}=t,l=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&c>=0){if(c&1024)return!0;if(c&16)return r?Co(r,o,l):!!o;if(c&8){let e=t.dynamicProps;for(let t=0;tObject.create(Eo),Oo=e=>Object.getPrototypeOf(e)===Eo;function ko(e,t,n,r=!1){let i={},a=Do();e.propsDefaults=Object.create(null),jo(e,t,i,a);for(let t in e.propsOptions[0])t in i||(i[t]=void 0);e.props=n?r?i:on(i):e.type.props?i:a,e.attrs=a}function Ao(e,t,n,r){let{props:i,attrs:a,vnode:{patchFlag:o}}=e,s=A(i),[c]=e.propsOptions,l=!1;if((r||o>0)&&!(o&16)){if(o&8){let n=e.vnode.dynamicProps;for(let r=0;r{d=!0;let[n,r]=Po(e,t,!0);l(c,n),r&&u.push(...r)};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}if(!s&&!d)return x(e)&&a.set(e,i),i;if(p(s))for(let e=0;ee===`_`||e===`_ctx`||e===`$stable`,Lo=e=>p(e)?e.map(Is):[Is(e)],Ro=(e,t,n)=>{if(t._n)return t;let r=P((...e)=>Lo(t(...e)),n);return r._c=!1,r},zo=(e,t,n)=>{let r=e._ctx;for(let n in e){if(Io(n))continue;let i=e[n];if(v(i))t[n]=Ro(n,i,r);else if(i!=null){let e=Lo(i);t[n]=()=>e}}},Bo=(e,t)=>{let n=Lo(t);e.slots.default=()=>n},Vo=(e,t,n)=>{for(let r in t)(n||!Io(r))&&(e[r]=t[r])},Ho=(e,t,n)=>{let r=e.slots=Do();if(e.vnode.shapeFlag&32){let e=t._;e?(Vo(r,t,n),n&&fe(r,`_`,e,!0)):zo(t,r)}else t&&Bo(e,t)},Uo=(e,t,n)=>{let{vnode:i,slots:a}=e,o=!0,s=r;if(i.shapeFlag&32){let e=t._;e?n&&e===1?o=!1:Vo(a,t,n):(o=!t.$stable,zo(t,a)),s=t}else t&&(Bo(e,t),s={default:1});if(o)for(let e in a)!Io(e)&&s[e]==null&&delete a[e]},Wo=gs;function Go(e){return qo(e)}function Ko(e){return qo(e,Ei)}function qo(e,t){let n=ge();n.__VUE__=!0;let{insert:o,remove:s,patchProp:c,createElement:l,createText:u,createComment:d,setText:f,setElementText:p,parentNode:m,nextSibling:h,setScopeId:g=a,insertStaticContent:_}=e,v=(e,t,n,r=null,a=null,o=null,s=void 0,c=null,l=!!t.dynamicChildren)=>{if(e===t)return;e&&!Os(e,t)&&(r=Se(e),_e(e,a,o,!0),e=null),t.patchFlag===-2&&(l=!1,t.dynamicChildren=null),t.dynamicChildren&&e&&e.dynamicChildren&&e.dynamicChildren.hasOnce&&(t.dynamicChildren===i&&(t.dynamicChildren=[]),t.dynamicChildren.hasOnce=!0);let{type:u,ref:d,shapeFlag:f}=t;switch(u){case ys:y(e,t,n,r);break;case z:b(e,t,n,r);break;case bs:e??x(t,n,r,s);break;case R:E(e,t,n,r,a,o,s,c,l);break;default:f&1?C(e,t,n,r,a,o,s,c,l):f&6?oe(e,t,n,r,a,o,s,c,l):(f&64||f&128)&&u.process(e,t,n,r,a,o,s,c,l,Ce)}d!=null&&a?vi(d,e&&e.ref,o,t||e,!t):d==null&&e&&e.ref!=null&&vi(e.ref,null,o,e,!0)},y=(e,t,n,r)=>{if(e==null)o(t.el=u(t.children),n,r);else{let n=t.el=e.el;t.children!==e.children&&f(n,t.children)}},b=(e,t,n,r)=>{e==null?o(t.el=d(t.children||``),n,r):t.el=e.el},x=(e,t,n,r)=>{[e.el,e.anchor]=_(e.children,t,n,r,e.el,e.anchor)},S=({el:e,anchor:t},n,r)=>{let i;for(;e&&e!==t;)i=h(e),o(e,n,r),e=i;o(t,n,r)},ee=({el:e,anchor:t})=>{let n;for(;e&&e!==t;)n=h(e),s(e),e=n;s(t)},C=(e,t,n,r,i,a,o,s,c)=>{if(t.type===`svg`?o=`svg`:t.type===`math`&&(o=`mathml`),e==null)te(t,n,r,i,a,o,s,c);else{let n=e.el&&e.el._isVueCE?e.el:null;try{n&&n._beginPatch(),re(e,t,i,a,o,s,c)}finally{n&&n._endPatch()}}},te=(e,t,n,r,i,a,s,u)=>{let d,f,{props:m,shapeFlag:h,transition:g,dirs:_}=e;if(d=e.el=l(e.type,a,m&&m.is,m),h&8?p(d,e.children):h&16&&T(e.children,d,null,r,i,Jo(e,a),s,u),_&&Tr(e,null,r,`created`),w(d,e,e.scopeId,s,r),m){for(let e in m)e!==`value`&&!ne(e)&&c(d,e,null,m[e],a,r);`value`in m&&c(d,`value`,null,m.value,a),(f=m.onVnodeBeforeMount)&&Bs(f,r,e)}_&&Tr(e,null,r,`beforeMount`);let v=Xo(i,g);v?g.beforeEnter(d):g&&!g.persisted&&(d[is]=!0),o(d,t,n),((f=m&&m.onVnodeMounted)||v||_)&&Wo(()=>{try{f&&Bs(f,r,e),v&&g.enter(d),_&&Tr(e,null,r,`mounted`)}finally{}},i)},w=(e,t,n,r,i)=>{if(n&&g(e,n),r)for(let t=0;t{for(let l=c;l{let l=t.el=e.el,{patchFlag:u,dynamicChildren:d,dirs:f}=t;u|=e.patchFlag&16;let m=e.props||r,h=t.props||r,g;if(n&&Yo(n,!1),(g=h.onVnodeBeforeUpdate)&&Bs(g,n,t,e),f&&Tr(t,e,n,`beforeUpdate`),n&&Yo(n,!0),d&&(!e.dynamicChildren||e.dynamicChildren.length!==d.length)&&(u=0,s=!1,d=null),(m.innerHTML&&h.innerHTML==null||m.textContent&&h.textContent==null)&&p(l,``),d?ie(e.dynamicChildren,d,l,n,i,Jo(t,a),o):s||fe(e,t,l,null,n,i,Jo(t,a),o,!1),u>0){if(u&16)ae(l,m,h,n,a);else if(u&2&&m.class!==h.class&&c(l,`class`,null,h.class,a),u&4&&c(l,`style`,m.style,h.style,a),u&8){let e=t.dynamicProps;for(let t=0;t{g&&Bs(g,n,t,e),f&&Tr(t,e,n,`updated`)},i)},ie=(e,t,n,r,i,a,o)=>{for(let s=0;s{if(t!==n){if(t!==r)for(let r in t)!ne(r)&&!(r in n)&&c(e,r,t[r],null,a,i);for(let r in n){if(ne(r))continue;let o=n[r],s=t[r];o!==s&&r!==`value`&&c(e,r,s,o,a,i)}`value`in n&&c(e,`value`,t.value,n.value,a)}},E=(e,t,n,r,i,a,s,c,l)=>{let d=t.el=e?e.el:u(``),f=t.anchor=e?e.anchor:u(``),{patchFlag:p,dynamicChildren:m,slotScopeIds:h}=t;h&&(c=c?c.concat(h):h),e==null?(o(d,n,r),o(f,n,r),T(t.children||[],n,f,i,a,s,c,l)):p>0&&p&64&&m&&e.dynamicChildren&&e.dynamicChildren.length===m.length?(ie(e.dynamicChildren,m,n,i,a,s,c),(t.key!=null||i&&t===i.subTree)&&Zo(e,t,!0)):fe(e,t,n,f,i,a,s,c,l)},oe=(e,t,n,r,i,a,o,s,c)=>{t.slotScopeIds=s,e==null?t.shapeFlag&512?i.ctx.activate(t,n,r,o,c):se(t,n,r,i,a,o,c):ce(e,t,c)},se=(e,t,n,r,i,a,o)=>{let s=e.component=Ws(e,r,i);if(qi(e)&&(s.ctx.renderer=Ce),$s(s,!1,o),s.asyncDep){if(i&&i.registerDep(s,le,o,a),!e.el){let r=s.subTree=W(z);b(null,r,t,n),e.placeholder=r.el}}else le(s,e,t,n,i,a,o)},ce=(e,t,n)=>{let r=t.component=e.component;if(So(e,t,n)){if(r.asyncDep&&!r.asyncResolved){t.el=e.el,t.placeholder=e.placeholder,ue(r,t,n);return}r.next=t,r.update()}else t.el=e.el,t.placeholder=e.placeholder,r.vnode=t},le=(e,t,n,r,i,a,o)=>{let s=()=>{if(e.isMounted){let{next:t,bu:n,u:r,parent:s,vnode:c}=e;{let n=$o(e);if(n){t&&(t.el=c.el,ue(e,t,o)),n.asyncDep.then(()=>{let t=()=>{e.job.flags&8||(i&&i.pendingBranch?Wo(t,i):l())};t.flags=48,Wo(t,i)});return}}let u=t,d;Yo(e,!1),t?(t.el=c.el,ue(e,t,o)):t=c,n&&de(n),(d=t.props&&t.props.onVnodeBeforeUpdate)&&Bs(d,s,t,c),Yo(e,!0);let f=vo(e),p=e.subTree;e.subTree=f,v(p,f,m(p.el||ts(p)),Se(p),e,i,a),t.el=f.el,u===null&&To(e,f.el),r&&Wo(r,i),(d=t.props&&t.props.onVnodeUpdated)&&Wo(()=>Bs(d,s,t,c),i)}else{let o,{el:s,props:c}=t,{bm:l,m:u,parent:d,root:f,type:p}=e,m=Wi(t);if(Yo(e,!1),l&&de(l),!m&&(o=c&&c.onVnodeBeforeMount)&&Bs(o,d,t),Yo(e,!0),s&&Te){let t=()=>{e.subTree=vo(e),Te(s,e.subTree,e,i,null)};m&&p.__asyncHydrate?p.__asyncHydrate(s,e,t):t()}else{f.ce&&f.ce._hasShadowRoot()&&f.ce._injectChildStyle(p,e.parent?e.parent.type:void 0);let o=e.subTree=vo(e);v(null,o,n,r,e,i,a),t.el=o.el}if(u&&Wo(u,i),!m&&(o=c&&c.onVnodeMounted)){let e=t;Wo(()=>Bs(o,d,e),i)}(t.shapeFlag&256||d&&Wi(d.vnode)&&d.vnode.shapeFlag&256)&&e.a&&Wo(e.a,i),e.isMounted=!0,t=n=r=null}};e.scope.on();let c=e.effect=new We(s);e.scope.off();let l=e.update=c.run.bind(c),u=e.job=c.runIfDirty.bind(c);u.i=e,u.id=e.uid,c.scheduler=()=>sr(u),Yo(e,!0),l()},ue=(e,t,n)=>{t.component=e;let r=e.vnode.props;e.vnode=t,e.next=null,Ao(e,t.props,r,n),Uo(e,t.children,n),st(),ur(e),ct()},fe=(e,t,n,r,i,a,o,s,c=!1)=>{let l=e&&e.children,u=e?e.shapeFlag:0,d=t.children,{patchFlag:f,shapeFlag:m}=t;if(f>0){if(f&128){me(l,d,n,r,i,a,o,s,c);return}if(f&256){pe(l,d,n,r,i,a,o,s,c);return}}m&8?(u&16&&xe(l,i,a),d!==l&&p(n,d)):u&16?m&16?me(l,d,n,r,i,a,o,s,c):xe(l,i,a,!0):(u&8&&p(n,``),m&16&&T(d,n,r,i,a,o,s,c))},pe=(e,t,n,r,a,o,s,c,l)=>{e||=i,t||=i;let u=e.length,d=t.length,f=Math.min(u,d),p=0;for(;pd?xe(e,a,o,!0,!1,f):T(t,n,r,a,o,s,c,l,f)},me=(e,t,n,r,a,o,s,c,l)=>{let u=0,d=t.length,f=e.length-1,p=d-1;for(;u<=f&&u<=p;){let r=e[u],i=t[u]=l?Ls(t[u]):Is(t[u]);if(Os(r,i))v(r,i,n,null,a,o,s,c,l);else break;u++}for(;u<=f&&u<=p;){let r=e[f],i=t[p]=l?Ls(t[p]):Is(t[p]);if(Os(r,i))v(r,i,n,null,a,o,s,c,l);else break;f--,p--}if(u>f){if(u<=p){let e=p+1,i=ep)for(;u<=f;)_e(e[u],a,o,!0),u++;else{let m=u,h=u,g=new Map;for(u=h;u<=p;u++){let e=t[u]=l?Ls(t[u]):Is(t[u]);e.key!=null&&g.set(e.key,u)}let _,y=0,b=p-h+1,x=!1,S=0,ee=Array(b);for(u=0;u=b){_e(r,a,o,!0);continue}let i;if(r.key!=null)i=g.get(r.key);else for(_=h;_<=p;_++)if(ee[_-h]===0&&Os(r,t[_])){i=_;break}i===void 0?_e(r,a,o,!0):(ee[i-h]=u+1,i>=S?S=i:x=!0,v(r,t[i],n,null,a,o,s,c,l),y++)}let C=x?Qo(ee):i;for(_=C.length-1,u=b-1;u>=0;u--){let e=h+u,i=t[e],f=t[e+1],p=e+1{let{el:a,type:c,transition:l,children:u,shapeFlag:d}=e;if(d&6)he(e.component.subTree,t,n,r);else if(d&128)e.suspense.move(t,n,r);else if(d&64)c.move(e,t,n,Ce);else if(c===R){o(a,t,n);for(let e=0;el.enter(a),i));else{let{leave:r,delayLeave:i,afterLeave:c}=l,u=()=>{e.ctx.isUnmounted?s(a):o(a,t,n)},d=()=>{let e=a._isLeaving||!!a[Qr];a._isLeaving&&a[Qr](!0),l.persisted&&!e?u():r(a,()=>{u(),c&&c()})};i?i(a,u,d):d()}}else o(a,t,n)},_e=(e,t,n,r=!1,i=!1)=>{let{type:a,props:o,ref:s,children:c,dynamicChildren:l,shapeFlag:u,patchFlag:d,dirs:f,cacheIndex:p,memo:m}=e;if((d===-2||l&&l.hasOnce)&&(i=!1),s!=null&&(st(),vi(s,null,n,e,!0),ct()),p==null||e.ctx&&e.ctx!==t||(t.renderCache[p]=void 0),u&256&&t.ctx.deactivate(e))return;let h=u&1&&f,g=!Wi(e),_;if(g&&(_=o&&o.onVnodeBeforeUnmount)&&Bs(_,t,e),u&6)be(e.component,n,r);else{if(u&128){e.suspense.unmount(n,r);return}h&&Tr(e,null,t,`beforeUnmount`),u&64?e.type.remove(e,t,n,Ce,r):l&&!l.hasOnce&&(a!==R||d>0&&d&64)?xe(l,t,n,!1,!0):(a===R&&d&384||!i&&u&16)&&xe(c,t,n),r&&ve(e)}let v=m!=null&&p==null;(g&&(_=o&&o.onVnodeUnmounted)||h||v)&&Wo(()=>{_&&Bs(_,t,e),h&&Tr(e,null,t,`unmounted`),v&&(e.el=null)},n)},ve=e=>{let{type:t,el:n,anchor:r,transition:i}=e,a=t===R;if(a&&!i){ye(n,r);return}if(t===bs){ee(e),i&&!i.persisted&&i.afterLeave&&i.afterLeave();return}let o=a?fi(e):e,c=()=>{a?m(n)&&ye(n,r):s(n),i&&!i.persisted&&i.afterLeave&&i.afterLeave()};if(o&&o.shapeFlag&1&&i&&!i.persisted){let{leave:e,delayLeave:t}=i,n=o.el,r=()=>e(n,c);t?t(n,c,r):r()}else c()},ye=(e,t)=>{let n;for(;e!==t;)n=h(e),s(e),e=n;s(t)},be=(e,t,n)=>{let{bum:r,scope:i,job:a,subTree:o,um:s,m:c,a:l}=e;es(c),es(l),r&&de(r),i.stop(),a?(a.flags|=8,_e(o,e,t,n)):o&&(o.transition=e.vnode.transition,_e(o,e,t,n)),s&&Wo(s,t);let u=()=>{e.isUnmounted=!0};u.flags=16,Wo(u,t)},xe=(e,t,n,r=!1,i=!1,a=0)=>{for(let o=a;o{if(e.shapeFlag&6)return Se(e.component.subTree);if(e.shapeFlag&128)return e.suspense.next();let t=h(e.anchor||e.el),n=t&&t[zr];return n?h(n):t},D=(e,t,n)=>{pr(()=>{e==null?t._vnode&&_e(t._vnode,null,null,!0):v(t._vnode||null,e,t,null,null,null,n),t._vnode=e},e&&t._vnode?void 0:e&&e.component?e.component.uid:Us())},Ce={p:v,um:_e,m:he,r:ve,mt:se,mc:T,pc:fe,pbc:ie,n:Se,o:e},we,Te;return t&&([we,Te]=t(Ce)),{render:D,hydrate:we,createApp:lo(D,we)}}function Jo({type:e,props:t},n){return n===`svg`&&e===`foreignObject`||n===`mathml`&&e===`annotation-xml`&&t&&t.encoding&&t.encoding.includes(`html`)?void 0:n}function Yo({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Xo(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Zo(e,t,n=!1){let r=e.children,i=t.children;if(p(r)&&p(i))for(let e=0;e>1,e[n[s]]0&&(t[r]=n[a-1]),n[a]=r)}}for(a=n.length,o=n[a-1];a-->0;)n[a]=o,o=t[o];return n}function $o(e){let t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:$o(t)}function es(e){if(e)for(let t=0;te.__isSuspense,rs=0,is=Symbol(`_deferredEnter`),as={name:`Suspense`,__isSuspense:!0,process(e,t,n,r,i,a,o,s,c,l){if(e==null)ls(t,n,r,i,a,o,s,c,l);else{let u=e.suspense;if(a&&a.deps>0&&!a.isHydrating){let n=u.parentComponent;if(n&&n.suspense===a&&n.suspenseId!==a.pendingId?a.pendingBranch&&!Os(t.ssContent,u.pendingBranch||u.activeBranch):!u.isInFallback){t.suspense=u,u.vnode=t,t.el=e.el;return}}us(e,t,n,r,i,o,s,c,l)}},hydrate:fs,normalize:ps};function os(e,t){let n=e.props&&e.props[t];v(n)&&n()}function ss(e){let t=[];cs(e,t,!0),t.length&&lr(t)}function cs(e,t,n){let{el:r,transition:i,children:a,shapeFlag:o}=e;if(o&6)cs(e.component.subTree,t,n);else if(!(o&192)&&(o&1&&(!n&&r&&r[is]&&(r[is]=void 0,i&&!i.persisted&&(i.beforeEnter(r),t.push(()=>i.enter(r)))),n=!1),o&16))for(let e=0;e0?(os(e,`onPending`),os(e,`onFallback`),l(null,e.ssFallback,t,n,r,null,a,o),_s(f,e.ssFallback)):f.resolve(!1,!0)}function us(e,t,n,r,i,a,o,s,{p:c,um:l,o:{createElement:u}}){let d=t.suspense=e.suspense;d.vnode=t,t.el=e.el;let f=t.ssContent,p=t.ssFallback,{activeBranch:m,pendingBranch:h,isInFallback:g,isHydrating:_}=d;if(h)d.pendingBranch=f,Os(h,f)?(d.deps++,c(h,f,_?n:d.hiddenContainer,null,i,d,a,o,s),d.deps--,d.deps<=0?d.resolve():g&&!_&&!d.isFallbackMountPending&&(c(m,p,n,r,i,null,a,o,s),_s(d,p))):(d.pendingId=rs++,_?(d.isHydrating=!1,d.activeBranch=h):l(h,i,d),d.deps=0,hs(d),d.hiddenContainer=u(`div`),g?(c(null,f,d.hiddenContainer,null,i,d,a,o,s),d.deps<=0?d.resolve():d.isFallbackMountPending||(c(m,p,n,r,i,null,a,o,s),_s(d,p))):m&&Os(m,f)?(c(m,f,n,r,i,d,a,o,s),d.resolve(!0),d.pendingId=rs++,d.deps=0):(c(null,f,d.hiddenContainer,null,i,d,a,o,s),d.deps<=0&&d.resolve()));else if(m&&Os(m,f))c(m,f,n,r,i,d,a,o,s),_s(d,f);else if(os(t,`onPending`),d.pendingBranch=f,d.pendingId=rs++,c(null,f,d.hiddenContainer,null,i,d,a,o,s),d.deps<=0)d.resolve();else{let{timeout:e}=d;e>0?d.timeoutTimer=setTimeout(()=>{d.timeoutTimer=void 0,d.fallback(d.vnode.ssFallback)},e):e===0&&d.fallback(p)}}function ds(e,t,n,r,i,a,o,s,c,l,u=!1){let{p:d,m:f,um:p,n:m,o:{parentNode:h,remove:g}}=l,_,v=vs(e);v&&t&&t.pendingBranch&&(_=t.pendingId,t.deps++);let y=e.props?me(e.props.timeout):void 0,b=a,x={vnode:e,parent:t,parentComponent:n,namespace:o,container:r,hiddenContainer:i,deps:0,pendingId:rs++,timeout:typeof y==`number`?y:-1,timeoutTimer:void 0,activeBranch:null,isFallbackMountPending:!1,pendingBranch:null,isInFallback:!u,isHydrating:u,isUnmounted:!1,effects:[],resolve(e=!1,n=!1){let{vnode:r,activeBranch:i,pendingBranch:o,pendingId:s,effects:c,parentComponent:l,container:u,isInFallback:d}=x,g=x.parent;for(;g&&!g.pendingBranch;)g=g.parent;let y=!1;if(x.isHydrating)x.isHydrating=!1;else if(!e){y=i&&o.transition&&o.transition.mode===`out-in`;let e=!1;y&&(i.transition.afterLeave=()=>{if(s===x.pendingId&&!x.isUnmounted){ss(o),f(o,u,a===b&&!e?m(i):a,0);let t=!1;if(g){let e=u,n;for(;n=h(e);)e=n;t=e===g.hiddenContainer}t||lr(c),d&&r.ssFallback&&(r.ssFallback.el=null)}}),i&&!x.isFallbackMountPending&&(h(i.el||ts(i))===u&&(a=m(i),e=!0),p(i,l,x,!0),!y&&d&&r.ssFallback&&Wo(()=>r.ssFallback.el=null,x)),y||(ss(o),f(o,u,a,0))}clearTimeout(x.timeoutTimer),x.timeoutTimer=void 0,x.isFallbackMountPending=!1,_s(x,o),x.pendingBranch=null,x.isInFallback=!1;let S=0;for(let e=0;e{if(x.isFallbackMountPending=!1,x.isUnmounted||!x.isInFallback)return;let e=x.vnode.ssFallback;d(null,e,i,o,r,null,a,s,c),_s(x,e)},u=e.transition&&e.transition.mode===`out-in`;u&&(x.isFallbackMountPending=!0,n.transition.afterLeave=l),x.isInFallback=!0,p(n,r,null,!0),u||l()},move(e,t,n){x.activeBranch&&f(x.activeBranch,e,t,n),x.container=e},next(){return x.activeBranch&&m(x.activeBranch)},registerDep(e,t,n,r){let i=!!x.pendingBranch;i&&x.deps++;let a=e.vnode.el,o=i=>{e.asyncResolved=!0;let{vnode:o}=e;tc(e,i,!1),a&&(o.el=a);let s=!a&&e.subTree.el;t(e,o,h(a||e.subTree.el),a?null:m(e.subTree),x,r,n),s&&(o.placeholder=null,g(s)),To(e,o.el)};e.asyncDep.catch(t=>(e.scope.active&&Xn(t,e,0,!1,!0),()=>null)).then(t=>{if(e.isUnmounted||x.isUnmounted)return;let n=i&&x.pendingId===e.suspenseId;if(Xs(),!e.scope.active)n&&--x.deps===0&&x.resolve();else if(!n&&x.pendingBranch){let n=()=>{e.isUnmounted||x.isUnmounted||!e.scope.active||(x.pendingBranch?gs(n,x):o(t))};n.flags=48,gs(n,x)}else o(t),n&&--x.deps===0&&x.resolve()})},unmount(e,t){if(x.isUnmounted=!0,clearTimeout(x.timeoutTimer),x.timeoutTimer=void 0,_!==void 0){let e=x.parent,t=_;_=void 0,lr(()=>{e.pendingId===t&&!e.isUnmounted&&--e.deps===0&&e.resolve()})}x.activeBranch&&p(x.activeBranch,n,e,t),x.pendingBranch&&(p(x.pendingBranch,n,x,t),hs(x))}};return x}function fs(e,t,n,r,i,a,o,s,c){let l=t.suspense=ds(t,r,n,e.parentNode,document.createElement(`div`),null,i,a,o,s,!0),u=c(e,l.pendingBranch=t.ssContent,n,l,a,o);return l.deps===0&&l.resolve(!1,!0),u}function ps(e){let{shapeFlag:t,children:n}=e,r=t&32;e.ssContent=ms(r?n.default:n),e.ssFallback=r?ms(n.fallback):W(z)}function ms(e){let t;if(v(e)){let n=ws&&e._c;n&&(e._d=!1,B()),e=e(),n&&(e._d=!0,t=Ss,Cs())}return p(e)&&(e=yo(e)),e=Is(e),t&&!e.dynamicChildren&&(e.dynamicChildren=t.filter(t=>t!==e)),e}function hs(e){let{effects:t}=e;for(let e=0;e0?Ss||i:null,Cs(),ws>0&&Ss&&Ss.push(e),e}function V(e,t,n,r,i,a){return Es(U(e,t,n,r,i,a,!0))}function H(e,t,n,r,i){return Es(W(e,t,n,r,i,!0))}function Ds(e){return e?e.__v_isVNode===!0:!1}function Os(e,t){return e.type===t.type&&e.key===t.key}function ks(e){}var As=({key:e})=>e??null,js=({ref:e,ref_key:t,ref_for:n})=>(typeof e==`number`&&(e=``+e),e==null?null:y(e)||j(e)||v(e)?{i:yr,r:e,k:t,f:!!n}:e);function U(e,t=null,n=null,r=0,i=null,a=e===R?0:1,o=!1,s=!1){let c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&As(t),ref:t&&js(t),scopeId:br,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:r,dynamicProps:i,dynamicChildren:null,appContext:null,ctx:yr};return s?(Rs(c,n),a&128&&e.normalize(c)):n&&(c.shapeFlag|=y(n)?8:16),ws>0&&!o&&Ss&&(c.patchFlag>0||a&6)&&c.patchFlag!==32&&Ss.push(c),c}var W=Ms;function Ms(e,t=null,n=null,r=0,i=null,a=!1){if(e&&e!==_a||(e=z),Ds(e)){let r=Ps(e,t,!0);return n&&Rs(r,n),ws>0&&!a&&Ss&&(r.shapeFlag&6?Ss[Ss.indexOf(e)]=r:Ss.push(r)),r.patchFlag=-2,r}if(fc(e)&&(e=e.__vccOpts),t){t=Ns(t);let{class:e,style:n}=t;e&&!y(e)&&(t.class=D(e)),x(n)&&(pn(n)&&!p(n)&&(n=l({},n)),t.style=ve(n))}let o=y(e)?1:ns(e)?128:Br(e)?64:x(e)?4:v(e)?2:0;return U(e,t,n,r,i,o,a,!0)}function Ns(e){return e?pn(e)?l({},e):Oo(e)?l({},e[sc]||e):e:null}function Ps(e,t,n=!1,r=!1){let{props:i,ref:a,patchFlag:o,children:s,transition:c}=e,l=t?zs(i||{},t):i,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:l,key:l&&As(l),ref:t&&t.ref?n&&a?p(a)?a.concat(js(t)):[a,js(t)]:js(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:s,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==R?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Ps(e.ssContent),ssFallback:e.ssFallback&&Ps(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce,cacheIndex:e.cacheIndex};return c&&r&&ui(u,c.clone(u)),u}function G(e=` `,t=0){return W(ys,null,e,t)}function Fs(e,t){let n=W(bs,null,e);return n.staticCount=t,n}function K(e=``,t=!1){return t?(B(),H(z,null,e)):W(z,null,e)}function Is(e){return e==null||typeof e==`boolean`?W(z):p(e)?W(R,null,e.slice()):Ds(e)?Ls(e):W(ys,null,String(e))}function Ls(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Ps(e)}function Rs(e,t){let n=0,{shapeFlag:r}=e;if(t==null)t=null;else if(p(t))n=16;else if(typeof t==`object`){if(r&65){let n=t.default;n&&(n._c&&(n._d=!1),Rs(e,n()),n._c&&(n._d=!0));return}{n=32;let r=t._;!r&&!Oo(t)?t._ctx=yr:r===3&&yr&&(yr.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}}else if(v(t)){if(r&65){Rs(e,{default:t});return}t={default:t,_ctx:yr},n=32}else t=String(t),r&64?(n=16,t=[G(t)]):n=8;e.children=t,e.shapeFlag|=n}function zs(...e){let t={};for(let n=0;nGs||yr,qs,Js;{let e=ge(),t=(t,n)=>{let r;return(r=e[t])||(r=e[t]=[]),r.push(n),e=>{r.length>1?r.forEach(t=>t(e)):r[0](e)}};qs=t(`__VUE_INSTANCE_SETTERS__`,e=>Gs=e),Js=t(`__VUE_SSR_SETTERS__`,e=>Qs=e)}var Ys=e=>{let t=Gs;return qs(e),e.scope.on(),()=>{e.scope.off(),qs(t)}},Xs=()=>{Gs&&Gs.scope.off(),qs(null)};function Zs(e){return e.vnode.shapeFlag&4}var Qs=!1;function $s(e,t=!1,n=!1){t&&Js(t);let{props:r,children:i}=e.vnode,a=Zs(e);ko(e,r,a,t),Ho(e,i,n||t);let o=a?ec(e,t):void 0;return t&&Js(!1),o}function ec(e,t){let n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,ka);let{setup:r}=n;if(r){st();let n=e.setupContext=r.length>1?lc(e):null,i=Ys(e),a=Jn(r,e,0,[e.props,n]),o=S(a);if(ct(),i(),(o||e.sp)&&!Wi(e)&&mi(e),o){if(a.then(Xs,Xs),t)return a.then(n=>{Js(!0);try{tc(e,n,t)}finally{Js(!1)}}).catch(t=>{Xn(t,e,0,void 0,!0),e.ssrRender=(e,t)=>t(``)});e.asyncDep=a}else tc(e,a,t)}else oc(e,t)}function tc(e,t,n){v(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:x(t)&&(e.setupState=Cn(t)),oc(e,n)}var nc,rc;function ic(e){nc=e,rc=e=>{e.render._rc&&(e.withProxy=new Proxy(e.ctx,Aa))}}var ac=()=>!nc;function oc(e,t,n){let r=e.type;if(!e.render){if(!t&&nc&&!r.render){let t=r.template||Za(e).template;if(t){let{isCustomElement:n,compilerOptions:i}=e.appContext.config,{delimiters:a,compilerOptions:o}=r,s=l(l({isCustomElement:n,delimiters:a},i),o);r.render=nc(t,s)}}e.render=r.render||a,rc&&rc(e)}{let t=Ys(e);st();try{qa(e)}finally{ct(),t()}}}var sc=Symbol(),cc={get(e,t){return vt(e,`get`,``),t===sc?e:e[t]}};function lc(e){return{attrs:new Proxy(e.attrs,cc),slots:e.slots,emit:e.emit,expose:t=>{e.exposed=t||{}}}}function uc(e){return e.exposed?e.exposeProxy||=new Proxy(Cn(mn(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Da)return Da[n](e)},has(e,t){return t in e||t in Da}}):e.proxy}function dc(e,t=!0){return v(e)?e.displayName||e.name:e.name||t&&e.__name}function fc(e){return v(e)&&`__vccOpts`in e}var pc=(e,t)=>Mn(e,t,Qs);function mc(e,t,n){try{Ts(-1);let r=arguments.length;return r===2?x(t)&&!p(t)?Ds(t)?W(e,null,[t]):W(e,t):W(e,null,t):(r>3?n=Array.prototype.slice.call(arguments,2):r===3&&Ds(n)&&(n=[n]),W(e,t,n))}finally{Ts(1)}}function hc(){}function gc(e,t,n,r){let i=n[r];if(i&&_c(i,e))return i;let a=t();return a.memo=e.slice(),a.cacheIndex=r,n[r]=a}function _c(e,t){let n=e.memo;if(n.length!=t.length)return!1;for(let e=0;e0&&Ss&&Ss.push(e),!0}var vc=`3.5.47`,yc=a,bc=qn,xc=gr,Sc=vr,Cc={createComponentInstance:Ws,setupComponent:$s,renderComponentRoot:vo,setCurrentRenderingInstance:xr,isVNode:Ds,normalizeVNode:Is,getComponentPublicInstance:uc,ensureValidVNode:wa,pushWarningContext:Un,popWarningContext:Wn},wc=void 0,Tc=typeof window<`u`&&window.trustedTypes;if(Tc)try{wc=Tc.createPolicy(`vue`,{createHTML:e=>e})}catch{}var Ec=wc?e=>wc.createHTML(e):e=>e,Dc=`http://www.w3.org/2000/svg`,Oc=`http://www.w3.org/1998/Math/MathML`,kc=typeof document<`u`?document:null,Ac=kc&&kc.createElement(`template`),jc={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?kc.createElementNS(Dc,e):t===`mathml`?kc.createElementNS(Oc,e):n?kc.createElement(e,{is:n}):kc.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>kc.createTextNode(e),createComment:e=>kc.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>kc.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),i!==a&&(i=i.nextSibling););else{Ac.innerHTML=Ec(r===`svg`?`${e}`:r===`mathml`?`${e}`:e);let i=Ac.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Mc=`transition`,Nc=`animation`,Pc=Symbol(`_vtc`),Fc={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Ic=l({},ni,Fc),Lc=(e=>(e.displayName=`Transition`,e.props=Ic,e))((e,{slots:t})=>mc(ai,Bc(e),t)),Rc=(e,t=[])=>{p(e)?e.forEach(e=>e(...t)):e&&e(...t)},zc=e=>e?p(e)?e.some(e=>e.length>1):e.length>1:!1;function Bc(e){let t={};for(let n in e)n in Fc||(t[n]=e[n]);if(e.css===!1)return t;let{name:n=`v`,type:r,duration:i,enterFromClass:a=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:c=a,appearActiveClass:u=o,appearToClass:d=s,leaveFromClass:f=`${n}-leave-from`,leaveActiveClass:p=`${n}-leave-active`,leaveToClass:m=`${n}-leave-to`}=e,h=Vc(i),g=h&&h[0],_=h&&h[1],{onBeforeEnter:v,onEnter:y,onEnterCancelled:b,onLeave:x,onLeaveCancelled:S,onBeforeAppear:ee=v,onAppear:C=y,onAppearCancelled:te=b}=t,w=(e,t,n,r)=>{e._enterResolve=void 0,e._enterCancelled=r,Wc(e,t?d:s),Wc(e,t?u:o),n&&n()},T=(e,t)=>{e._leaveResolve=void 0,e._isLeaving=!1,Wc(e,f),Wc(e,m),Wc(e,p),t&&t()},ne=e=>(t,n)=>{let i=e?C:y,o=()=>{t._enterResolve===o&&w(t,e,n)};t._enterResolve=o,Rc(i,[t,o]),Gc(()=>{Wc(t,e?c:a),t._enterResolve===o&&(Uc(t,e?d:s),zc(i)||qc(t,r,g,o))})};return l(t,{onBeforeEnter(e){Rc(v,[e]),Uc(e,a),Uc(e,o)},onBeforeAppear(e){Rc(ee,[e]),Uc(e,c),Uc(e,u)},onEnter:ne(!1),onAppear:ne(!0),onLeave(e,t){e._isLeaving=!0;let n=()=>{e._leaveResolve===n&&T(e,t)};e._leaveResolve=n,Uc(e,f),e._enterCancelled?(Uc(e,p),Zc(e)):(Zc(e),Uc(e,p)),Gc(()=>{e._leaveResolve===n&&(Wc(e,f),Uc(e,m),zc(x)||qc(e,r,_,n))}),Rc(x,[e,n])},onEnterCancelled(e){w(e,!1,void 0,!0),Rc(b,[e])},onAppearCancelled(e){w(e,!0,void 0,!0),Rc(te,[e])},onLeaveCancelled(e){T(e),Rc(S,[e])}})}function Vc(e){if(e==null)return null;if(x(e))return[Hc(e.enter),Hc(e.leave)];{let t=Hc(e);return[t,t]}}function Hc(e){return me(e)}function Uc(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.add(t)),(e[Pc]||(e[Pc]=new Set)).add(t)}function Wc(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.remove(t));let n=e[Pc];n&&(n.delete(t),n.size||(e[Pc]=void 0))}function Gc(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}var Kc=0;function qc(e,t,n,r){let i=e._endId=++Kc,a=()=>{i===e._endId&&r()};if(n!=null)return setTimeout(a,n);let{type:o,timeout:s,propCount:c}=Jc(e,t);if(!o)return r();let l=o+`end`,u=0,d=()=>{e.removeEventListener(l,f),a()},f=t=>{t.target===e&&++u>=c&&d()};setTimeout(()=>{u(n[e]||``).split(`, `),i=r(`${Mc}Delay`),a=r(`${Mc}Duration`),o=Yc(i,a),s=r(`${Nc}Delay`),c=r(`${Nc}Duration`),l=Yc(s,c),u=null,d=0,f=0;t===Mc?o>0&&(u=Mc,d=o,f=a.length):t===Nc?l>0&&(u=Nc,d=l,f=c.length):(d=Math.max(o,l),u=d>0?o>l?Mc:Nc:null,f=u?u===Mc?a.length:c.length:0);let p=u===Mc&&/\b(?:transform|all)(?:,|$)/.test(r(`${Mc}Property`).toString());return{type:u,timeout:d,propCount:f,hasTransform:p}}function Yc(e,t){for(;e.lengthXc(t)+Xc(e[n])))}function Xc(e){return e===`auto`?0:Number(e.slice(0,-1).replace(`,`,`.`))*1e3}function Zc(e){return(e?e.ownerDocument:document).body.offsetHeight}function Qc(e,t,n){let r=e[Pc];r&&(t=(t?[t,...r]:[...r]).join(` `)),t==null?e.removeAttribute(`class`):n?e.setAttribute(`class`,t):e.className=t}var $c=Symbol(`_vod`),el=Symbol(`_vsh`),tl={name:`show`,beforeMount(e,{value:t},{transition:n}){e[$c]=e.style.display===`none`?``:e.style.display,n&&t?n.beforeEnter(e):nl(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:r}){!t!=!n&&(r?t?(r.beforeEnter(e),nl(e,!0),r.enter(e)):r.leave(e,()=>{nl(e,!1)}):nl(e,t))},beforeUnmount(e,{value:t}){nl(e,t)}};function nl(e,t){e.style.display=t?e[$c]:`none`,e[el]=!t}function rl(){tl.getSSRProps=({value:e})=>{if(!e)return{style:{display:`none`}}}}var il=Symbol(``);function al(e){let t=Ks();if(!t)return;let n=(n=e(t.proxy))=>{Array.from(document.querySelectorAll(`[data-v-owner="${t.uid}"]`)).forEach(e=>dl(e,n))},r={uid:String(t.uid),update:n};He(()=>r.update=void 0),t.ut=(e,t)=>{e&&(e[ol]=[t,r],cl(e),sl(e)),n()};let i=()=>{let r=e(t.proxy);t.ce?dl(t.ce,r):ul(t.subTree,r),n(r)};oa(()=>{lr(i)}),aa(()=>{Pr(i,a,{flush:`post`});let e=new MutationObserver(i);e.observe(t.subTree.el.parentNode,{childList:!0}),la(()=>e.disconnect())})}var ol=Symbol(``);function sl(e,t){let[n,r]=e[ol],i;if(r.update)for(let a=e;a&&a!==n;a=a.nextSibling)a.nodeType===1&&(!t||(t===!0||t.has(a))&&(a.getAttribute(`data-v-owner`)||r.uid)===r.uid)&&(a.setAttribute(`data-v-owner`,r.uid),i=r.update);return i}function cl(e){let t=e.parentNode;if(t){let n=t[ol];n||(n=t[ol]=new Set,new MutationObserver(ll).observe(t,{childList:!0})),n.add(e)}}function ll(e,t){let n=e[0].target,r=n[ol],i=new Set;for(let{addedNodes:t}of e)t.forEach(e=>i.add(e));let a=new Set;r.forEach(e=>{e.parentNode===n?i.size&&a.add(sl(e,i)):(r.delete(e),cl(e),a.add(sl(e,!0)))}),a.forEach(e=>e&&e()),r.size||(t.disconnect(),n[ol]=void 0)}function ul(e,t){if(e.shapeFlag&128){let n=e.suspense;e=n.activeBranch,n.pendingBranch&&!n.isHydrating&&n.effects.push(()=>{ul(n.activeBranch,t)})}for(;e.component;)e=e.component.subTree;if(e.shapeFlag&1&&e.el)dl(e.el,t);else if(e.type===R)e.children.forEach(e=>ul(e,t));else if(e.type===bs){let{el:n,anchor:r}=e;for(;n&&(dl(n,t),n!==r);)n=n.nextSibling}}function dl(e,t){if(e.nodeType===1){let n=e.style,r=``;for(let e in t){let i=Le(t[e]);n.setProperty(`--${e}`,i),r+=`--${e}: ${i};`}n[il]=r}}var fl=/(?:^|;)\s*display\s*:/;function pl(e,t,n){let r=e.style,i=y(n),a=!1;if(n&&!i){if(t){if(y(t))for(let e of t.split(`;`)){let t=e.slice(0,e.indexOf(`:`)).trim();n[t]??hl(r,t,``)}else for(let e in t)n[e]??hl(r,e,``)}for(let i in n){i===`display`&&(a=!0);let o=n[i];o==null?hl(r,i,``):yl(e,i,!y(t)&&t?t[i]:void 0,o)||hl(r,i,o)}}else if(i){if(t!==n){let e=r[il];e&&(n+=`;`+e),r.cssText=n,a=fl.test(n)}}else t&&e.removeAttribute(`style`);$c in e&&(i&&t===n||(e[$c]=a?r.display:``),e[el]&&(r.display=`none`))}var ml=/\s*!important$/;function hl(e,t,n){if(p(n))n.forEach(n=>hl(e,t,n));else if(n??=``,t.startsWith(`--`))ml.test(n)?e.setProperty(t,n.replace(ml,``),`important`):e.setProperty(t,n);else{let r=vl(e,t);ml.test(n)?e.setProperty(se(r),n.replace(ml,``),`important`):e[r]=n}}var gl=[`Webkit`,`Moz`,`ms`],_l={};function vl(e,t){let n=_l[t];if(n)return n;let r=E(t);if(r!==`filter`&&r in e)return _l[t]=r;r=ce(r);for(let n=0;nAl||=(jl.then(()=>Al=0),Date.now());function Nl(e,t){let n=e=>{if(!e._vts)e._vts=Date.now();else if(e._vts<=n.attached)return;let r=n.value;if(p(r)){let n=e.stopImmediatePropagation;e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0};let i=r.slice(),a=[e];for(let n=0;ne.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Fl=(e,t,n,r,i,a)=>{let o=i===`svg`;t===`class`?Qc(e,r,o):t===`style`?pl(e,n,r):s(t)?c(t)||El(e,t,n,r,a):(t[0]===`.`?(t=t.slice(1),1):t[0]===`^`?(t=t.slice(1),0):Il(e,t,r,o))?(Sl(e,t,r),e.tagName.includes(`-`)||t!==`value`&&t!==`checked`&&t!==`selected`||xl(e,t,r,o,a,t!==`value`)):e._isVueCE&&(Ll(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!y(r)))?Sl(e,E(t),r,a,t):(t===`true-value`?e._trueValue=r:t===`false-value`&&(e._falseValue=r),xl(e,t,r,o))};function Il(e,t,n,r){if(r)return!!(t===`innerHTML`||t===`textContent`||t in e&&Pl(t)&&v(n));if(t===`spellcheck`||t===`draggable`||t===`translate`||t===`autocorrect`||t===`sandbox`&&e.tagName===`IFRAME`||t===`form`||t===`list`&&e.tagName===`INPUT`||t===`type`&&e.tagName===`TEXTAREA`)return!1;if(t===`width`||t===`height`){let t=e.tagName;if(t===`IMG`||t===`VIDEO`||t===`CANVAS`||t===`SOURCE`)return!1}return Pl(t)&&y(n)?!1:t in e}function Ll(e,t){let n=e._def.props;if(!n)return!1;let r=E(t);return Array.isArray(n)?n.some(e=>E(e)===r):Object.keys(n).some(e=>E(e)===r)}var Rl={};function zl(e,t,n){let r=I(e,t);w(r)&&(r=l({},r,t));class i extends Hl{constructor(e){super(r,e,n)}}return i.def=r,i}var Bl=((e,t)=>zl(e,t,Ru)),Vl=typeof HTMLElement<`u`?HTMLElement:class{},Hl=class e extends Vl{constructor(e,t={},n=Lu){super(),this._def=e,this._props=t,this._createApp=n,this._isVueCE=!0,this._instance=null,this._app=null,this._nonce=this._def.nonce,this._connected=!1,this._resolved=!1,this._patching=!1,this._dirty=!1,this._numberProps=null,this._styleChildren=new WeakSet,this._styleAnchors=new WeakMap,this._ob=null,this.shadowRoot&&n!==Lu?this._root=this.shadowRoot:e.shadowRoot===!1?this._root=this:(this.attachShadow(l({},e.shadowRootOptions,{mode:`open`})),this._root=this.shadowRoot)}connectedCallback(){if(!this.isConnected)return;!this.shadowRoot&&!this._resolved&&this._parseSlots(),this._connected=!0;let t=this;for(;t&&=t.assignedSlot||t.parentNode||t.host;)if(t instanceof e){this._parent=t;break}this._instance||(this._resolved?this._mount(this._def):t&&t._pendingResolve?this._pendingResolve=t._pendingResolve.then(()=>{if(this._pendingResolve=void 0,this.isConnected)return this._resolveDef()}):this._resolveDef())}_setParent(e=this._parent){e&&(this._instance.parent=e._instance,this._inheritParentContext(e))}_inheritParentContext(e=this._parent){e&&this._app&&Object.setPrototypeOf(this._app._context.provides,e._instance.provides)}disconnectedCallback(){this._connected=!1,ar(()=>{this._connected||(this._ob&&=(this._ob.disconnect(),null),this._app&&this._app.unmount(),this._instance&&(this._instance.ce=void 0),this._app=this._instance=null,this._teleportTargets&&=(this._teleportTargets.clear(),void 0))})}_processMutations(e){for(let t of e)this._setAttr(t.attributeName)}_resolveDef(){if(this._pendingResolve)return this._pendingResolve;for(let e=0;e{this._resolved=!0,this._pendingResolve=void 0;let{props:n,styles:r}=e,i;if(n&&!p(n))for(let e in n){let t=n[e];(t===Number||t&&t.type===Number)&&(e in this._props&&(this._props[e]=me(this._props[e])),(i||=Object.create(null))[E(e)]=!0)}this._numberProps=i,this._resolveProps(e),this.shadowRoot&&this._applyStyles(r),this._connected&&this._mount(e)},t=this._def.__asyncLoader;if(t)return this._pendingResolve=t().then(t=>{t.configureApp=this._def.configureApp,e(this._def=t,!0)}),this._pendingResolve;e(this._def)}_mount(e){this._app=this._createApp(e),this._inheritParentContext(),e.configureApp&&e.configureApp(this._app),this._app._ceVNode=this._createVNode(),this._app.mount(this._root);let t=this._instance&&this._instance.exposed;if(t)for(let e in t)f(this,e)||Object.defineProperty(this,e,{get:()=>N(t[e])})}_resolveProps(e){let{props:t}=e,n=p(t)?t:Object.keys(t||{});for(let e of Object.keys(this))e[0]!==`_`&&n.includes(e)&&this._setProp(e,this[e]);for(let e of n.map(E))Object.defineProperty(this,e,{get(){return this._getProp(e)},set(t){this._setProp(e,t,!0,!this._patching)}})}_setAttr(e){if(e.startsWith(`data-v-`))return;let t=this.hasAttribute(e),n=t?this.getAttribute(e):Rl,r=E(e);t&&this._numberProps&&this._numberProps[r]&&(n=me(n)),this._setProp(r,n,!1,!0)}_getProp(e){return this._props[e]}_setProp(e,t,n=!0,r=!1){if(t!==this._props[e]&&(this._dirty=!0,t===Rl?delete this._props[e]:(this._props[e]=t,e===`key`&&this._app&&(this._app._ceVNode.key=t)),r&&this._instance&&this._update(),n)){let n=this._ob;n&&(this._processMutations(n.takeRecords()),n.disconnect()),t===!0?this.setAttribute(se(e),``):typeof t==`string`||typeof t==`number`?this.setAttribute(se(e),t+``):t||this.removeAttribute(se(e)),n&&n.observe(this,{attributes:!0})}}_update(){let e=this._createVNode();this._app&&(e.appContext=this._app._context),Fu(e,this._root)}_createVNode(){let e={};this.shadowRoot||(e.onVnodeMounted=e.onVnodeUpdated=this._renderSlots.bind(this));let t=W(this._def,l(e,this._props));return this._instance||(t.ce=e=>{this._instance=e,e.ce=this,e.isCE=!0;let t=(e,t)=>{this.dispatchEvent(new CustomEvent(e,w(t[0])?l({detail:t},t[0]):{detail:t}))};e.emit=(e,...n)=>{t(e,n),se(e)!==e&&t(se(e),n)},this._setParent()}),t}_applyStyles(e,t,n){if(!e)return;if(t){if(t===this._def||this._styleChildren.has(t))return;this._styleChildren.add(t)}let r=this._nonce,i=this.shadowRoot,a=n?this._getStyleAnchor(n)||this._getStyleAnchor(this._def):this._getRootStyleInsertionAnchor(i),o=null;for(let s=e.length-1;s>=0;s--){let c=document.createElement(`style`);r&&c.setAttribute(`nonce`,r),c.textContent=e[s],i.insertBefore(c,o||a),o=c,s===0&&(n||this._styleAnchors.set(this._def,c),t&&this._styleAnchors.set(t,c))}}_getStyleAnchor(e){if(!e)return null;let t=this._styleAnchors.get(e);return t&&t.parentNode===this.shadowRoot?t:(t&&this._styleAnchors.delete(e),null)}_getRootStyleInsertionAnchor(e){for(let t=0;t(delete e.props.mode,e))({name:`TransitionGroup`,props:l({},Ic,{tag:String,moveClass:String}),setup(e,{slots:t}){let n=Ks(),r=ei(),i,a,o,s,c=()=>(s===void 0&&(s=i.length>0&&ou(i[0].el,n.vnode.el,$l(e))),s);return sa(()=>{if(Xl.delete(n),!c()){i=[],o=void 0;return}let t=$l(e);i.forEach(Ql);let r=o&&au(o,n.vnode.el);o=void 0,i.forEach(e=>eu(e,r));let a=i.filter(tu);Zc(n.vnode.el),a.forEach(e=>{let n=e.el,r=n.style;Uc(n,t),r.transform=r.webkitTransform=r.transitionDuration=``;let i=n[Jl]=e=>{e&&e.target!==n||(!e||e.propertyName.endsWith(`transform`))&&(n.removeEventListener(`transitionend`,i),n[Jl]=null,Wc(n,t))};n.addEventListener(`transitionend`,i)}),i=[]}),()=>{let l=A(e),u=Bc(l),d=l.tag||R;if(i=[],s=void 0,a)for(let e=0;ee.willMove()&&e.item.contains(t));return n&&nu(n.item,n)}function ou(e,t,n){let r=e.cloneNode(),i=e[Pc];i&&i.forEach(e=>{e.split(/\s+/).forEach(e=>e&&r.classList.remove(e))}),n.split(/\s+/).forEach(e=>e&&r.classList.add(e)),r.style.display=`none`;let a=t.nodeType===1?t:t.parentNode;a.appendChild(r);let{hasTransform:o}=Jc(r);return a.removeChild(r),o}var su=e=>{let t=e.props[`onUpdate:modelValue`]||!1;return p(t)?e=>de(t,e):t};function cu(e){e.target.composing=!0}function lu(e){let t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event(`input`)))}var uu=Symbol(`_assign`),du=Symbol(`_initialValue`);function fu(e,t,n){return t&&(e=e.trim()),n&&(e=pe(e)),e}var q={created(e,{modifiers:{lazy:t,trim:n,number:r}},i){e.parentNode&&(e.type===`text`?e[du]=e.defaultValue.replace(/[\r\n]/g,``):e.type===`textarea`&&(e[du]=e.defaultValue.replace(/\r\n?/g,` +`))),e[uu]=su(i);let a=r||i.props&&i.props.type===`number`;Cl(e,t?`change`:`input`,t=>{t.target.composing||e[uu](fu(e.value,n,a))}),(n||a)&&Cl(e,`change`,()=>{e.value=fu(e.value,n,a)}),t||(Cl(e,`compositionstart`,cu),Cl(e,`compositionend`,lu),Cl(e,`change`,lu))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[du];delete e[du],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[uu](fu(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[uu]=su(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?pe(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)}},pu={deep:!0,created(e,t,n){e[uu]=su(n),Cl(e,`change`,()=>{let t=e._modelValue,n=yu(e),r=e.checked,i=e[uu];if(p(t)){let e=Me(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(bu(e,r))})},mounted:mu,beforeUpdate(e,t,n){e[uu]=su(n),mu(e,t,n)}};function mu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=Me(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=je(t,bu(e,!0))}e.checked!==i&&(e.checked=i)}var hu={created(e,{value:t},n){e.checked=je(t,n.props.value),e[uu]=su(n),Cl(e,`change`,()=>{e[uu](yu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[uu]=su(r),t!==n&&(e.checked=je(t,r.props.value))}},gu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,Cl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?pe(yu(e)):yu(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[uu](i)}finally{ar(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[uu]=su(r)},mounted(e,{value:t,modifiers:{number:n}}){vu(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[uu]=su(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&_u(t,r[1],r[0])||vu(e,t,n)}};function _u(e,t,n){if(!n||p(e))return je(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 vu(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;aString(e)===String(s)):Me(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(pe(s))}else if(je(yu(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function yu(e){return`_value`in e?e._value:e.value}function bu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var xu={created(e,t,n){Cu(e,t,n,null,`created`)},mounted(e,t,n){Cu(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){Cu(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){Cu(e,t,n,r,`updated`)}};function Su(e,t){switch(e){case`SELECT`:return gu;case`TEXTAREA`:return q;default:switch(t){case`checkbox`:return pu;case`radio`:return hu;default:return q}}}function Cu(e,t,n,r,i){let a=Su(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function wu(){q.getSSRProps=({value:e})=>({value:e}),hu.getSSRProps=({value:e},t)=>{if(t.props&&je(t.props.value,e))return{checked:!0}},pu.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&Me(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}},xu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=Su(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var Tu=[`ctrl`,`shift`,`alt`,`meta`],Eu={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)=>Tu.some(n=>e[`${n}Key`]&&!t.includes(n))},Du=(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{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||Ou[e]===r))return e(n)})},Au=l({patchProp:Fl},jc),ju,Mu=!1;function Nu(){return ju||=Go(Au)}function Pu(){return ju=Mu?ju:Ko(Au),Mu=!0,ju}var Fu=((...e)=>{Nu().render(...e)}),Iu=((...e)=>{Pu().hydrate(...e)}),Lu=((...e)=>{let t=Nu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Bu(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,zu(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),Ru=((...e)=>{let t=Pu().createApp(...e),{mount:n}=t;return t.mount=e=>{let t=Bu(e);if(t)return n(t,!0,zu(t))},t});function zu(e){if(e instanceof SVGElement)return`svg`;if(typeof MathMLElement==`function`&&e instanceof MathMLElement)return`mathml`}function Bu(e){return y(e)?document.querySelector(e):e}var Vu=!1,Hu=()=>{Vu||(Vu=!0,wu(),rl())},Uu=t({BaseTransition:()=>ai,BaseTransitionPropsValidators:()=>ni,Comment:()=>z,DeprecationTypes:()=>null,EffectScope:()=>ze,ErrorCodes:()=>Kn,ErrorTypeStrings:()=>bc,Fragment:()=>R,KeepAlive:()=>Ji,ReactiveEffect:()=>We,Static:()=>bs,Suspense:()=>as,Teleport:()=>Yr,Text:()=>ys,TrackOpTypes:()=>Nn,Transition:()=>Lc,TransitionGroup:()=>Zl,TriggerOpTypes:()=>Pn,VueElement:()=>Hl,assertNumber:()=>Gn,callWithAsyncErrorHandling:()=>Yn,callWithErrorHandling:()=>Jn,camelize:()=>E,capitalize:()=>ce,cloneVNode:()=>Ps,compatUtils:()=>null,compile:()=>Wu,computed:()=>pc,createApp:()=>Lu,createBlock:()=>H,createCommentVNode:()=>K,createElementBlock:()=>V,createElementVNode:()=>U,createHydrationRenderer:()=>Ko,createPropsRestProxy:()=>Wa,createRenderer:()=>Go,createSSRApp:()=>Ru,createSlots:()=>Sa,createStaticVNode:()=>Fs,createTextVNode:()=>G,createVNode:()=>W,customRef:()=>Tn,defineAsyncComponent:()=>Gi,defineComponent:()=>I,defineCustomElement:()=>zl,defineEmits:()=>Ma,defineExpose:()=>Na,defineModel:()=>Ia,defineOptions:()=>Pa,defineProps:()=>ja,defineSSRCustomElement:()=>Bl,defineSlots:()=>Fa,devtools:()=>xc,effect:()=>rt,effectScope:()=>Be,getCurrentInstance:()=>Ks,getCurrentScope:()=>Ve,getCurrentWatcher:()=>Rn,getTransitionRawChildren:()=>di,guardReactiveProps:()=>Ns,h:()=>mc,handleError:()=>Xn,hasInjectionContext:()=>Or,hydrate:()=>Iu,hydrateOnIdle:()=>Ri,hydrateOnInteraction:()=>Hi,hydrateOnMediaQuery:()=>Vi,hydrateOnVisible:()=>Bi,initCustomFormatter:()=>hc,initDirectivesForSSR:()=>Hu,inject:()=>Dr,isMemoSame:()=>_c,isProxy:()=>pn,isReactive:()=>un,isReadonly:()=>dn,isRef:()=>j,isRuntimeOnly:()=>ac,isShallow:()=>fn,isVNode:()=>Ds,markRaw:()=>mn,mergeDefaults:()=>Ha,mergeModels:()=>Ua,mergeProps:()=>zs,nextTick:()=>ar,nodeOps:()=>jc,normalizeClass:()=>D,normalizeProps:()=>Ce,normalizeStyle:()=>ve,onActivated:()=>Xi,onBeforeMount:()=>ia,onBeforeUnmount:()=>ca,onBeforeUpdate:()=>oa,onDeactivated:()=>Zi,onErrorCaptured:()=>pa,onMounted:()=>aa,onRenderTracked:()=>fa,onRenderTriggered:()=>da,onScopeDispose:()=>He,onServerPrefetch:()=>ua,onUnmounted:()=>la,onUpdated:()=>sa,onWatcherCleanup:()=>zn,openBlock:()=>B,patchProp:()=>Fl,popScopeId:()=>Cr,provide:()=>Er,proxyRefs:()=>Cn,pushScopeId:()=>Sr,queuePostFlushCb:()=>lr,reactive:()=>an,readonly:()=>sn,ref:()=>M,registerRuntimeCompiler:()=>ic,render:()=>Fu,renderList:()=>L,renderSlot:()=>Ca,resolveComponent:()=>ga,resolveDirective:()=>ya,resolveDynamicComponent:()=>va,resolveFilter:()=>null,resolveTransitionHooks:()=>si,setBlockTracking:()=>Ts,setDevtoolsHook:()=>Sc,setTransitionHooks:()=>ui,shallowReactive:()=>on,shallowReadonly:()=>cn,shallowRef:()=>_n,ssrContextKey:()=>kr,ssrUtils:()=>Cc,stop:()=>it,toDisplayString:()=>O,toHandlerKey:()=>le,toHandlers:()=>Ta,toRaw:()=>A,toRef:()=>kn,toRefs:()=>En,toValue:()=>xn,transformVNodeArgs:()=>ks,triggerRef:()=>bn,unref:()=>N,useAttrs:()=>za,useCssModule:()=>Gl,useCssVars:()=>al,useHost:()=>Ul,useId:()=>pi,useModel:()=>fo,useSSRContext:()=>Ar,useShadowRoot:()=>Wl,useSlots:()=>Ra,useTemplateRef:()=>hi,useTransitionState:()=>ei,vModelCheckbox:()=>pu,vModelDynamic:()=>xu,vModelRadio:()=>hu,vModelSelect:()=>gu,vModelText:()=>q,vShow:()=>tl,version:()=>vc,warn:()=>yc,watch:()=>Pr,watchEffect:()=>jr,watchPostEffect:()=>Mr,watchSyncEffect:()=>Nr,withAsyncContext:()=>Ga,withCtx:()=>P,withDefaults:()=>La,withDirectives:()=>F,withKeys:()=>ku,withMemo:()=>gc,withModifiers:()=>Du,withScopeId:()=>wr}),Wu=()=>{},Gu=class extends Error{status;body;constructor(e,t){super(t?.message??`HTTP ${e}`),this.status=e,this.body=t}get errors(){return Object.fromEntries(Object.entries(this.body?.errors??{}).map(([e,t])=>[e,t[0]]))}},J=JSON.parse(document.getElementById(`manager-boot`).textContent);function Ku(){let e=document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]+)/);return e?decodeURIComponent(e[1]):``}async function qu(e,t,n){let r=await fetch(t,{method:e,credentials:`same-origin`,headers:{Accept:`application/json`,"X-Requested-With":`XMLHttpRequest`,"X-XSRF-TOKEN":Ku(),...n===void 0?{}:{"Content-Type":`application/json`}},body:n===void 0?void 0:JSON.stringify(n)}),i=r.status===204?null:await r.json().catch(()=>null);if(!r.ok)throw new Gu(r.status,i);return i}async function Ju(e,t){let n=await fetch(e,{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"X-Requested-With":`XMLHttpRequest`,"X-XSRF-TOKEN":Ku()},body:t}),r=await n.json().catch(()=>null);if(!n.ok)throw new Gu(n.status,r);return r}var Y={get:e=>qu(`GET`,e),post:(e,t={})=>qu(`POST`,e,t),put:(e,t={})=>qu(`PUT`,e,t),delete:(e,t)=>qu(`DELETE`,e,t)};function Yu(e){let t=an({values:{...e},errors:{},busy:!1,async send(e,n){t.busy=!0,t.errors={};try{return await Y[e](n,t.values)}catch(e){if(e instanceof Gu&&e.status===422)return t.errors=e.errors,null;throw e}finally{t.busy=!1}}});return t}var Xu={Dashboard:`Dashboard`,"Log in":`Inloggen`,"Log out":`Uitloggen`,Email:`E-mailadres`,Password:`Wachtwoord`,"Keep me logged in":`Ingelogd blijven`,"Logging in…":`Bezig met inloggen…`,"Log in to manage the site.":`Log in om de site te beheren.`,"My account":`Mijn account`,Name:`Naam`,"Email address":`E-mailadres`,"What you may do":`Wat je mag`,"Super admin: everything":`Super admin: alles`,"Not in a group yet":`Nog in geen groep`,"New password":`Nieuw wachtwoord`,"Leave empty to keep the password you have.":`Laat leeg om je wachtwoord te houden.`,"Current password":`Huidig wachtwoord`,"At least 12 characters.":`Minstens 12 tekens.`,"New password, once more":`Nieuw wachtwoord, nogmaals`,Save:`Opslaan`,"Saving…":`Bezig met opslaan…`,"Saved.":`Opgeslagen.`,Look:`Uiterlijk`,Theme:`Thema`,Posts:`Berichten`,"New post":`Nieuw bericht`,Title:`Titel`,Status:`Status`,Category:`Categorie`,Edit:`Bewerken`,Delete:`Verwijderen`,"Put online":`Online zetten`,"Take offline":`Offline halen`,Draft:`Concept`,Scheduled:`Ingepland`,Published:`Gepubliceerd`,"Are you sure?":`Weet je het zeker?`,"No posts yet.":`Nog geen berichten.`,"Address (slug)":`Adres (slug)`,Summary:`Samenvatting`,"Text (Markdown)":`Tekst (Markdown)`,"Cover image":`Omslagafbeelding`,"Tags (comma separated)":`Tags (met komma's)`,Featured:`Uitgelicht`,Publish:`Publiceren`,"Publish at":`Publiceren op`,Menu:`Menu`,"Click the part of the picture that must stay in view.":`Klik op het deel van de foto dat in beeld moet blijven.`,"Focus point":`Scherpstelpunt`,Clear:`Wissen`,Formatting:`Opmaak`,Bold:`Vet`,Italic:`Cursief`,Heading:`Kop`,List:`Lijst`,Quote:`Citaat`,Link:`Link`,bold:`vet`,italic:`cursief`,text:`tekst`,Photo:`Foto`,Write:`Schrijven`,Preview:`Voorbeeld`,History:`Geschiedenis`,Now:`Nu`,"Put back":`Terugzetten`,"Put this version back? The text now is kept in the history.":`Deze versie terugzetten? De tekst van nu blijft bewaard in de geschiedenis.`,"The earlier version is back.":`De eerdere versie is terug.`,New:`Nieuw`,"New page":`Nieuwe pagina`,"Description for search engines":`Omschrijving voor zoekmachines`,"One per line.":`Eén per regel.`,"Show everything":`Alles tonen`,"Simple view":`Simpele weergave`,"Loading…":`Laden…`,"You may not open this page.":`Je mag deze pagina niet openen.`,"Something went wrong. Try again.":`Er ging iets mis. Probeer het opnieuw.`,"This page has no screen in the manager yet.":`Deze pagina heeft nog geen scherm in de manager.`,"Go to the dashboard":`Naar het dashboard`,"The page expired. Reload it and try again.":`De pagina is verlopen. Laad hem opnieuw en probeer het nog eens.`,Back:`Terug`,"Start screen":`Startscherm`,"The dashboard":`Het dashboard`,Primary:`Primair`,"Primary group":`Primaire groep`,"Where accounts with this as their primary group land when they open the manager.":`Waar accounts met dit als primaire groep landen als ze de manager openen.`,"The primary group is the label of the account and sets its start screen. What it may do is everything its groups allow together.":`De primaire groep is het label van het account en bepaalt het startscherm. Wat het account mag, is alles wat al zijn groepen samen toestaan.`,Settings:`Instellingen`,"Refresh now":`Nu verversen`,"Try it":`Proberen`,"Trying…":`Bezig met proberen…`,"Save first: it tries what is saved.":`Sla eerst op: er wordt geprobeerd met wat is opgeslagen.`,"The check could not be run.":`De controle kon niet worden uitgevoerd.`,"Refreshed.":`Ververst.`,"These parts need new tables:":`Deze onderdelen hebben nieuwe tabellen nodig:`,"Run php artisan migrate on the server.":`Draai php artisan migrate op de server.`,"The changes are saved, but the file that makes them work at once could not be written (bootstrap/cache). They work after Refresh now, or when that folder may be written.":`De wijzigingen zijn opgeslagen, maar het bestand dat ze direct laat werken kon niet geschreven worden (bootstrap/cache). Ze werken na Nu verversen, of als die map beschreven mag worden.`,"A change works at once and is kept in the database.":`Een wijziging werkt direct en wordt in de database bewaard.`,"It is also written into the .env file.":`Hij wordt ook in het .env-bestand geschreven.`,"The .env file may not be written here, so only the database is used.":`Het .env-bestand mag hier niet beschreven worden, dus alleen de database wordt gebruikt.`,"Set. Type to replace it.":`Ingesteld. Typ om te vervangen.`,"Keep what is saved":`Bewaar wat is opgeslagen`,"Back to what the config says":`Terug naar wat de config zegt`,"Your password":`Je wachtwoord`,"Keys, passwords and addresses of integrations are only changed after you type your own password.":`Sleutels, wachtwoorden en adressen van koppelingen worden alleen gewijzigd nadat je je eigen wachtwoord typt.`,Accounts:`Accounts`,"New account":`Nieuw account`,you:`jij`,"Super admin":`Super admin`,Groups:`Groepen`,Cancel:`Annuleren`,"New group":`Nieuwe groep`,Description:`Omschrijving`,accounts:`accounts`,"Categories and tags":`Categorieën en tags`,Categories:`Categorieën`,Tags:`Tags`,Add:`Toevoegen`,Rename:`Hernoemen`,"New name":`Nieuwe naam`,Pages:`Pagina's`,Reviews:`Reviews`,"Nothing here yet.":`Hier is nog niets.`,Previous:`Vorige`,Next:`Volgende`,Media:`Media`,"Choose an image":`Kies een afbeelding`,"No images yet.":`Nog geen afbeeldingen.`,"Uploaded.":`Geüpload.`,Upload:`Uploaden`,"Uploading…":`Bezig met uploaden…`,"This file is in use. Delete it anyway?":`Dit bestand is in gebruik. Toch verwijderen?`,"Largest file":`Grootste bestand`,"Alternative text":`Alternatieve tekst`,Used:`Gebruikt`,"No files yet.":`Nog geen bestanden.`,Choose:`Kiezen`,"Audit log":`Auditlog`,"Addresses banned":`Geblokkeerde adressen`,"Logins (24 h)":`Logins (24 u)`,"Failed logins (24 h)":`Mislukte logins (24 u)`,"Refused (24 h)":`Geweigerd (24 u)`,all:`alles`,logins:`logins`,failed:`mislukt`,actions:`acties`,viewed:`bekeken`,refused:`geweigerd`,bans:`blokkades`,Search:`Zoeken`,Account:`Account`,Everyone:`Iedereen`,Filter:`Filteren`,Someone:`Iemand`,banned:`geblokkeerd`,Ban:`Blokkeren`,Bans:`Blokkades`,"Minutes (0 = until lifted)":`Minuten (0 = tot opgeheven)`,Reason:`Reden`,"Whole site":`Hele site`,"No bans.":`Geen blokkades.`,automatic:`automatisch`,"whole site":`hele site`,hits:`pogingen`,Lift:`Opheffen`,Rules:`Regels`,"until lifted":`tot opgeheven`,"Ban an address by itself after too many failed logins":`Een adres zelf blokkeren na te veel mislukte logins`,"Failed logins":`Mislukte logins`,"Within minutes":`Binnen minuten`,"Ban for minutes (0 = until lifted)":`Blokkeren voor minuten (0 = tot opgeheven)`,"Keep the log (days)":`Log bewaren (dagen)`,"Notes about addresses":`Notities over adressen`,Group:`Groep`,Note:`Notitie`,Statistics:`Statistieken`,"compared with":`vergeleken met`,Visitors:`Bezoekers`,Visits:`Bezoeken`,"Page views":`Paginaweergaven`,"Average time":`Gemiddelde tijd`,"Bounce rate":`Bouncepercentage`,Channels:`Kanalen`,Sources:`Bronnen`,Countries:`Landen`,Devices:`Apparaten`,Browsers:`Browsers`,Systems:`Systemen`,Direct:`Direct`,"When people visit":`Wanneer mensen komen`,Programs:`Programma's`,Download:`Downloaden`,Sharing:`Delen`,"Posts are shared for real.":`Berichten worden echt gedeeld.`,'Dry run: nothing is sent to the networks. Turn on "Post for real" under Settings when the site is live.':`Proefrun: er wordt niets naar de netwerken gestuurd. Zet "Echt posten" aan bij Instellingen als de site live is.`,Connected:`Gekoppeld`,"Not connected":`Niet gekoppeld`,"Fill in under Settings:":`Vul in bij Instellingen:`,"Return address for the app":`Terugkeeradres voor de app`,Connect:`Koppel`,"Connect again":`Koppel opnieuw`,Disconnect:`Ontkoppel`,"Recently shared":`Onlangs gedeeld`,"Nothing has been shared yet.":`Er is nog niets gedeeld.`,"Dry run":`Proefrun`,Shared:`Gedeeld`,Failed:`Mislukt`,"The account is connected.":`Het account is gekoppeld.`,"The network did not give permission, or it was cancelled.":`Het netwerk gaf geen toestemming, of het is afgebroken.`,"Connecting did not complete. Try again.":`Koppelen is niet gelukt. Probeer het opnieuw.`,"The account is disconnected. What was shared stays where it is.":`Het account is ontkoppeld. Wat gedeeld is, blijft staan.`,Share:`Delen`,"Share now":`Nu delen`,"Dry run: nothing was sent.":`Proefrun: er is niets verstuurd.`,"Shared.":`Gedeeld.`,View:`Bekijk`,"Dry run: nothing is sent to the networks.":`Proefrun: er wordt niets naar de netwerken gestuurd.`,"Name of the service":`Naam van de dienst`,'What you call it, for example "Roof extensions".':`Hoe je het noemt, bijvoorbeeld "Dakkapellen".`,"Short description":`Korte beschrijving`,"One sentence that shows under the name.":`Eén zin die onder de naam staat.`,"The full story":`Het hele verhaal`,"What you do and how you work. This is the text on the page of this service.":`Wat je doet en hoe je werkt. Dit is de tekst op de pagina van deze dienst.`,"Main photo":`Hoofdfoto`,"What you do":`Wat je doet`,"Short lines, one per line.":`Korte regels, één per regel.`,"Questions people ask":`Vragen die mensen stellen`,"Add the questions you hear often, with your answer.":`Zet hier de vragen die je vaak hoort, met je antwoord.`,"Show this on my website":`Laat dit zien op mijn website`,"Name of the job":`Naam van de klus`,'For example "New kitchen in a farmhouse".':`Bijvoorbeeld "Nieuwe keuken in een boerderij".`,"What kind of work was it?":`Wat voor werk was het?`,Town:`Plaats`,"The town only, never the street.":`Alleen de plaats, nooit de straat.`,"Year it was finished":`Jaar waarin het klaar was`,"What happened":`Wat er gebeurd is`,"A few sentences about the job. Leave an empty line between paragraphs.":`Een paar zinnen over de klus. Laat een lege regel tussen alinea's.`,"The customer said these photos may be on the website":`De klant heeft gezegd dat deze foto's op de website mogen`,"Show this on the home page":`Laat dit zien op de voorpagina`,"Who said it":`Wie het zei`,"Where they live or what they do":`Waar ze wonen of wat ze doen`,'For example "Utrecht" or "owner of a bakery".':`Bijvoorbeeld "Utrecht" of "eigenaar van een bakkerij".`,"What they said":`Wat ze zeiden`,"Their words, as they gave them.":`Hun woorden, zoals ze ze gaven.`,"What the button says":`Wat er op de knop staat`,"Where it goes":`Waar het naartoe gaat`,"A page of your website, like /contact, or a full web address.":`Een pagina van je website, zoals /contact, of een volledig webadres.`,"Open it in a new tab":`Open het in een nieuw tabblad`,'For example "Facebook".':`Bijvoorbeeld "Facebook".`,"Web address of your page":`Webadres van je pagina`,"Name of your business":`Naam van je bedrijf`,"Your first name":`Je voornaam`,'Used on buttons such as "Call Alex".':`Staat op knoppen zoals "Bel Alex".`,"Your phone number":`Je telefoonnummer`,"As you want people to read it. It shows on every page, and behind the Call button.":`Zoals je wilt dat mensen het lezen. Het staat op elke pagina en achter de knop Bel.`,"Your WhatsApp number":`Je nummer voor WhatsApp`,"Leave it empty and there are no WhatsApp buttons on the website.":`Laat je het leeg, dan staan er geen WhatsApp-knoppen op de website.`,"Your mail address":`Je mailadres`,"It is never printed on the website, so spammers cannot find it. A visitor gets it by pressing a button.":`Het staat nergens leesbaar op de website, zodat spammers het niet vinden. Een bezoeker krijgt het door op een knop te drukken.`,"Street and number":`Straat en huisnummer`,"Chamber of Commerce number":`KvK-nummer`,"VAT number":`Btw-nummer`,"As on your invoices. Not sure? Leave it empty.":`Zoals op je facturen. Niet zeker? Laat het leeg.`,"When people can reach you":`Wanneer mensen je kunnen bereiken`,"One line per day or group of days, as you want it read.":`Eén regel per dag of groep dagen, zoals je het wilt laten lezen.`,"Towns where you work":`Plaatsen waar je werkt`,"One town per line.":`Eén plaats per regel.`,"What customers say":`Wat klanten zeggen`,"Customer review":`Review van een klant`,"Our jobs":`Onze klussen`,Job:`Klus`,"Buttons at the top":`Knoppen bovenaan`,Button:`Knop`,"Your pages on other sites":`Je pagina's op andere sites`,"About your business":`Over je bedrijf`,"What it cost":`Wat het kostte`,"What was built, and what it cost":`Wat er gebouwd is, en wat het kostte`,"The work":`Het werk`,"The AI model":`Het AI-model`,Hosting:`Hosting`,":hours hours at :rate an hour":`:hours uur à :rate per uur`,":count tokens":`:count tokens`,":amount a year, from :day":`:amount per jaar, vanaf :day`,Total:`Totaal`,":percent% discount on the work, until :day":`:percent% korting op het werk, tot :day`,"To pay":`Te betalen`,":count pieces of work have no hours yet.":`Bij :count stukken werk staan nog geen uren.`,":count pieces of work could not be priced yet.":`Voor :count stukken werk was nog geen prijs te bepalen.`,"No work has been recorded yet.":`Er is nog geen werk vastgelegd.`,"Not released yet":`Nog niet uitgebracht`,"Priced with the fixed rates of the site.":`Geprijsd met de vaste tarieven van de site.`,"Priced with the price of each day, and for some rows with the fixed rates of the site.":`Geprijsd met de prijs van elke dag, en voor een deel met de vaste tarieven van de site.`,"Priced with the price list and the euro rate of the day of each row.":`Geprijsd met de prijslijst en de eurokoers van de dag van elke regel.`,Numbers:`Cijfers`,Period:`Periode`,"The same as :period.":`Evenveel als :period.`,":count more than :period.":`:count meer dan :period.`,":count fewer than :period.":`:count minder dan :period.`,"Nothing has been counted in this period yet. As soon as people visit the site, you will see it here.":`In deze periode is er nog niets geteld. Zodra mensen de site bezoeken, zie je het hier.`,"Together they looked at :count pages.":`Samen bekeken ze :count pagina's.`,"Requests through the site":`Aanvragen via de site`,":count became a job.":`:count werd een klus.`,":count still wait for an answer.":`:count wachten nog op antwoord.`,"To the requests":`Naar de aanvragen`,"Taps on Call":`Tikken op Bel`,"Taps on WhatsApp":`Tikken op WhatsApp`,"Visitors per month":`Bezoekers per maand`,"Visitors per day":`Bezoekers per dag`,"Busiest: :when, with :count visitors.":`Het drukst: :when, met :count bezoekers.`,"Most viewed pages":`Meest bekeken pagina's`,":count times":`:count keer`,"How people find you":`Hoe mensen je vinden`,"What the requests were about":`Waar de aanvragen over gingen`,"Most read articles":`Meest gelezen artikelen`,":count messages of spam or advertising were kept away from you.":`:count berichten van spam of reclame zijn bij je weggehouden.`,"Visitors are counted without cookies. Search robots, and you yourself when you are logged in, are not counted.":`Bezoekers worden geteld zonder cookies. Zoekrobots en jijzelf, als je bent ingelogd, tellen niet mee.`,"Need help? Message :name":`Hulp nodig? App :name`,"Need help?":`Hulp nodig?`,"View the site":`Bekijk de site`,Updates:`Updates`,"What changed on your website":`Wat er op je website veranderd is`,"No changes recorded yet.":`Er is nog niets bijgehouden.`,Requests:`Aanvragen`,Waiting:`Wachtend`,Handled:`Afgehandeld`,Other:`Overig`,Spam:`Spam`,"Note saved.":`Notitie bewaard.`,"Moved.":`Verplaatst.`,"Blocked.":`Geblokkeerd.`,"The block is lifted.":`De blokkade is opgeheven.`,"This could not be done.":`Dit kon niet worden gedaan.`,"The mail about this request could not be sent.":`De mail over deze aanvraag kon niet worden verstuurd.`,Where:`Waar`,Call:`Bel`,Mail:`Mail`,"Back to waiting":`Terug naar wachtend`,"It became a job":`Het is een klus geworden`,"No job":`Geen klus`,"A note for yourself":`Een notitie voor jezelf`,Screening:`Screening`,"It is a real request":`Dit is een echte aanvraag`,"This is not a request":`Dit is geen aanvraag`,"Block this address":`Blokkeer dit e-mailadres`,"Block its domain":`Blokkeer het domein`,"Block this number":`Blokkeer dit nummer`,"Block the sender address":`Blokkeer het adres van de afzender`,"Blocked senders":`Geblokkeerde afzenders`,until:`tot`,"What it brought in":`Wat het opleverde`,"The last :days days":`De laatste :days dagen`,requests:`aanvragen`,"became a job":`werden een klus`,"kept away by the screening":`tegengehouden door de screening`,"Ways in":`Manieren om binnen te komen`,About:`Waarover`,"Where the buttons are pressed":`Waar op de knoppen wordt gedrukt`,Remove:`Verwijderen`,"Add a picture":`Een foto toevoegen`,Open:`Openen`,"Created.":`Aangemaakt.`,"Deleted.":`Verwijderd.`,Language:`Taal`,"What this account sees":`Wat dit account ziet`,"What its rights give":`Wat zijn rechten geven`,"The simple manager":`De simpele manager`,"The whole manager":`De hele manager`,"Hi :name!":`Hoi :name!`,"What would you like to do today? Take your time and pick one.":`Wat wil je vandaag doen? Neem je tijd en kies er één.`,"Show the tour the next time this account opens the manager":`Toon de rondleiding de volgende keer dat dit account de manager opent`,"Hi :name! Welcome!":`Hoi :name! Welkom!`,"I will show you around in a few small steps. Looking around cannot break anything, and you can stop whenever you like: press the cross.":`Ik laat je in een paar kleine stapjes zien waar alles staat. Rondkijken kan niks stuk maken, en je kunt altijd stoppen: druk op het kruisje.`,"This is the menu":`Dit is het menu`,"Everything you can do lives here. Press a name and you are there.":`Alles wat je kunt doen staat hier. Druk op een naam en je bent er.`,"Your start page":`Je startpagina`,"Lost? Press Dashboard, at the top of the menu, and you are back here. Nice and calm.":`Even kwijt? Druk op Dashboard, bovenaan het menu, en je bent weer hier. Lekker rustig.`,"Write news":`Nieuws schrijven`,"Here you write articles and news for your website. Keep it as a draft until you are happy, then put it online.":`Hier schrijf je berichten en nieuws voor je website. Laat het een concept tot je tevreden bent, en zet het dan online.`,"Your photos":`Je foto's`,"All photos and files live here. Upload them once and use them in posts and pages.":`Alle foto's en bestanden staan hier. Upload ze één keer en gebruik ze in berichten en pagina's.`,"Your pages":`Je pagina's`,"Change the texts and photos of the pages of your website here.":`Pas hier de teksten en foto's van de pagina's van je website aan.`,"Changed your mind?":`Bedacht je het anders?`,"Every time you save a post or a page I keep the old version. You can always put an earlier one back.":`Elke keer dat je een bericht of pagina bewaart, bewaar ik de oude versie. Je kunt altijd een eerdere terugzetten.`,"Something went wrong?":`Gaat er iets mis?`,"A message tells you what. Read it, fix it and try again. Nothing is deleted without asking you first.":`Een melding vertelt wat. Lees hem, los het op en probeer het nog eens. Er wordt niks verwijderd zonder dat ik het eerst vraag.`,"Your own corner":`Je eigen hoekje`,"Here you choose your language and your colours, and change your password.":`Hier kies je je taal en je kleuren, en verander je je wachtwoord.`,"That is it!":`Dat was het!`,"Want to see this again? Press Show the tour in the menu. Have fun!":`Wil je dit nog eens zien? Druk op Rondleiding tonen in het menu. Veel plezier!`,"Stop the tour":`Rondleiding stoppen`,Tour:`Rondleiding`,"The tour":`De rondleiding`,"Show the tour":`Rondleiding tonen`,Done:`Klaar`},Zu={};function Qu(e){Zu=e.toLowerCase().startsWith(`nl`)?Xu:{}}function X(e,t){let n=Zu[e]??e;return t?n.replace(/:(\w+)/g,(e,n)=>n in t?String(t[n]):e):n}var $u=[`d`],ed=I({__name:`Icon`,props:{name:{},big:{type:Boolean}},setup(e){let t={home:`M3 11l9-8 9 8v9a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z`,file:`M7 3h7l5 5v13H7zM14 3v5h5`,image:`M4 5h16v14H4zM4 16l5-5 4 4 3-3 4 4M9 9h.01`,users:`M16 20v-1a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v1M10 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6M20 20v-1a3 3 0 0 0-2-2.8M16 5.2a3 3 0 0 1 0 5.6`,group:`M3 7h18v12H3zM8 7V5h8v2`,chart:`M4 20V10M10 20V4M16 20v-8M22 20H2`,shield:`M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z`,star:`M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z`,tag:`M3 12V4h8l10 10-8 8zM7.5 8h.01`,link:`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`,cog:`M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.4-2.3.9a7 7 0 0 0-2-1.2L14.2 3h-4l-.4 2.6a7 7 0 0 0-2 1.2l-2.3-.9-2 3.4 2 1.5A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.5 2 3.4 2.3-.9a7 7 0 0 0 2 1.2l.4 2.6h4l.4-2.6a7 7 0 0 0 2-1.2l2.3.9 2-3.4-2-1.5c.1-.4.1-.8.1-1.2`};return(n,r)=>e.name&&t[e.name]?(B(),V(`svg`,{key:0,class:D(e.big?`h-8 w-8 shrink-0`:`h-4 w-4 shrink-0`),viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`1.8`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`},[U(`path`,{d:t[e.name]},null,8,$u)],2)):K(``,!0)}}),td=[`href`],Z=I({__name:`Link`,props:{href:{}},setup(e){function t(e,t){e.metaKey||e.ctrlKey||e.shiftKey||e.button!==0||(e.preventDefault(),c4(t))}return(n,r)=>(B(),V(`a`,{href:e.href,onClick:r[0]||=n=>t(n,e.href)},[Ca(n.$slots,`default`)],8,td))}}),nd={key:0,class:`mx-auto max-w-3xl pt-4`},rd={class:`font-display text-3xl font-bold`},id={class:`mb-8 mt-2 text-lg text-muted`},ad={class:`grid gap-4 sm:grid-cols-2`},od={class:`flex items-start justify-between`},sd={key:0,class:`m-badge`,"aria-hidden":`true`},cd={class:`text-xl font-bold`},ld={key:0,class:`text-muted`},ud={key:1,class:`text-muted`},dd={key:0,class:`mt-8 flex flex-wrap items-center gap-3`},fd=[`href`],pd=[`href`],md={class:`font-display mb-6 text-2xl font-bold`},hd={class:`mb-4 text-muted`},gd={class:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`},_d=I({__name:`Dashboard`,props:{navigation:{},facts:{},help:{},site:{}},setup(e){function t(e){return e.icon?e.icon:e.href.endsWith(`/media`)?`image`:e.href.endsWith(`/posts`)||e.href.endsWith(`/pages`)?`file`:`star`}let n=J.view===`simple`,r=(J.user?.name??``).split(` `)[0];return(i,a)=>n?(B(),V(`div`,nd,[U(`h1`,rd,O(N(X)(`Hi :name!`,{name:N(r)})),1),U(`p`,id,O(N(X)(`What would you like to do today? Take your time and pick one.`)),1),U(`div`,ad,[(B(!0),V(R,null,L(e.navigation,n=>(B(),H(Z,{key:n.href,href:n.href,class:`m-card m-tile`},{default:P(()=>[U(`span`,od,[W(ed,{name:t(n),big:``,class:`text-brand`},null,8,[`name`]),e.facts?.[n.href]?.badge?(B(),V(`span`,sd,O(e.facts[n.href].badge),1)):K(``,!0)]),U(`span`,cd,O(N(X)(n.label)),1),e.facts?.[n.href]?.summary?(B(),V(`span`,ld,O(e.facts[n.href].summary),1)):n.hint?(B(),V(`span`,ud,O(N(X)(n.hint)),1)):K(``,!0)]),_:2},1032,[`href`]))),128))]),e.help||e.site?(B(),V(`div`,dd,[e.help?(B(),V(`a`,{key:0,href:e.help.link,target:`_blank`,rel:`noopener`,class:`m-btn m-btn-secondary`},O(e.help.name?N(X)(`Need help? Message :name`,{name:e.help.name}):N(X)(`Need help?`)),9,fd)):K(``,!0),e.site?(B(),V(`a`,{key:1,href:e.site,target:`_blank`,rel:`noopener`,class:`m-btn m-btn-secondary`},O(N(X)(`View the site`)),9,pd)):K(``,!0)])):K(``,!0)])):(B(),V(R,{key:1},[U(`h1`,md,O(N(X)(`Dashboard`)),1),U(`p`,hd,O(N(J).user?.name),1),U(`div`,gd,[(B(!0),V(R,null,L(e.navigation,e=>(B(),H(Z,{key:e.href,href:e.href,class:`m-card block p-5 font-semibold transition hover:border-brand`},{default:P(()=>[G(O(N(X)(e.label)),1)]),_:2},1032,[`href`]))),128))])],64))}}),vd={class:`m-card max-w-xl p-6`},yd={class:`text-sm`},bd=I({__name:`Fallback`,setup(e){return(e,t)=>(B(),V(`div`,vd,[U(`p`,yd,O(N(X)(`This page has no screen in the manager yet.`)),1),W(Z,{href:N(J).base,class:`m-btn m-btn-secondary mt-4`},{default:P(()=>[G(O(N(X)(`Go to the dashboard`)),1)]),_:1},8,[`href`])]))}}),xd={class:`grid min-h-screen place-items-center px-4`},Sd=[`src`],Cd={class:`font-display text-2xl font-bold`},wd={class:`mt-1 text-sm text-muted`},Td={class:`mt-6`},Ed={for:`email`,class:`m-label`},Dd={key:0,class:`m-error`},Od={class:`mt-4`},kd={for:`password`,class:`m-label`},Ad={key:0,class:`m-error`},jd={key:0,class:`mt-4`},Md={key:0,class:`m-error`},Nd={key:1,class:`mt-4`},Pd=[`for`],Fd=[`id`,`onUpdate:modelValue`,`type`,`autocomplete`,`required`],Id={key:0,class:`m-error`},Ld={class:`mt-4 flex items-center gap-2 text-sm text-muted`},Rd=[`disabled`],zd=I({__name:`Login`,setup(e){let t=J.login_fields??[],n=Yu({email:``,password:``,remember:!1,...Object.fromEntries(t.map(e=>[e.name,``]))}),r=M(null),i;aa(()=>{let e=t.find(e=>e.type===`turnstile`);if(!e)return;let a=()=>{i=window.turnstile.render(r.value,{sitekey:e.site_key,callback:t=>n.values[e.name]=t})};if(window.turnstile)a();else{let e=document.createElement(`script`);e.src=`https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`,e.async=!0,e.onload=a,document.head.appendChild(e)}});async function a(){let e=await n.send(`post`,J.base+`/login`);e?window.location.assign(e.redirect):(n.values.password=``,i!==void 0&&window.turnstile.reset(i),t.filter(e=>e.type===`turnstile`).forEach(e=>n.values[e.name]=``))}return(e,i)=>(B(),V(`div`,xd,[U(`form`,{class:`m-card w-full max-w-sm p-7`,onSubmit:Du(a,[`prevent`])},[N(J).logo?(B(),V(`img`,{key:0,src:N(J).logo,alt:``,class:`mb-4 h-9 w-auto`},null,8,Sd)):K(``,!0),U(`h1`,Cd,O(N(J).name),1),U(`p`,wd,O(N(X)(`Log in to manage the site.`)),1),U(`div`,Td,[U(`label`,Ed,O(N(X)(`Email`)),1),F(U(`input`,{id:`email`,"onUpdate:modelValue":i[0]||=e=>N(n).values.email=e,type:`email`,autocomplete:`username`,required:``,autofocus:``,class:`m-input`},null,512),[[q,N(n).values.email]]),N(n).errors.email?(B(),V(`p`,Dd,O(N(n).errors.email),1)):K(``,!0)]),U(`div`,Od,[U(`label`,kd,O(N(X)(`Password`)),1),F(U(`input`,{id:`password`,"onUpdate:modelValue":i[1]||=e=>N(n).values.password=e,type:`password`,autocomplete:`current-password`,required:``,class:`m-input`},null,512),[[q,N(n).values.password]]),N(n).errors.password?(B(),V(`p`,Ad,O(N(n).errors.password),1)):K(``,!0)]),(B(!0),V(R,null,L(N(t),e=>(B(),V(R,{key:e.name},[e.type===`turnstile`?(B(),V(`div`,jd,[U(`div`,{ref_for:!0,ref:e=>r.value=e},null,512),N(n).errors[e.name]?(B(),V(`p`,Md,O(N(n).errors[e.name]),1)):K(``,!0)])):(B(),V(`div`,Nd,[U(`label`,{for:`login-`+e.name,class:`m-label`},O(N(X)(e.label??e.name)),9,Pd),F(U(`input`,{id:`login-`+e.name,"onUpdate:modelValue":t=>N(n).values[e.name]=t,type:e.type===`password`||e.type===`number`?e.type:`text`,autocomplete:e.autocomplete,required:e.required,class:`m-input`},null,8,Fd),[[xu,N(n).values[e.name]]]),N(n).errors[e.name]?(B(),V(`p`,Id,O(N(n).errors[e.name]),1)):K(``,!0)]))],64))),128)),U(`label`,Ld,[F(U(`input`,{"onUpdate:modelValue":i[2]||=e=>N(n).values.remember=e,type:`checkbox`},null,512),[[pu,N(n).values.remember]]),G(` `+O(N(X)(`Keep me logged in`)),1)]),U(`button`,{type:`submit`,class:`m-btn m-btn-primary mt-6 w-full justify-center`,disabled:N(n).busy},O(N(n).busy?N(X)(`Logging in…`):N(X)(`Log in`)),9,Rd)],32)]))}}),Bd={class:`m-card max-h-[85vh] w-full max-w-3xl overflow-y-auto p-5`,role:`dialog`,"aria-modal":`true`},Vd={class:`mb-4 flex items-center justify-between`},Hd={class:`font-display text-lg font-bold`},Ud={key:0,class:`text-sm text-muted`},Wd={key:1,class:`text-sm text-muted`},Gd={key:2,class:`grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4`},Kd=[`onClick`],qd=[`src`,`alt`],Jd={class:`block truncate px-2 py-1 text-xs`},Yd=I({__name:`MediaPicker`,emits:[`pick`,`close`],setup(e,{emit:t}){let n=t,r=M([]),i=M(!0);return aa(async()=>{try{r.value=(await Y.get(`${J.base}/media/items`)).items.filter(e=>e.is_image)}finally{i.value=!1}}),(e,t)=>(B(),V(`div`,{class:`fixed inset-0 z-50 grid place-items-center bg-black/60 p-4`,onClick:t[1]||=Du(e=>n(`close`),[`self`])},[U(`div`,Bd,[U(`div`,Vd,[U(`h2`,Hd,O(N(X)(`Choose an image`)),1),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:t[0]||=e=>n(`close`)},O(N(X)(`Cancel`)),1)]),i.value?(B(),V(`p`,Ud,O(N(X)(`Loading…`)),1)):r.value.length?(B(),V(`div`,Gd,[(B(!0),V(R,null,L(r.value,e=>(B(),V(`button`,{key:e.id,type:`button`,class:`overflow-hidden rounded-lg border border-line text-left hover:border-brand`,onClick:t=>n(`pick`,e.url,e)},[U(`img`,{src:e.url,alt:e.name,loading:`lazy`,class:`aspect-square w-full object-cover`},null,8,qd),U(`span`,Jd,O(e.name),1)],8,Kd))),128))])):(B(),V(`p`,Wd,O(N(X)(`No images yet.`)),1))])]))}}),Xd=[`aria-label`],Zd=[`disabled`,`title`],Qd=[`disabled`,`title`],$d=[`disabled`,`title`],ef=[`disabled`,`title`],tf=[`disabled`,`title`],nf=[`disabled`,`title`],rf=[`disabled`],af={class:`ml-auto flex gap-1`},of=[`id`,`value`,`rows`,`required`,`maxlength`],sf={key:0,class:`m-input min-h-40 overflow-auto`},cf={key:0,class:`text-sm text-muted`},lf=[`innerHTML`],uf=I({__name:`MarkdownEditor`,props:{modelValue:{},id:{},rows:{},required:{type:Boolean},maxlength:{}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=M(null),a=M(`write`),o=M(``),s=M(!1),c=M(!1),l=J.permissions.includes(`media.view`);function u(e,t=e,a=``){let o=i.value,s=o.selectionStart,c=o.selectionEnd,l=n.modelValue.slice(s,c)||a,u=n.modelValue.slice(0,s)+e+l+t+n.modelValue.slice(c);r(`update:modelValue`,u),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+e.length,s+e.length+l.length)})}function d(e){let t=i.value,a=n.modelValue.lastIndexOf(` +`,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=`![${a}](${e})`;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 Y.post(`${J.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(B(),V(`div`,null,[U(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":N(X)(`Formatting`)},[U(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:N(X)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,N(X)(`bold`))},`B`,8,Zd),U(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:N(X)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,N(X)(`italic`))},`I`,8,Qd),U(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(X)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,$d),U(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(X)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,ef),U(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(X)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,tf),U(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:N(X)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,N(X)(`text`))},`🔗`,8,nf),N(l)?(B(),V(`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},O(N(X)(`Photo`)),9,rf)):K(``,!0),U(`span`,af,[U(`button`,{type:`button`,class:D([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},O(N(X)(`Write`)),3),U(`button`,{type:`button`,class:D([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},O(N(X)(`Preview`)),3)])],8,Xd),F(U(`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,of),[[tl,a.value===`write`]]),a.value===`preview`?(B(),V(`div`,sf,[s.value?(B(),V(`p`,cf,O(N(X)(`Loading…`)),1)):(B(),V(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,lf))])):K(``,!0),c.value?(B(),H(Yd,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):K(``,!0)]))}}),df={class:`m-card mt-6 max-w-3xl p-5`},ff={class:`font-display text-lg font-bold`},pf={key:0,class:`mt-2 text-sm text-muted`},mf={key:1,class:`mt-2 text-sm text-muted`},hf={key:2,class:`mt-3 divide-y divide-line`},gf={class:`flex flex-wrap items-center justify-between gap-2`},_f=[`aria-expanded`,`onClick`],vf={class:`font-semibold`},yf={key:0,class:`text-muted`},bf={key:1,class:`m-badge ml-2`},xf={class:`block text-xs text-muted`},Sf=[`onClick`],Cf={key:0,class:`mt-2 space-y-2 text-sm`},wf={class:`text-xs font-semibold uppercase tracking-wide text-muted`},Tf={class:`whitespace-pre-wrap break-words`},Ef=I({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=M([]),r=M(!1),i=M(null),a=M(!0),o=`${J.base}/revisions/${t.type}/${t.id}`;aa(async()=>{try{let e=await Y.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(X(`Put this version back? The text now is kept in the history.`))&&(await Y.post(`${o}/${e.id}/restore`),$(X(`The earlier version is back.`)),await l4())}let c=e=>new Date(e).toLocaleString(J.locale||void 0);return(e,t)=>(B(),V(`section`,df,[U(`h2`,ff,O(N(X)(`History`)),1),a.value?(B(),V(`p`,pf,O(N(X)(`Loading…`)),1)):n.value.length?(B(),V(`ul`,hf,[(B(!0),V(R,null,L(n.value,e=>(B(),V(`li`,{key:e.id,class:`py-3`},[U(`div`,gf,[U(`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},[U(`span`,vf,O(c(e.created_at)),1),e.user?(B(),V(`span`,yf,` · `+O(e.user),1)):K(``,!0),e.current?(B(),V(`span`,bf,O(N(X)(`Now`)),1)):K(``,!0),U(`span`,xf,O(e.changed.join(`, `)),1)],8,_f),r.value&&!e.current?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},O(N(X)(`Put back`)),9,Sf)):K(``,!0)]),i.value===e.id?(B(),V(`dl`,Cf,[(B(!0),V(R,null,L(e.values,(e,t)=>(B(),V(`div`,{key:t},[U(`dt`,wf,O(t),1),U(`dd`,Tf,O(e),1)]))),128))])):K(``,!0)]))),128))])):(B(),V(`p`,mf,O(N(X)(`Nothing here yet.`)),1))]))}}),Df={key:0,class:`m-card mt-6 p-4`},Of={class:`mb-3 font-semibold`},kf={key:0,class:`mb-3 text-xs text-muted`},Af={class:`flex items-center justify-between gap-3`},jf={class:`font-medium`},Mf=[`disabled`,`onClick`],Nf={class:`mt-1 text-xs text-muted`},Pf={key:0,class:`mt-1 text-xs`},Ff=[`href`],If=I({__name:`SharePanel`,props:{id:{}},setup(e){let t=e,n=M([]),r=M(!1),i=M(``);async function a(){let e=await Y.get(`${J.base}/posts/${t.id}/sharing`);n.value=e.platforms,r.value=e.live}async function o(e){i.value=e.platform;try{$((await Y.post(`${J.base}/posts/${t.id}/share`,{platform:e.platform})).dry_run?X(`Dry run: nothing was sent.`):X(`Shared.`))}catch(e){if(!(e instanceof Gu)||e.status!==422)throw e;$(e.body?.message??X(`This could not be done.`),!0)}finally{i.value=``,await a()}}return aa(a),(e,t)=>n.value.length?(B(),V(`section`,Df,[U(`h2`,Of,O(N(X)(`Share`)),1),r.value?K(``,!0):(B(),V(`p`,kf,O(N(X)(`Dry run: nothing is sent to the networks.`)),1)),(B(!0),V(R,null,L(n.value,e=>(B(),V(`div`,{key:e.platform,class:`mb-3 border-t border-line pt-3 first:border-0 first:pt-0`},[U(`div`,Af,[U(`p`,jf,O(e.label),1),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,disabled:!e.connected||i.value===e.platform,onClick:t=>o(e)},O(e.connected?N(X)(`Share now`):N(X)(`Not connected`)),9,Mf)]),U(`p`,Nf,O(e.preview),1),e.last?(B(),V(`p`,Pf,[e.last.status===`failed`?(B(),V(R,{key:0},[G(O(N(X)(`Failed`))+`: `+O(e.last.error),1)],64)):(B(),V(R,{key:1},[G(O(e.last.dry_run?N(X)(`Dry run`):N(X)(`Shared`))+` · `+O(e.last.shared_at),1)],64)),e.last.url?(B(),V(`a`,{key:2,href:e.last.url,target:`_blank`,rel:`noopener`,class:`ml-2 underline`},O(N(X)(`View`)),9,Ff)):K(``,!0)])):K(``,!0)]))),128))])):K(``,!0)}}),Lf={class:`mb-6 flex items-center justify-between gap-3`},Rf={class:`font-display text-2xl font-bold`},zf={for:`title`,class:`m-label`},Bf={key:0,class:`m-error`},Vf={class:`grid gap-5 sm:grid-cols-2`},Hf={for:`slug`,class:`m-label`},Uf={key:0,class:`m-error`},Wf={for:`category`,class:`m-label`},Gf={id:`categories`},Kf=[`value`],qf={for:`excerpt`,class:`m-label`},Jf={key:0,class:`m-error`},Yf={for:`body`,class:`m-label`},Xf={key:0,class:`m-error`},Zf={class:`grid gap-5 sm:grid-cols-2`},Qf={for:`cover`,class:`m-label`},$f={class:`flex gap-2`},ep={for:`tags`,class:`m-label`},tp={id:`known-tags`},np=[`value`],rp={class:`flex flex-wrap items-center gap-6`},ip={class:`flex items-center gap-2 text-sm`},ap={key:0,class:`flex items-center gap-2 text-sm`},op={key:1},sp={for:`at`,class:`m-label`},cp=[`disabled`],lp=I({__name:`PostForm`,props:{post:{},categories:{},known_tags:{}},setup(e){let t=e.post,n=Yu({title:t?.title??``,slug:t?.slug??``,excerpt:t?.excerpt??``,body:t?.body??``,cover_image:t?.cover_image??``,category:t?.category??``,tags:t?.tags??[],is_featured:t?.is_featured??!1,is_published:t?.is_published??!1,published_at:t?.published_at??``}),r=M(!1),i=(t?.tags??[]).join(`, `);async function a(){n.values.tags=i.split(`,`).map(e=>e.trim()).filter(Boolean),(t?await n.send(`put`,`${J.base}/posts/${t.id}`):await n.send(`post`,`${J.base}/posts`))&&($(X(t?`Saved.`:`Created.`)),c4(`${J.base}/posts`))}return(o,s)=>(B(),V(R,null,[U(`div`,Lf,[U(`h1`,Rf,O(N(t)?N(t).title:N(X)(`New post`)),1),W(Z,{href:N(J).base+`/posts`,class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Back`)),1)]),_:1},8,[`href`])]),U(`form`,{class:`m-card max-w-3xl space-y-5 p-5`,onSubmit:Du(a,[`prevent`])},[U(`div`,null,[U(`label`,zf,O(N(X)(`Title`)),1),F(U(`input`,{id:`title`,"onUpdate:modelValue":s[0]||=e=>N(n).values.title=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[q,N(n).values.title]]),N(n).errors.title?(B(),V(`p`,Bf,O(N(n).errors.title),1)):K(``,!0)]),U(`div`,Vf,[U(`div`,null,[U(`label`,Hf,O(N(X)(`Address (slug)`)),1),F(U(`input`,{id:`slug`,"onUpdate:modelValue":s[1]||=e=>N(n).values.slug=e,maxlength:`255`,class:`m-input`},null,512),[[q,N(n).values.slug]]),N(n).errors.slug?(B(),V(`p`,Uf,O(N(n).errors.slug),1)):K(``,!0)]),U(`div`,null,[U(`label`,Wf,O(N(X)(`Category`)),1),F(U(`input`,{id:`category`,"onUpdate:modelValue":s[2]||=e=>N(n).values.category=e,list:`categories`,maxlength:`60`,class:`m-input`},null,512),[[q,N(n).values.category]]),U(`datalist`,Gf,[(B(!0),V(R,null,L(e.categories,e=>(B(),V(`option`,{key:e,value:e},null,8,Kf))),128))])])]),U(`div`,null,[U(`label`,qf,O(N(X)(`Summary`)),1),F(U(`textarea`,{id:`excerpt`,"onUpdate:modelValue":s[3]||=e=>N(n).values.excerpt=e,rows:`2`,maxlength:`500`,class:`m-input`},null,512),[[q,N(n).values.excerpt]]),N(n).errors.excerpt?(B(),V(`p`,Jf,O(N(n).errors.excerpt),1)):K(``,!0)]),U(`div`,null,[U(`label`,Yf,O(N(X)(`Text (Markdown)`)),1),W(uf,{id:`body`,modelValue:N(n).values.body,"onUpdate:modelValue":s[4]||=e=>N(n).values.body=e,required:``},null,8,[`modelValue`]),N(n).errors.body?(B(),V(`p`,Xf,O(N(n).errors.body),1)):K(``,!0)]),U(`div`,Zf,[U(`div`,null,[U(`label`,Qf,O(N(X)(`Cover image`)),1),U(`div`,$f,[F(U(`input`,{id:`cover`,"onUpdate:modelValue":s[5]||=e=>N(n).values.cover_image=e,maxlength:`2048`,class:`m-input`},null,512),[[q,N(n).values.cover_image]]),N(J).permissions.includes(`media.view`)?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary shrink-0`,onClick:s[6]||=e=>r.value=!0},O(N(X)(`Choose`)),1)):K(``,!0)])]),U(`div`,null,[U(`label`,ep,O(N(X)(`Tags (comma separated)`)),1),F(U(`input`,{id:`tags`,"onUpdate:modelValue":s[7]||=e=>j(i)?i.value=e:i=e,list:`known-tags`,class:`m-input`},null,512),[[q,N(i)]]),U(`datalist`,tp,[(B(!0),V(R,null,L(e.known_tags,e=>(B(),V(`option`,{key:e,value:e},null,8,np))),128))])])]),U(`div`,rp,[U(`label`,ip,[F(U(`input`,{"onUpdate:modelValue":s[8]||=e=>N(n).values.is_featured=e,type:`checkbox`},null,512),[[pu,N(n).values.is_featured]]),G(` `+O(N(X)(`Featured`)),1)]),N(J).permissions.includes(`posts.publish`)?(B(),V(`label`,ap,[F(U(`input`,{"onUpdate:modelValue":s[9]||=e=>N(n).values.is_published=e,type:`checkbox`},null,512),[[pu,N(n).values.is_published]]),G(` `+O(N(X)(`Publish`)),1)])):K(``,!0),N(n).values.is_published?(B(),V(`div`,op,[U(`label`,sp,O(N(X)(`Publish at`)),1),F(U(`input`,{id:`at`,"onUpdate:modelValue":s[10]||=e=>N(n).values.published_at=e,type:`datetime-local`,class:`m-input`},null,512),[[q,N(n).values.published_at]])])):K(``,!0)]),U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(n).busy},O(N(n).busy?N(X)(`Saving…`):N(X)(`Save`)),9,cp)],32),N(t)&&N(J).permissions.includes(`sharing.publish`)?(B(),H(If,{key:0,id:N(t).id},null,8,[`id`])):K(``,!0),N(t)&&N(J).permissions.includes(`revisions.view`)?(B(),H(Ef,{key:1,type:`posts`,id:N(t).id},null,8,[`id`])):K(``,!0),r.value?(B(),H(Yd,{key:2,onPick:s[11]||=e=>{N(n).values.cover_image=e,r.value=!1},onClose:s[12]||=e=>r.value=!1})):K(``,!0)],64))}}),up={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},dp={class:`font-display text-2xl font-bold`},fp={key:0,class:`m-card p-5 text-sm text-muted`},pp={key:1,class:`m-card divide-y divide-line`},mp={class:`min-w-0`},hp={class:`truncate font-semibold`},gp={class:`mt-1 flex items-center gap-2 text-xs text-muted`},_p={class:`m-badge`},vp={key:0},yp={class:`flex gap-2`},bp=[`onClick`],xp=[`onClick`],Sp=I({__name:`PostsIndex`,props:{posts:{}},setup(e){let t={draft:`Draft`,scheduled:`Scheduled`,published:`Published`};async function n(e){await Y.put(`${J.base}/posts/${e.id}/online`,{online:e.status!==`published`}),await l4()}async function r(e){window.confirm(X(`Are you sure?`))&&(await Y.delete(`${J.base}/posts/${e.id}`),$(X(`Deleted.`)),await l4())}return(i,a)=>(B(),V(R,null,[U(`div`,up,[U(`h1`,dp,O(N(X)(`Posts`)),1),N(J).permissions.includes(`posts.write`)?(B(),H(Z,{key:0,href:N(J).base+`/posts/create`,class:`m-btn m-btn-primary`},{default:P(()=>[G(O(N(X)(`New post`)),1)]),_:1},8,[`href`])):K(``,!0)]),e.posts.length?(B(),V(`ul`,pp,[(B(!0),V(R,null,L(e.posts,e=>(B(),V(`li`,{key:e.id,class:`flex flex-wrap items-center justify-between gap-3 p-4`},[U(`div`,mp,[U(`p`,hp,O(e.title),1),U(`p`,gp,[U(`span`,_p,O(N(X)(t[e.status])),1),e.category?(B(),V(`span`,vp,O(e.category),1)):K(``,!0)])]),U(`div`,yp,[N(J).permissions.includes(`posts.publish`)&&e.can_change?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>n(e)},O(e.status===`published`?N(X)(`Take offline`):N(X)(`Put online`)),9,bp)):K(``,!0),e.can_change?(B(),H(Z,{key:1,href:`${N(J).base}/posts/${e.id}/edit`,class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Edit`)),1)]),_:1},8,[`href`])):K(``,!0),e.can_delete?(B(),V(`button`,{key:2,type:`button`,class:`m-btn m-btn-danger`,onClick:t=>r(e)},O(N(X)(`Delete`)),9,xp)):K(``,!0)])]))),128))])):(B(),V(`p`,fp,O(N(X)(`No posts yet.`)),1))],64))}}),Cp=[`src`],wp=I({__name:`Mascot`,props:{name:{},flip:{type:Boolean},size:{}},setup(e){return(t,n)=>(B(),V(`img`,{src:N(J).mascot+e.name,alt:``,class:D([`m-mascot select-none object-contain`,e.flip?`-scale-x-100`:``]),style:ve({width:(e.size??112)+`px`,height:(e.size??112)+`px`}),draggable:`false`},null,14,Cp))}}),Tp={class:`font-display mb-6 text-2xl font-bold`},Ep={for:`name`,class:`m-label`},Dp={key:0,class:`m-error`},Op={class:`m-label`},kp={class:`text-sm`},Ap={class:`m-label`},jp={class:`flex flex-wrap gap-1.5`},Mp={key:0,class:`m-badge`},Np={key:0,class:`m-badge`},Pp={key:0,class:`rounded-lg border border-line p-4`},Fp={class:`px-1.5 text-sm font-semibold`},Ip={class:`mt-1 flex flex-wrap gap-3`},Lp=[`onUpdate:modelValue`,`value`],Rp={class:`flex`},zp={key:0,class:`m-error`},Bp={key:1,class:`rounded-lg border border-line p-4`},Vp={class:`px-1.5 text-sm font-semibold`},Hp={class:`mt-1 flex flex-wrap gap-3`},Up=[`onUpdate:modelValue`,`value`],Wp={key:0,class:`m-error`},Gp={class:`space-y-4 rounded-lg border border-line p-4`},Kp={class:`px-1.5 text-sm font-semibold`},qp={class:`m-help`},Jp={for:`current_password`,class:`m-label`},Yp={key:0,class:`m-error`},Xp={for:`password`,class:`m-label`},Zp={class:`m-help`},Qp={key:0,class:`m-error`},$p={for:`password_confirmation`,class:`m-label`},em={key:2,class:`flex items-center gap-3 rounded-lg border border-line p-4`},tm={class:`text-sm font-semibold`},nm=[`disabled`],rm=I({__name:`Profile`,props:{profile:{}},setup(e){let t=e,n=Yu({name:t.profile.name,theme:t.profile.theme,locale:t.profile.locale,current_password:``,password:``,password_confirmation:``});async function r(){await n.send(`put`,J.base+`/profile`)&&($(X(`Saved.`)),(n.values.theme!==J.theme||n.values.locale!==J.locale)&&window.location.reload(),n.values.current_password=n.values.password=n.values.password_confirmation=``)}return(t,i)=>(B(),V(R,null,[U(`h1`,Tp,O(N(X)(`My account`)),1),U(`form`,{class:`m-card max-w-xl space-y-5 p-5`,onSubmit:Du(r,[`prevent`])},[U(`div`,null,[U(`label`,Ep,O(N(X)(`Name`)),1),F(U(`input`,{id:`name`,"onUpdate:modelValue":i[0]||=e=>N(n).values.name=e,type:`text`,required:``,maxlength:`255`,class:`m-input`,autocomplete:`name`},null,512),[[q,N(n).values.name]]),N(n).errors.name?(B(),V(`p`,Dp,O(N(n).errors.name),1)):K(``,!0)]),U(`div`,null,[U(`span`,Op,O(N(X)(`Email address`)),1),U(`p`,kp,O(e.profile.email),1)]),U(`div`,null,[U(`span`,Ap,O(N(X)(`What you may do`)),1),U(`p`,jp,[e.profile.is_super_admin?(B(),V(`span`,Mp,O(N(X)(`Super admin: everything`)),1)):(B(),V(R,{key:1},[(B(!0),V(R,null,L(e.profile.groups,e=>(B(),V(`span`,{key:e,class:`m-badge`},O(e),1))),128)),e.profile.groups.length?K(``,!0):(B(),V(`span`,Np,O(N(X)(`Not in a group yet`)),1))],64))])]),e.profile.themes.length?(B(),V(`fieldset`,Pp,[U(`legend`,Fp,O(N(X)(`Look`)),1),U(`div`,Ip,[(B(!0),V(R,null,L(e.profile.themes,e=>(B(),V(`label`,{key:e.key,class:D([`flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm`,N(n).values.theme===e.key?`border-brand`:`border-line`])},[F(U(`input`,{"onUpdate:modelValue":e=>N(n).values.theme=e,type:`radio`,name:`theme`,value:e.key,class:`sr-only`},null,8,Lp),[[hu,N(n).values.theme]]),U(`span`,Rp,[(B(),V(R,null,L([`ink`,`panel`,`brand`],t=>U(`span`,{key:t,class:`h-4 w-4 border border-line`,style:ve({background:e.colors[t]})},null,4)),64))]),G(` `+O(e.label),1)],2))),128))]),N(n).errors.theme?(B(),V(`p`,zp,O(N(n).errors.theme),1)):K(``,!0)])):K(``,!0),e.profile.locales.length?(B(),V(`fieldset`,Bp,[U(`legend`,Vp,O(N(X)(`Language`)),1),U(`div`,Hp,[(B(!0),V(R,null,L(e.profile.locales,e=>(B(),V(`label`,{key:e,class:D([`flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm`,N(n).values.locale===e?`border-brand`:`border-line`])},[F(U(`input`,{"onUpdate:modelValue":e=>N(n).values.locale=e,type:`radio`,name:`locale`,value:e,class:`sr-only`},null,8,Up),[[hu,N(n).values.locale]]),G(` `+O(e===`nl`?`Nederlands`:`English`),1)],2))),128))]),N(n).errors.locale?(B(),V(`p`,Wp,O(N(n).errors.locale),1)):K(``,!0)])):K(``,!0),U(`fieldset`,Gp,[U(`legend`,Kp,O(N(X)(`New password`)),1),U(`p`,qp,O(N(X)(`Leave empty to keep the password you have.`)),1),U(`div`,null,[U(`label`,Jp,O(N(X)(`Current password`)),1),F(U(`input`,{id:`current_password`,"onUpdate:modelValue":i[1]||=e=>N(n).values.current_password=e,type:`password`,class:`m-input`,autocomplete:`current-password`},null,512),[[q,N(n).values.current_password]]),N(n).errors.current_password?(B(),V(`p`,Yp,O(N(n).errors.current_password),1)):K(``,!0)]),U(`div`,null,[U(`label`,Xp,O(N(X)(`New password`)),1),F(U(`input`,{id:`password`,"onUpdate:modelValue":i[2]||=e=>N(n).values.password=e,type:`password`,minlength:`12`,maxlength:`200`,class:`m-input`,autocomplete:`new-password`},null,512),[[q,N(n).values.password]]),U(`p`,Zp,O(N(X)(`At least 12 characters.`)),1),N(n).errors.password?(B(),V(`p`,Qp,O(N(n).errors.password),1)):K(``,!0)]),U(`div`,null,[U(`label`,$p,O(N(X)(`New password, once more`)),1),F(U(`input`,{id:`password_confirmation`,"onUpdate:modelValue":i[3]||=e=>N(n).values.password_confirmation=e,type:`password`,maxlength:`200`,class:`m-input`,autocomplete:`new-password`},null,512),[[q,N(n).values.password_confirmation]])])]),N(J).tutorial_state?(B(),V(`div`,em,[W(wp,{name:`peek`,size:64}),U(`div`,null,[U(`p`,tm,O(N(X)(`The tour`)),1),U(`button`,{type:`button`,class:`text-sm text-brand underline`,onClick:i[4]||=e=>N(Q).tour=!0},O(N(X)(`Show the tour`)),1)])])):K(``,!0),U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(n).busy},O(N(n).busy?N(X)(`Saving…`):N(X)(`Save`)),9,nm)],32)],64))}}),im={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},am={class:`font-display text-2xl font-bold`},om={class:`grid gap-4 sm:grid-cols-2`},sm={class:`m-label`,for:`a-name`},cm={key:0,class:`m-error`},lm={class:`m-label`,for:`a-email`},um={key:0,class:`m-error`},dm={class:`m-label`,for:`a-pass`},fm=[`required`],pm={class:`m-help`},mm={key:0,class:`m-error`},hm={key:0},gm={class:`m-label`},_m=[`value`,`disabled`],vm={key:0,class:`ml-auto flex items-center gap-1 text-xs text-muted`},ym=[`value`],bm={class:`m-help`},xm={key:1},Sm={class:`m-label`},Cm={class:`flex items-center gap-2 py-0.5 text-sm`},wm={class:`flex items-center gap-2 py-0.5 text-sm`},Tm={class:`flex items-center gap-2 py-0.5 text-sm`},Em={class:`flex items-center gap-2 text-sm`},Dm={class:`flex gap-2`},Om=[`disabled`],km={class:`m-card divide-y divide-line`},Am={class:`min-w-0`},jm={class:`truncate font-semibold`},Mm={key:0,class:`text-xs font-normal text-muted`},Nm={class:`truncate text-xs text-muted`},Pm={class:`mt-1 flex flex-wrap gap-1`},Fm={key:0,class:`m-badge`},Im=[`title`],Lm={class:`flex gap-2`},Rm=[`onClick`],zm=[`onClick`],Bm=I({__name:`AccountsIndex`,props:{accounts:{},groups:{}},setup(e){let t=M(null),n=Yu({name:``,email:``,password:``,groups:[],primary_group:0,view:``,tutorial:!1});function r(e){t.value=e,n.errors={},n.values.name=e===`new`?``:e.name,n.values.email=e===`new`?``:e.email,n.values.password=``,n.values.groups=e===`new`?[]:e.groups.map(e=>e.id),n.values.primary_group=e===`new`?0:e.groups.find(e=>e.primary)?.id??0,n.values.view=e===`new`?``:e.view??``,n.values.tutorial=e!==`new`&&e.tutorial===`pending`}async function i(){let e=t.value;(e===`new`?await n.send(`post`,`${J.base}/accounts`):await n.send(`put`,`${J.base}/accounts/${e.id}`))&&($(X(`Saved.`)),t.value=null,await l4())}async function a(e){window.confirm(X(`Are you sure?`))&&(await Y.delete(`${J.base}/accounts/${e.id}`),$(X(`Deleted.`)),await l4())}return(o,s)=>(B(),V(R,null,[U(`div`,im,[U(`h1`,am,O(N(X)(`Accounts`)),1),U(`button`,{type:`button`,class:`m-btn m-btn-primary`,onClick:s[0]||=e=>r(`new`)},O(N(X)(`New account`)),1)]),t.value?(B(),V(`form`,{key:0,class:`m-card mb-6 max-w-2xl space-y-4 p-5`,onSubmit:Du(i,[`prevent`])},[U(`div`,om,[U(`div`,null,[U(`label`,sm,O(N(X)(`Name`)),1),F(U(`input`,{id:`a-name`,"onUpdate:modelValue":s[1]||=e=>N(n).values.name=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[q,N(n).values.name]]),N(n).errors.name?(B(),V(`p`,cm,O(N(n).errors.name),1)):K(``,!0)]),U(`div`,null,[U(`label`,lm,O(N(X)(`Email address`)),1),F(U(`input`,{id:`a-email`,"onUpdate:modelValue":s[2]||=e=>N(n).values.email=e,type:`email`,required:``,maxlength:`255`,class:`m-input`},null,512),[[q,N(n).values.email]]),N(n).errors.email?(B(),V(`p`,um,O(N(n).errors.email),1)):K(``,!0)])]),U(`div`,null,[U(`label`,dm,O(N(X)(`Password`)),1),F(U(`input`,{id:`a-pass`,"onUpdate:modelValue":s[3]||=e=>N(n).values.password=e,type:`password`,minlength:`12`,maxlength:`200`,required:t.value===`new`,class:`m-input`,autocomplete:`new-password`},null,8,fm),[[q,N(n).values.password]]),U(`p`,pm,O(t.value===`new`?N(X)(`At least 12 characters.`):N(X)(`Leave empty to keep the password you have.`)),1),N(n).errors.password?(B(),V(`p`,mm,O(N(n).errors.password),1)):K(``,!0)]),e.groups.length?(B(),V(`fieldset`,hm,[U(`legend`,gm,O(N(X)(`Groups`)),1),(B(!0),V(R,null,L(e.groups,e=>(B(),V(`label`,{key:e.id,class:D([`flex items-center gap-2 py-0.5 text-sm`,e.can_give?``:`opacity-50`])},[F(U(`input`,{"onUpdate:modelValue":s[4]||=e=>N(n).values.groups=e,type:`checkbox`,value:e.id,disabled:!e.can_give},null,8,_m),[[pu,N(n).values.groups]]),G(` `+O(e.name)+` `,1),N(n).values.groups.includes(e.id)&&N(n).values.groups.length>1?(B(),V(`label`,vm,[F(U(`input`,{"onUpdate:modelValue":s[5]||=e=>N(n).values.primary_group=e,type:`radio`,value:e.id},null,8,ym),[[hu,N(n).values.primary_group]]),G(` `+O(N(X)(`Primary`)),1)])):K(``,!0)],2))),128)),U(`p`,bm,O(N(X)(`The primary group is the label of the account and sets its start screen. What it may do is everything its groups allow together.`)),1)])):K(``,!0),N(J).simple_view?(B(),V(`fieldset`,xm,[U(`legend`,Sm,O(N(X)(`What this account sees`)),1),U(`label`,Cm,[F(U(`input`,{"onUpdate:modelValue":s[6]||=e=>N(n).values.view=e,type:`radio`,value:``},null,512),[[hu,N(n).values.view]]),G(` `+O(N(X)(`What its rights give`)),1)]),U(`label`,wm,[F(U(`input`,{"onUpdate:modelValue":s[7]||=e=>N(n).values.view=e,type:`radio`,value:`simple`},null,512),[[hu,N(n).values.view]]),G(` `+O(N(X)(`The simple manager`)),1)]),U(`label`,Tm,[F(U(`input`,{"onUpdate:modelValue":s[8]||=e=>N(n).values.view=e,type:`radio`,value:`full`},null,512),[[hu,N(n).values.view]]),G(` `+O(N(X)(`The whole manager`)),1)])])):K(``,!0),U(`label`,Em,[F(U(`input`,{"onUpdate:modelValue":s[9]||=e=>N(n).values.tutorial=e,type:`checkbox`},null,512),[[pu,N(n).values.tutorial]]),G(` `+O(N(X)(`Show the tour the next time this account opens the manager`)),1)]),U(`div`,Dm,[U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(n).busy},O(N(n).busy?N(X)(`Saving…`):N(X)(`Save`)),9,Om),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:s[10]||=e=>t.value=null},O(N(X)(`Cancel`)),1)])],32)):K(``,!0),U(`ul`,km,[(B(!0),V(R,null,L(e.accounts,e=>(B(),V(`li`,{key:e.id,class:`flex flex-wrap items-center justify-between gap-3 p-4`},[U(`div`,Am,[U(`p`,jm,[G(O(e.name)+` `,1),e.is_you?(B(),V(`span`,Mm,`(`+O(N(X)(`you`))+`)`,1)):K(``,!0)]),U(`p`,Nm,O(e.email),1),U(`p`,Pm,[e.is_super_admin?(B(),V(`span`,Fm,O(N(X)(`Super admin`)),1)):K(``,!0),(B(!0),V(R,null,L(e.groups,t=>(B(),V(`span`,{key:t.id,class:D([`m-badge`,t.primary&&e.groups.length>1?`font-bold`:``]),title:t.primary&&e.groups.length>1?N(X)(`Primary group`):``},O(t.name),11,Im))),128))])]),U(`div`,Lm,[e.can_change?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>r(e)},O(N(X)(`Edit`)),9,Rm)):K(``,!0),e.can_delete?(B(),V(`button`,{key:1,type:`button`,class:`m-btn m-btn-danger`,onClick:t=>a(e)},O(N(X)(`Delete`)),9,zm)):K(``,!0)])]))),128))])],64))}}),Vm={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},Hm={class:`font-display text-2xl font-bold`},Um={class:`m-label`,for:`g-name`},Wm={key:0,class:`m-error`},Gm={class:`m-label`,for:`g-desc`},Km={class:`m-label`,for:`g-start`},qm={value:``},Jm=[`value`],Ym={class:`m-help`},Xm={class:`px-1 text-sm font-semibold`},Zm=[`value`,`onChange`],Qm={class:`flex gap-2`},$m=[`disabled`],eh={key:1,class:`m-card p-5 text-sm text-muted`},th={key:2,class:`m-card divide-y divide-line`},nh={class:`min-w-0`},rh={class:`font-semibold`},ih={class:`text-xs font-normal text-muted`},ah={key:0,class:`text-xs text-muted`},oh={class:`flex gap-2`},sh=[`onClick`],ch=[`onClick`],lh=I({__name:`GroupsIndex`,props:{groups:{},catalogue:{}},setup(e){let t=e,n=M(null),r=Yu({name:``,description:``,start:``,permissions:[]}),i=J.navigation.filter(e=>e.href.startsWith(J.base+`/`)&&!e.new_tab).map(e=>({label:e.label,value:e.href.slice(J.base.length)})),a=t.catalogue.flatMap(e=>e.permissions);function o(e){n.value=e,r.errors={},r.values.name=e===`new`?``:e.name,r.values.description=e===`new`?``:e.description??``,r.values.start=e===`new`?``:e.start??``,r.values.permissions=e===`new`?[]:[...e.permissions]}function s(e){r.values.permissions.includes(e.value)?r.values.permissions=[...new Set([...r.values.permissions,...e.needs])]:r.values.permissions=r.values.permissions.filter(t=>!a.find(e=>e.value===t)?.needs.includes(e.value))}async function c(){let e=n.value;(e===`new`?await r.send(`post`,`${J.base}/groups`):await r.send(`put`,`${J.base}/groups/${e.id}`))&&($(X(`Saved.`)),n.value=null,await l4())}async function l(e){window.confirm(X(`Are you sure?`))&&(await Y.delete(`${J.base}/groups/${e.id}`),$(X(`Deleted.`)),await l4())}return(t,a)=>(B(),V(R,null,[U(`div`,Vm,[U(`h1`,Hm,O(N(X)(`Groups`)),1),U(`button`,{type:`button`,class:`m-btn m-btn-primary`,onClick:a[0]||=e=>o(`new`)},O(N(X)(`New group`)),1)]),n.value?(B(),V(`form`,{key:0,class:`m-card mb-6 max-w-3xl space-y-4 p-5`,onSubmit:Du(c,[`prevent`])},[U(`div`,null,[U(`label`,Um,O(N(X)(`Name`)),1),F(U(`input`,{id:`g-name`,"onUpdate:modelValue":a[1]||=e=>N(r).values.name=e,required:``,maxlength:`60`,class:`m-input`},null,512),[[q,N(r).values.name]]),N(r).errors.name?(B(),V(`p`,Wm,O(N(r).errors.name),1)):K(``,!0)]),U(`div`,null,[U(`label`,Gm,O(N(X)(`Description`)),1),F(U(`textarea`,{id:`g-desc`,"onUpdate:modelValue":a[2]||=e=>N(r).values.description=e,rows:`2`,maxlength:`500`,class:`m-input`},null,512),[[q,N(r).values.description]])]),U(`div`,null,[U(`label`,Km,O(N(X)(`Start screen`)),1),F(U(`select`,{id:`g-start`,"onUpdate:modelValue":a[3]||=e=>N(r).values.start=e,class:`m-input`},[U(`option`,qm,O(N(X)(`The dashboard`)),1),(B(!0),V(R,null,L(N(i),e=>(B(),V(`option`,{key:e.value,value:e.value},O(e.label),9,Jm))),128))],512),[[gu,N(r).values.start]]),U(`p`,Ym,O(N(X)(`Where accounts with this as their primary group land when they open the manager.`)),1)]),(B(!0),V(R,null,L(e.catalogue,e=>(B(),V(`fieldset`,{key:e.section,class:`rounded-lg border border-line p-3`},[U(`legend`,Xm,O(e.section),1),(B(!0),V(R,null,L(e.permissions,e=>(B(),V(`label`,{key:e.value,class:`flex items-center gap-2 py-0.5 text-sm`},[F(U(`input`,{"onUpdate:modelValue":a[4]||=e=>N(r).values.permissions=e,type:`checkbox`,value:e.value,onChange:t=>s(e)},null,40,Zm),[[pu,N(r).values.permissions]]),G(` `+O(e.label),1)]))),128))]))),128)),U(`div`,Qm,[U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(r).busy},O(N(r).busy?N(X)(`Saving…`):N(X)(`Save`)),9,$m),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:a[5]||=e=>n.value=null},O(N(X)(`Cancel`)),1)])],32)):K(``,!0),e.groups.length?(B(),V(`ul`,th,[(B(!0),V(R,null,L(e.groups,e=>(B(),V(`li`,{key:e.id,class:`flex flex-wrap items-center justify-between gap-3 p-4`},[U(`div`,nh,[U(`p`,rh,[G(O(e.name)+` `,1),U(`span`,ih,`· `+O(e.accounts)+` `+O(N(X)(`accounts`)),1)]),e.description?(B(),V(`p`,ah,O(e.description),1)):K(``,!0)]),U(`div`,oh,[U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>o(e)},O(N(X)(`Edit`)),9,sh),U(`button`,{type:`button`,class:`m-btn m-btn-danger`,onClick:t=>l(e)},O(N(X)(`Delete`)),9,ch)])]))),128))])):(B(),V(`p`,eh,O(N(X)(`Nothing here yet.`)),1))],64))}}),uh={class:`font-display mb-6 text-2xl font-bold`},dh={key:0,class:`m-error mb-4`},fh={class:`grid gap-6 md:grid-cols-2`},ph={class:`mb-3 font-semibold`},mh=[`onSubmit`],hh=[`onUpdate:modelValue`,`aria-label`],gh={type:`submit`,class:`m-btn m-btn-primary`},_h={class:`divide-y divide-line`},vh={class:`min-w-0 truncate`},yh={class:`text-xs text-muted`},bh={class:`flex gap-1`},xh=[`onClick`],Sh=[`onClick`],Ch=I({__name:`LabelsIndex`,props:{categories:{},tags:{}},setup(e){let t=[{type:`category`,title:`Categories`},{type:`tag`,title:`Tags`}],n=M({category:``,tag:``}),r=M(``);async function i(e){r.value=``;try{await e(),await l4()}catch(e){if(e instanceof Gu&&e.status===422)r.value=Object.values(e.errors)[0]??e.message;else throw e}}let a=e=>i(async()=>{await Y.post(`${J.base}/labels`,{type:e,name:n.value[e]}),n.value[e]=``,$(X(`Created.`))}),o=(e,t)=>{let n=window.prompt(X(`New name`),t);return n&&n!==t?i(()=>Y.put(`${J.base}/labels`,{type:e,name:t,new_name:n})):void 0},s=(e,t)=>window.confirm(X(`Are you sure?`))?i(()=>Y.delete(`${J.base}/labels`,{type:e,name:t})):void 0;return(i,c)=>(B(),V(R,null,[U(`h1`,uh,O(N(X)(`Categories and tags`)),1),r.value?(B(),V(`p`,dh,O(r.value),1)):K(``,!0),U(`div`,fh,[(B(),V(R,null,L(t,t=>U(`section`,{key:t.type,class:`m-card p-4`},[U(`h2`,ph,O(N(X)(t.title)),1),U(`form`,{class:`mb-3 flex gap-2`,onSubmit:Du(e=>a(t.type),[`prevent`])},[F(U(`input`,{"onUpdate:modelValue":e=>n.value[t.type]=e,required:``,maxlength:`60`,class:`m-input`,"aria-label":N(X)(t.title)},null,8,hh),[[q,n.value[t.type]]]),U(`button`,gh,O(N(X)(`Add`)),1)],40,mh),U(`ul`,_h,[(B(!0),V(R,null,L(t.type===`category`?e.categories:e.tags,e=>(B(),V(`li`,{key:e.name,class:`flex items-center justify-between gap-2 py-2 text-sm`},[U(`span`,vh,[G(O(e.name)+` `,1),U(`span`,yh,`· `+O(e.posts),1)]),U(`span`,bh,[U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:n=>o(t.type,e.name)},O(N(X)(`Rename`)),9,xh),U(`button`,{type:`button`,class:`m-btn m-btn-danger`,onClick:n=>s(t.type,e.name)},O(N(X)(`Delete`)),9,Sh)])]))),128))])])),64))])],64))}}),wh={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},Th={class:`font-display text-2xl font-bold`},Eh=[`accept`,`disabled`],Dh=[`title`],Oh={class:`h-2 overflow-hidden rounded-full bg-panel-2`},kh={class:`m-help`},Ah={key:0,class:`w-full shrink-0 sm:w-64`},jh=[`src`,`alt`],Mh={class:`m-help`},Nh={class:`mt-2 flex items-center gap-2`},Ph=[`src`],Fh={class:`min-w-0 flex-1 space-y-3`},Ih={class:`m-label`,for:`m-name`},Lh=[`disabled`],Rh={key:0,class:`m-error`},zh={key:0},Bh={class:`m-label`,for:`m-alt`},Vh=[`disabled`],Hh={class:`m-help`},Uh={key:0},Wh={key:1},Gh={class:`m-help break-all`},Kh={class:`flex gap-2`},qh=[`disabled`],Jh={key:1,class:`m-card p-5 text-sm text-muted`},Yh={key:2,class:`grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5`},Xh=[`onClick`],Zh=[`src`,`alt`],Qh={key:1,class:`grid aspect-square w-full place-items-center text-xs text-muted`},$h={class:`block truncate px-2 py-1.5 text-xs`},eg=I({__name:`MediaLibrary`,props:{items:{},max_file_mb:{},extensions:{},storage:{}},setup(e){let t=e=>J.permissions.includes(e),n=M(!1),r=M(null),i=Yu({name:``,alt:``,focus_x:null,focus_y:null}),a=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1e3))} kB`;function o(e){r.value=e,i.errors={},i.values.name=e.name,i.values.alt=e.alt??``,i.values.focus_x=e.focus_x,i.values.focus_y=e.focus_y}function s(e){if(!t(`media.edit`))return;let n=e.currentTarget.getBoundingClientRect();i.values.focus_x=Math.round(Math.min(1,Math.max(0,(e.clientX-n.left)/n.width))*1e3)/1e3,i.values.focus_y=Math.round(Math.min(1,Math.max(0,(e.clientY-n.top)/n.height))*1e3)/1e3}let c=(e,t)=>`${(e??.5)*100}% ${(t??.5)*100}%`;async function l(e){let t=e.target;n.value=!0;try{for(let e of Array.from(t.files??[])){let t=new FormData;t.append(`file`,e),await Ju(`${J.base}/media`,t)}$(X(`Uploaded.`)),await l4()}catch(e){$(e instanceof Gu?Object.values(e.errors)[0]??e.message:X(`Something went wrong. Try again.`),!0)}finally{n.value=!1,t.value=``}}async function u(){r.value&&await i.send(`put`,`${J.base}/media/${r.value.id}`)&&($(X(`Saved.`)),r.value=null,await l4())}async function d(e){let t=e.usage_count>0?X(`This file is in use. Delete it anyway?`):X(`Are you sure?`);window.confirm(t)&&(await Y.delete(`${J.base}/media/${e.id}`),r.value=null,$(X(`Deleted.`)),await l4())}return(f,p)=>(B(),V(R,null,[U(`div`,wh,[U(`h1`,Th,O(N(X)(`Media`)),1),t(`media.upload`)?(B(),V(`label`,{key:0,class:D([`m-btn m-btn-primary cursor-pointer`,n.value?`opacity-50`:``])},[G(O(n.value?N(X)(`Uploading…`):N(X)(`Upload`))+` `,1),U(`input`,{type:`file`,multiple:``,class:`sr-only`,accept:e.extensions.map(e=>`.`+e).join(`,`),disabled:n.value,onChange:l},null,40,Eh)],2)):K(``,!0)]),U(`div`,{class:`mb-6 max-w-md`,title:`${a(e.storage.used)} / ${a(e.storage.limit)}`},[U(`div`,Oh,[U(`div`,{class:`h-full bg-brand`,style:ve({width:Math.min(100,e.storage.used/Math.max(1,e.storage.limit)*100)+`%`})},null,4)]),U(`p`,kh,O(a(e.storage.used))+` / `+O(a(e.storage.limit))+` · `+O(N(X)(`Largest file`))+`: `+O(e.max_file_mb)+` MB`,1)],8,Dh),r.value?(B(),V(`form`,{key:0,class:`m-card mb-6 flex max-w-3xl flex-wrap gap-5 p-5`,onSubmit:Du(u,[`prevent`])},[r.value.is_image?(B(),V(`div`,Ah,[U(`div`,{class:D([`relative`,t(`media.edit`)?`cursor-crosshair`:``]),onClick:s},[U(`img`,{src:r.value.url,alt:r.value.alt??``,class:`w-full rounded-lg`,draggable:`false`},null,8,jh),N(i).values.focus_x===null?K(``,!0):(B(),V(`span`,{key:0,class:`pointer-events-none absolute h-5 w-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-brand/60 shadow`,style:ve({left:(N(i).values.focus_x??0)*100+`%`,top:(N(i).values.focus_y??0)*100+`%`})},null,4))],2),U(`p`,Mh,O(t(`media.edit`)?N(X)(`Click the part of the picture that must stay in view.`):N(X)(`Focus point`)),1),U(`div`,Nh,[U(`img`,{src:r.value.url,alt:``,class:`h-16 w-16 rounded-lg object-cover`,style:ve({objectPosition:c(N(i).values.focus_x,N(i).values.focus_y)})},null,12,Ph),t(`media.edit`)&&N(i).values.focus_x!==null?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:p[0]||=e=>N(i).values.focus_x=N(i).values.focus_y=null},O(N(X)(`Clear`)),1)):K(``,!0)])])):K(``,!0),U(`div`,Fh,[U(`div`,null,[U(`label`,Ih,O(N(X)(`Name`)),1),F(U(`input`,{id:`m-name`,"onUpdate:modelValue":p[1]||=e=>N(i).values.name=e,required:``,maxlength:`250`,class:`m-input`,disabled:!t(`media.edit`)},null,8,Lh),[[q,N(i).values.name]]),N(i).errors.name?(B(),V(`p`,Rh,O(N(i).errors.name),1)):K(``,!0)]),r.value.is_image?(B(),V(`div`,zh,[U(`label`,Bh,O(N(X)(`Alternative text`)),1),F(U(`input`,{id:`m-alt`,"onUpdate:modelValue":p[2]||=e=>N(i).values.alt=e,maxlength:`500`,class:`m-input`,disabled:!t(`media.edit`)},null,8,Vh),[[q,N(i).values.alt]])])):K(``,!0),U(`p`,Hh,[G(O(r.value.mime_type)+` · `+O(a(r.value.size)),1),r.value.width?(B(),V(`span`,Uh,` · `+O(r.value.width)+`×`+O(r.value.height),1)):K(``,!0),G(` · `+O(N(X)(`Used`))+`: `+O(r.value.usage_count),1),r.value.uploaded_by?(B(),V(`span`,Wh,` · `+O(r.value.uploaded_by),1)):K(``,!0)]),U(`p`,Gh,O(r.value.url),1),U(`div`,Kh,[t(`media.edit`)?(B(),V(`button`,{key:0,type:`submit`,class:`m-btn m-btn-primary`,disabled:N(i).busy},O(N(X)(`Save`)),9,qh)):K(``,!0),t(`media.delete`)?(B(),V(`button`,{key:1,type:`button`,class:`m-btn m-btn-danger`,onClick:p[3]||=e=>d(r.value)},O(N(X)(`Delete`)),1)):K(``,!0),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:p[4]||=e=>r.value=null},O(N(X)(`Cancel`)),1)])])],32)):K(``,!0),e.items.length?(B(),V(`div`,Yh,[(B(!0),V(R,null,L(e.items,e=>(B(),V(`button`,{key:e.id,type:`button`,class:D([`m-card overflow-hidden text-left transition hover:border-brand`,r.value?.id===e.id?`border-brand`:``]),onClick:t=>o(e)},[e.is_image?(B(),V(`img`,{key:0,src:e.url,alt:e.alt??``,loading:`lazy`,class:`aspect-square w-full object-cover`},null,8,Zh)):(B(),V(`span`,Qh,O(e.mime_type),1)),U(`span`,$h,O(e.name),1)],10,Xh))),128))])):(B(),V(`p`,Jh,O(N(X)(`No files yet.`)),1))],64))}}),tg={class:`font-display mb-6 text-2xl font-bold`},ng={class:`mb-6 grid grid-cols-2 gap-3 md:grid-cols-4`},rg={class:`text-2xl font-bold`},ig={class:`m-help`},ag={class:`mb-4 flex flex-wrap gap-2`},og=[`onClick`],sg=[`placeholder`,`aria-label`],cg=[`aria-label`],lg={value:``},ug=[`value`],dg={type:`submit`,class:`m-btn m-btn-secondary`},fg={key:0,class:`m-card p-5 text-sm text-muted`},pg={key:1,class:`m-card divide-y divide-line`},mg={class:`min-w-0`},hg={class:`font-semibold`},gg={key:1},_g={class:`text-xs text-muted`},vg={class:`flex gap-2`},yg={key:0,class:`m-badge`},bg=[`onClick`],xg={key:2,class:`mt-4 flex items-center gap-2`},Sg={class:`text-sm text-muted`},Cg={class:`font-display mb-3 mt-10 text-xl font-bold`},wg={class:`m-label`,for:`b-min`},Tg={class:`min-w-[10rem] flex-1`},Eg={class:`m-label`,for:`b-why`},Dg={key:0,class:`flex items-center gap-2 text-sm`},Og={type:`submit`,class:`m-btn m-btn-danger`},kg={key:1,class:`m-error w-full`},Ag={key:4,class:`text-sm text-muted`},jg={key:5,class:`m-card divide-y divide-line`},Mg={class:`font-semibold`},Ng={key:0,class:`m-badge`},Pg={key:1,class:`m-badge`},Fg={class:`text-xs text-muted`},Ig=[`onClick`],Lg={class:`font-display mb-3 mt-10 text-xl font-bold`},Rg={class:`flex items-center gap-2 text-sm sm:col-span-2`},zg={class:`m-label`,for:`r-max`},Bg={class:`m-label`,for:`r-win`},Vg={class:`m-label`,for:`r-ban`},Hg={class:`m-label`,for:`r-keep`},Ug=[`max`],Wg={class:`m-help`},Gg={class:`sm:col-span-2`},Kg=[`disabled`],qg={class:`font-display mb-3 mt-10 text-xl font-bold`},Jg={class:`m-label`,for:`n-group`},Yg={class:`min-w-[10rem] flex-1`},Xg={class:`m-label`,for:`n-note`},Zg={type:`submit`,class:`m-btn m-btn-secondary`},Qg={key:0,class:`m-error w-full`},$g={key:0,class:`m-card divide-y divide-line text-sm`},e_={key:0,class:`m-badge`},t_=I({__name:`AuditLog`,props:{entries:{},pagination:{},filters:{},accounts:{},summary:{},bans:{},notes:{},settings:{},max_keep_days:{},can_manage:{type:Boolean},my_ip:{},never_banned:{},whole_site_bans:{type:Boolean}},setup(e){let t=e,n=[`all`,`logins`,`failed`,`actions`,`viewed`,`refused`,`bans`],r=an({q:t.filters.q,ip:t.filters.ip,user:t.filters.user??``}),i=e=>new Date(e).toLocaleString();function a(e){let n=new URLSearchParams,i={show:t.filters.show,q:r.q,ip:r.ip,user:r.user,...e};for(let[e,t]of Object.entries(i))t!==``&&t!==`all`&&t!==1&&n.set(e,String(t));c4(`${J.base}/audit${n.size?`?`+n:``}`)}let o=Yu({ip:``,minutes:1440,reason:``,whole_site:!1});async function s(e){e&&(o.values.ip=e);let t=await o.send(`post`,`${J.base}/audit/bans`);t&&($(t.message),o.values.ip=o.values.reason=``,await l4())}async function c(e){$((await Y.delete(`${J.base}/audit/bans/${e.id}`)).message),await l4()}let l=Yu({...t.settings});async function u(){await l.send(`put`,`${J.base}/audit/settings`)&&($(X(`Saved.`)),await l4())}let d=Yu({ip:``,group:``,note:``});async function f(){await d.send(`put`,`${J.base}/audit/notes`)&&($(X(`Saved.`)),d.values.ip=d.values.group=d.values.note=``,await l4())}let p=e=>e.expires_at?i(e.expires_at):X(`until lifted`);return(t,m)=>(B(),V(R,null,[U(`h1`,tg,O(N(X)(`Audit log`)),1),U(`div`,ng,[(B(!0),V(R,null,L(e.summary,(e,t)=>(B(),V(`div`,{key:t,class:`m-card p-4`},[U(`p`,rg,O(e),1),U(`p`,ig,O(N(X)(t===`banned`?`Addresses banned`:t===`logins`?`Logins (24 h)`:t===`failed`?`Failed logins (24 h)`:`Refused (24 h)`)),1)]))),128))]),U(`nav`,ag,[(B(),V(R,null,L(n,t=>U(`button`,{key:t,type:`button`,class:D([`m-btn`,e.filters.show===t?`m-btn-primary`:`m-btn-secondary`]),onClick:e=>a({show:t,page:1})},O(N(X)(t)),11,og)),64))]),U(`form`,{class:`mb-4 flex flex-wrap gap-2`,onSubmit:m[3]||=Du(e=>a({page:1}),[`prevent`])},[F(U(`input`,{"onUpdate:modelValue":m[0]||=e=>r.q=e,class:`m-input max-w-xs`,placeholder:N(X)(`Search`),"aria-label":N(X)(`Search`)},null,8,sg),[[q,r.q]]),F(U(`input`,{"onUpdate:modelValue":m[1]||=e=>r.ip=e,class:`m-input max-w-[12rem]`,placeholder:`IP`,"aria-label":`IP`},null,512),[[q,r.ip]]),F(U(`select`,{"onUpdate:modelValue":m[2]||=e=>r.user=e,class:`m-input max-w-[12rem]`,"aria-label":N(X)(`Account`)},[U(`option`,lg,O(N(X)(`Everyone`)),1),(B(!0),V(R,null,L(e.accounts,e=>(B(),V(`option`,{key:e.id,value:e.id},O(e.name),9,ug))),128))],8,cg),[[gu,r.user]]),U(`button`,dg,O(N(X)(`Filter`)),1)],32),e.entries.length?(B(),V(`ul`,pg,[(B(!0),V(R,null,L(e.entries,t=>(B(),V(`li`,{key:t.id,class:`flex flex-wrap items-start justify-between gap-3 p-4 text-sm`},[U(`div`,mg,[U(`p`,hg,[G(O(t.summary)+` `,1),t.subject?(B(),V(R,{key:0},[m[19]||=G(` · `,-1),t.subject.url?(B(),H(Z,{key:0,href:t.subject.url,class:`underline`},{default:P(()=>[G(O(t.subject.label),1)]),_:2},1032,[`href`])):(B(),V(`span`,gg,O(t.subject.label),1))],64)):K(``,!0)]),U(`p`,_g,O(i(t.at))+` · `+O(t.who??t.email??N(X)(`Someone`))+` · `+O(t.ip)+` · `+O(t.browser),1)]),U(`span`,vg,[t.banned?(B(),V(`span`,yg,O(N(X)(`banned`)),1)):K(``,!0),e.can_manage&&t.ip&&!t.banned&&!t.never_banned&&t.ip!==e.my_ip?(B(),V(`button`,{key:1,type:`button`,class:`m-btn m-btn-danger`,onClick:e=>s(t.ip)},O(N(X)(`Ban`)),9,bg)):K(``,!0)])]))),128))])):(B(),V(`p`,fg,O(N(X)(`Nothing here yet.`)),1)),e.pagination.pages>1?(B(),V(`nav`,xg,[e.pagination.page>1?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:m[4]||=t=>a({page:e.pagination.page-1})},O(N(X)(`Previous`)),1)):K(``,!0),U(`span`,Sg,O(e.pagination.page)+` / `+O(e.pagination.pages),1),e.pagination.pagea({page:e.pagination.page+1})},O(N(X)(`Next`)),1)):K(``,!0)])):K(``,!0),U(`h2`,Cg,O(N(X)(`Bans`)),1),e.can_manage?(B(),V(`form`,{key:3,class:`m-card mb-4 flex max-w-3xl flex-wrap items-end gap-3 p-4`,onSubmit:m[10]||=Du(e=>s(),[`prevent`])},[U(`div`,null,[m[20]||=U(`label`,{class:`m-label`,for:`b-ip`},`IP`,-1),F(U(`input`,{id:`b-ip`,"onUpdate:modelValue":m[6]||=e=>N(o).values.ip=e,required:``,class:`m-input`},null,512),[[q,N(o).values.ip]])]),U(`div`,null,[U(`label`,wg,O(N(X)(`Minutes (0 = until lifted)`)),1),F(U(`input`,{id:`b-min`,"onUpdate:modelValue":m[7]||=e=>N(o).values.minutes=e,type:`number`,min:`0`,class:`m-input w-32`},null,512),[[q,N(o).values.minutes,void 0,{number:!0}]])]),U(`div`,Tg,[U(`label`,Eg,O(N(X)(`Reason`)),1),F(U(`input`,{id:`b-why`,"onUpdate:modelValue":m[8]||=e=>N(o).values.reason=e,maxlength:`200`,class:`m-input`},null,512),[[q,N(o).values.reason]])]),e.whole_site_bans?(B(),V(`label`,Dg,[F(U(`input`,{"onUpdate:modelValue":m[9]||=e=>N(o).values.whole_site=e,type:`checkbox`},null,512),[[pu,N(o).values.whole_site]]),G(` `+O(N(X)(`Whole site`)),1)])):K(``,!0),U(`button`,Og,O(N(X)(`Ban`)),1),N(o).errors.ip?(B(),V(`p`,kg,O(N(o).errors.ip),1)):K(``,!0)],32)):K(``,!0),e.bans.length?(B(),V(`ul`,jg,[(B(!0),V(R,null,L(e.bans,t=>(B(),V(`li`,{key:t.id,class:D([`flex flex-wrap items-center justify-between gap-3 p-4 text-sm`,t.active?``:`opacity-50`])},[U(`div`,null,[U(`p`,Mg,[G(O(t.ip)+` `,1),t.automatic?(B(),V(`span`,Ng,O(N(X)(`automatic`)),1)):K(``,!0),m[21]||=G(),t.whole_site?(B(),V(`span`,Pg,O(N(X)(`whole site`)),1)):K(``,!0)]),U(`p`,Fg,O(t.reason)+` · `+O(p(t))+` · `+O(t.hits)+` `+O(N(X)(`hits`)),1)]),e.can_manage&&t.active?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>c(t)},O(N(X)(`Lift`)),9,Ig)):K(``,!0)],2))),128))])):(B(),V(`p`,Ag,O(N(X)(`No bans.`)),1)),e.can_manage?(B(),V(R,{key:6},[U(`h2`,Lg,O(N(X)(`Rules`)),1),U(`form`,{class:`m-card grid max-w-3xl gap-4 p-5 sm:grid-cols-2`,onSubmit:Du(u,[`prevent`])},[U(`label`,Rg,[F(U(`input`,{"onUpdate:modelValue":m[11]||=e=>N(l).values.auto_ban=e,type:`checkbox`},null,512),[[pu,N(l).values.auto_ban]]),G(` `+O(N(X)(`Ban an address by itself after too many failed logins`)),1)]),U(`div`,null,[U(`label`,zg,O(N(X)(`Failed logins`)),1),F(U(`input`,{id:`r-max`,"onUpdate:modelValue":m[12]||=e=>N(l).values.max_failures=e,type:`number`,min:`3`,max:`100`,class:`m-input`},null,512),[[q,N(l).values.max_failures,void 0,{number:!0}]])]),U(`div`,null,[U(`label`,Bg,O(N(X)(`Within minutes`)),1),F(U(`input`,{id:`r-win`,"onUpdate:modelValue":m[13]||=e=>N(l).values.window_minutes=e,type:`number`,min:`1`,max:`1440`,class:`m-input`},null,512),[[q,N(l).values.window_minutes,void 0,{number:!0}]])]),U(`div`,null,[U(`label`,Vg,O(N(X)(`Ban for minutes (0 = until lifted)`)),1),F(U(`input`,{id:`r-ban`,"onUpdate:modelValue":m[14]||=e=>N(l).values.ban_minutes=e,type:`number`,min:`0`,class:`m-input`},null,512),[[q,N(l).values.ban_minutes,void 0,{number:!0}]])]),U(`div`,null,[U(`label`,Hg,O(N(X)(`Keep the log (days)`)),1),F(U(`input`,{id:`r-keep`,"onUpdate:modelValue":m[15]||=e=>N(l).values.keep_days=e,type:`number`,min:`7`,max:e.max_keep_days,class:`m-input`},null,8,Ug),[[q,N(l).values.keep_days,void 0,{number:!0}]]),U(`p`,Wg,`≤ `+O(e.max_keep_days),1)]),U(`div`,Gg,[U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(l).busy},O(N(X)(`Save`)),9,Kg)]),(B(!0),V(R,null,L(N(l).errors,(e,t)=>(B(),V(`p`,{key:t,class:`m-error sm:col-span-2`},O(e),1))),128))],32),U(`h2`,qg,O(N(X)(`Notes about addresses`)),1),U(`form`,{class:`m-card mb-4 flex max-w-3xl flex-wrap items-end gap-3 p-4`,onSubmit:Du(f,[`prevent`])},[U(`div`,null,[m[22]||=U(`label`,{class:`m-label`,for:`n-ip`},`IP`,-1),F(U(`input`,{id:`n-ip`,"onUpdate:modelValue":m[16]||=e=>N(d).values.ip=e,required:``,class:`m-input`},null,512),[[q,N(d).values.ip]])]),U(`div`,null,[U(`label`,Jg,O(N(X)(`Group`)),1),F(U(`input`,{id:`n-group`,"onUpdate:modelValue":m[17]||=e=>N(d).values.group=e,maxlength:`60`,class:`m-input`},null,512),[[q,N(d).values.group]])]),U(`div`,Yg,[U(`label`,Xg,O(N(X)(`Note`)),1),F(U(`input`,{id:`n-note`,"onUpdate:modelValue":m[18]||=e=>N(d).values.note=e,maxlength:`2000`,class:`m-input`},null,512),[[q,N(d).values.note]])]),U(`button`,Zg,O(N(X)(`Save`)),1),N(d).errors.ip?(B(),V(`p`,Qg,O(N(d).errors.ip),1)):K(``,!0)],32),e.notes.length?(B(),V(`ul`,$g,[(B(!0),V(R,null,L(e.notes,e=>(B(),V(`li`,{key:e.ip,class:`p-3`},[U(`b`,null,O(e.ip),1),m[23]||=G(),e.group?(B(),V(`span`,e_,O(e.group),1)):K(``,!0),G(` `+O(e.note),1)]))),128))])):K(``,!0)],64)):K(``,!0)],64))}}),n_={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},r_={class:`font-display text-2xl font-bold`},i_={key:0,class:`m-card mb-4 p-4 text-sm`},a_={key:1,class:`m-card mb-4 p-4 text-sm`},o_={class:`mb-4 max-w-3xl text-sm text-muted`},s_={class:`px-1 text-sm font-semibold`},c_={key:0,class:`flex items-center justify-between gap-3 text-sm`},l_=[`checked`,`disabled`,`onChange`],u_=[`for`],d_=[`id`,`value`,`onChange`],f_=[`value`],p_=[`id`,`type`,`value`,`placeholder`,`autocomplete`,`disabled`,`onInput`],m_={key:2,class:`m-help`},h_={key:3,class:`m-error`},g_=[`onClick`],__={key:0,class:`flex flex-wrap items-center gap-3`},v_=[`disabled`,`onClick`],y_={key:0,class:`m-help`},b_={key:0,class:`m-card p-5`},x_={class:`m-label`,for:`s-password`},S_={class:`m-help`},C_={key:0,class:`m-error`},w_=[`disabled`],T_=I({__name:`Settings`,props:{groups:{},write_env:{type:Boolean},env_writable:{type:Boolean},config_cached:{type:Boolean}},setup(e){let t=e,n=an({}),r=M([]),i=M(``),a=M({}),o=M(!1),s=M(null),c=pc(()=>t.groups.flatMap(e=>e.items)),l=e=>e.key in n?n[e.key]:e.value,u=pc(()=>Object.keys(n).length>0||r.value.length>0),d=pc(()=>c.value.some(e=>e.sensitive&&(e.key in n||r.value.includes(e.key))));function f(e,t){e.type===`secret`&&(t===``||t===null)||t===e.value&&e.type!==`secret`?delete n[e.key]:n[e.key]=t}function p(e){delete n[e.key],r.value=r.value.includes(e.key)?r.value.filter(t=>t!==e.key):[...r.value,e.key]}async function m(){o.value=!0,a.value={};try{let e=await Y.put(`${J.base}/settings`,{values:{...n},reset:r.value,password:i.value});s.value={migrate:e.migrate??[],file:e.file_written,env:e.env_written},$(X(`Saved.`)),Object.keys(n).forEach(e=>delete n[e]),r.value=[],i.value=``,await l4()}catch(e){if(e instanceof Gu&&e.status===422)a.value=e.errors;else throw e}finally{o.value=!1}}let h=M({});async function g(e){h.value[e]=`busy`;try{h.value[e]=await Y.post(`${J.base}/settings/check`,{group:e})}catch{h.value[e]={ok:!1,message:X(`The check could not be run.`)}}}async function _(){await Y.post(`${J.base}/settings/refresh`),$(X(`Refreshed.`))}return(t,c)=>(B(),V(R,null,[U(`div`,n_,[U(`h1`,r_,O(N(X)(`Settings`)),1),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:_},O(N(X)(`Refresh now`)),1)]),s.value?.migrate.length?(B(),V(`p`,i_,[G(O(N(X)(`These parts need new tables:`))+` `,1),U(`strong`,null,O(s.value.migrate.join(`, `)),1),G(`. `+O(N(X)(`Run php artisan migrate on the server.`)),1)])):K(``,!0),s.value&&!s.value.file?(B(),V(`p`,a_,O(N(X)(`The changes are saved, but the file that makes them work at once could not be written (bootstrap/cache). They work after Refresh now, or when that folder may be written.`)),1)):K(``,!0),U(`p`,o_,[G(O(N(X)(`A change works at once and is kept in the database.`))+` `,1),e.write_env?(B(),V(R,{key:0},[G(O(e.env_writable?N(X)(`It is also written into the .env file.`):N(X)(`The .env file may not be written here, so only the database is used.`)),1)],64)):K(``,!0)]),U(`form`,{class:`max-w-3xl space-y-6`,onSubmit:Du(m,[`prevent`])},[(B(!0),V(R,null,L(e.groups,e=>(B(),V(`fieldset`,{key:e.name,class:`m-card space-y-4 p-5`},[U(`legend`,s_,O(e.name),1),(B(!0),V(R,null,L(e.items,e=>(B(),V(`div`,{key:e.key},[e.type===`toggle`?(B(),V(`label`,c_,[U(`span`,null,O(e.label),1),U(`input`,{type:`checkbox`,checked:!!l(e),disabled:r.value.includes(e.key),onChange:t=>f(e,t.target.checked)},null,40,l_)])):(B(),V(R,{key:1},[U(`label`,{class:`m-label`,for:`s-`+e.key},O(e.label),9,u_),e.type===`select`?(B(),V(`select`,{key:0,id:`s-`+e.key,class:`m-input`,value:l(e),onChange:t=>f(e,t.target.value)},[(B(!0),V(R,null,L(e.options,(e,t)=>(B(),V(`option`,{key:t,value:t},O(e),9,f_))),128))],40,d_)):(B(),V(`input`,{key:1,id:`s-`+e.key,class:`m-input`,type:e.type===`secret`?`password`:e.type===`number`?`number`:`text`,value:e.type===`secret`?n[e.key]??``:l(e)??``,placeholder:e.type===`secret`&&e.set?N(X)(`Set. Type to replace it.`):``,autocomplete:e.type===`secret`?`new-password`:`off`,disabled:r.value.includes(e.key),onInput:t=>f(e,t.target.value)},null,40,p_))],64)),e.help?(B(),V(`p`,m_,O(e.help),1)):K(``,!0),a.value[`values.`+e.key]?(B(),V(`p`,h_,O(a.value[`values.`+e.key]),1)):K(``,!0),e.saved||r.value.includes(e.key)?(B(),V(`button`,{key:4,type:`button`,class:`mt-1 text-xs text-muted underline hover:text-text`,onClick:t=>p(e)},O(r.value.includes(e.key)?N(X)(`Keep what is saved`):N(X)(`Back to what the config says`)),9,g_)):K(``,!0)]))),128)),e.check?(B(),V(`div`,__,[U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,disabled:u.value||h.value[e.name]===`busy`,onClick:t=>g(e.name)},O(h.value[e.name]===`busy`?N(X)(`Trying…`):N(X)(`Try it`)),9,v_),u.value?(B(),V(`span`,y_,O(N(X)(`Save first: it tries what is saved.`)),1)):h.value[e.name]&&h.value[e.name]!==`busy`?(B(),V(`span`,{key:1,class:D(h.value[e.name].ok?`text-sm`:`m-error`),role:`status`},O(h.value[e.name].ok?`✓`:`✗`)+` `+O(h.value[e.name].message),3)):K(``,!0)])):K(``,!0)]))),128)),d.value?(B(),V(`div`,b_,[U(`label`,x_,O(N(X)(`Your password`)),1),F(U(`input`,{id:`s-password`,"onUpdate:modelValue":c[0]||=e=>i.value=e,type:`password`,class:`m-input`,autocomplete:`current-password`,required:``},null,512),[[q,i.value]]),U(`p`,S_,O(N(X)(`Keys, passwords and addresses of integrations are only changed after you type your own password.`)),1),a.value.password?(B(),V(`p`,C_,O(a.value.password),1)):K(``,!0)])):K(``,!0),U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:o.value||!u.value},O(o.value?N(X)(`Saving…`):N(X)(`Save`)),9,w_)],32)],64))}}),E_={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},D_={class:`font-display text-2xl font-bold`},O_={class:`text-sm text-muted`},k_={key:0},A_={class:`mb-6 flex flex-wrap gap-2`},j_={class:`mb-6 grid grid-cols-2 gap-3 md:grid-cols-5`},M_={class:`text-2xl font-bold`},N_={class:`m-help`},P_={class:`m-card mb-6 p-4`},F_={class:`mb-3 font-semibold`},I_=[`aria-label`],L_=[`title`],R_={class:`mb-6 grid gap-6 md:grid-cols-2`},z_={class:`m-card p-4`},B_={class:`mb-3 font-semibold`},V_={key:0,class:`text-sm text-muted`},H_={class:`divide-y divide-line text-sm`},U_={class:`truncate`},W_={class:`text-muted`},G_={class:`m-card p-4`},K_={class:`mb-3 font-semibold`},q_={key:0,class:`text-sm text-muted`},J_={class:`divide-y divide-line text-sm`},Y_={class:`truncate`},X_={class:`text-muted`},Z_={class:`mb-3 font-semibold`},Q_={key:0,class:`text-sm text-muted`},$_={class:`divide-y divide-line text-sm`},e1={class:`truncate`},t1={class:`text-muted`},n1={class:`m-card mb-6 overflow-x-auto p-4`},r1={class:`mb-3 font-semibold`},i1={class:`space-y-0.5 text-xs`},a1={class:`w-9 shrink-0 text-muted`},o1=[`title`],s1={class:`m-card mb-6 p-4`},c1={class:`mb-3 font-semibold`},l1={class:`text-sm font-normal text-muted`},u1={key:0,class:`text-sm text-muted`},d1={class:`divide-y divide-line text-sm`},f1={class:`text-xs text-muted`},p1={class:`text-muted`},m1={class:`flex flex-wrap items-center gap-2 text-sm`},h1={class:`text-muted`},g1=[`href`],_1=I({__name:`StatisticsReport`,props:{range:{},ranges:{},exports:{},totals:{},previous:{},series:{},pages:{},posts:{},channels:{},sources:{},countries:{},devices:{},browsers:{},systems:{},heatmap:{},bots:{}},setup(e){let t=e,n=pc(()=>[[`Visitors`,`visitors`],[`Visits`,`visits`],[`Page views`,`page_views`],[`Average time`,`average_seconds`],[`Bounce rate`,`bounce_rate`]]),r=(e,t)=>e===`average_seconds`?`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`:e===`bounce_rate`?`${t}%`:t.toLocaleString(),i=e=>{let n=t.previous?.[e];return n?Math.round((t.totals[e]-n)/n*100):null},a=pc(()=>Math.max(1,...t.series.map(e=>e.visits))),o=pc(()=>Math.max(1,...t.heatmap.flatMap(e=>e.hours))),s=pc(()=>[[`Channels`,t.channels],[`Sources`,t.sources],[`Countries`,t.countries],[`Devices`,t.devices],[`Browsers`,t.browsers],[`Systems`,t.systems]]),c=e=>`${J.base}/statistics?range=${e}`,l=e=>`${J.base}/statistics/export?sheet=${e}&range=${new URLSearchParams(Q.path.split(`?`)[1]??``).get(`range`)??t.range.key}`;return(t,u)=>(B(),V(R,null,[U(`div`,E_,[U(`h1`,D_,O(N(X)(`Statistics`)),1),U(`p`,O_,[G(O(e.range.from)+` → `+O(e.range.to),1),e.range.compared_to?(B(),V(`span`,k_,` · `+O(N(X)(`compared with`))+` `+O(e.range.compared_to),1)):K(``,!0)])]),U(`nav`,A_,[(B(!0),V(R,null,L(e.ranges,t=>(B(),H(Z,{key:t.key,href:c(t.key),class:D([`m-btn`,e.range.key===t.key?`m-btn-primary`:`m-btn-secondary`])},{default:P(()=>[G(O(t.label),1)]),_:2},1032,[`href`,`class`]))),128))]),U(`div`,j_,[(B(!0),V(R,null,L(n.value,([t,n])=>(B(),V(`div`,{key:n,class:`m-card p-4`},[U(`p`,M_,O(r(n,e.totals[n])),1),U(`p`,N_,[G(O(N(X)(t)),1),i(n)===null?K(``,!0):(B(),V(`span`,{key:0,class:D((i(n)??0)>=0?`text-emerald-500`:`text-red-500`)},O((i(n)??0)>0?`+`:``)+O(i(n))+`%`,3))])]))),128))]),U(`section`,P_,[U(`h2`,F_,O(N(X)(`Visits`)),1),U(`div`,{class:`flex h-40 items-end gap-px`,role:`img`,"aria-label":N(X)(`Visits`)},[(B(!0),V(R,null,L(e.series,e=>(B(),V(`div`,{key:e.key,class:`min-w-px flex-1 rounded-t bg-brand`,style:ve({height:Math.max(2,e.visits/a.value*100)+`%`}),title:`${e.label}: ${e.visits}`},null,12,L_))),128))],8,I_)]),U(`div`,R_,[U(`section`,z_,[U(`h2`,B_,O(N(X)(`Pages`)),1),e.pages.length?K(``,!0):(B(),V(`p`,V_,O(N(X)(`Nothing here yet.`)),1)),U(`ul`,H_,[(B(!0),V(R,null,L(e.pages,e=>(B(),V(`li`,{key:e.path,class:`flex justify-between gap-3 py-1.5`},[U(`span`,U_,O(e.title??e.path),1),U(`span`,W_,O(e.views),1)]))),128))])]),U(`section`,G_,[U(`h2`,K_,O(N(X)(`Posts`)),1),e.posts.length?K(``,!0):(B(),V(`p`,q_,O(N(X)(`Nothing here yet.`)),1)),U(`ul`,J_,[(B(!0),V(R,null,L(e.posts,e=>(B(),V(`li`,{key:e.slug,class:`flex justify-between gap-3 py-1.5`},[U(`span`,Y_,O(e.title),1),U(`span`,X_,O(e.views),1)]))),128))])]),(B(!0),V(R,null,L(s.value,([e,t])=>(B(),V(`section`,{key:e,class:`m-card p-4`},[U(`h2`,Z_,O(N(X)(e)),1),t.length?K(``,!0):(B(),V(`p`,Q_,O(N(X)(`Nothing here yet.`)),1)),U(`ul`,$_,[(B(!0),V(R,null,L(t,e=>(B(),V(`li`,{key:e.name+(e.channel??``),class:`flex justify-between gap-3 py-1.5`},[U(`span`,e1,O(e.name||N(X)(`Direct`)),1),U(`span`,t1,O(e.visits),1)]))),128))])]))),128))]),U(`section`,n1,[U(`h2`,r1,O(N(X)(`When people visit`)),1),U(`div`,i1,[(B(!0),V(R,null,L(e.heatmap,e=>(B(),V(`div`,{key:e.day,class:`flex items-center gap-0.5`},[U(`span`,a1,O(e.day),1),(B(!0),V(R,null,L(e.hours,(t,n)=>(B(),V(`span`,{key:n,class:`block h-5 min-w-3 flex-1 rounded-sm border border-line`,title:`${e.day} ${n}:00 · ${t}`,style:ve({background:`color-mix(in srgb, var(--m-brand) ${Math.round(t/o.value*100)}%, var(--m-panel-2))`})},null,12,o1))),128))]))),128))])]),U(`section`,s1,[U(`h2`,c1,[G(O(N(X)(`Programs`))+` `,1),U(`span`,l1,`· `+O(e.bots.total),1)]),e.bots.names.length?K(``,!0):(B(),V(`p`,u1,O(N(X)(`Nothing here yet.`)),1)),U(`ul`,d1,[(B(!0),V(R,null,L(e.bots.names,e=>(B(),V(`li`,{key:e.name,class:`flex justify-between gap-3 py-1.5`},[U(`span`,null,[G(O(e.name)+` `,1),U(`span`,f1,O(e.kind),1)]),U(`span`,p1,O(e.hits),1)]))),128))])]),U(`p`,m1,[U(`span`,h1,O(N(X)(`Download`))+`:`,1),(B(!0),V(R,null,L(e.exports,(e,t)=>(B(),V(`a`,{key:t,href:l(String(t)),class:`m-btn m-btn-secondary`},O(e)+` (CSV)`,9,g1))),128))])],64))}}),v1={class:`font-display mb-6 text-2xl font-bold`},y1={key:0,class:`m-card p-5 text-sm text-muted`},b1={key:1,class:`m-card divide-y divide-line`},x1={class:`min-w-0`},S1={class:`truncate font-semibold`},C1={class:`truncate text-xs text-muted`},w1={class:`m-badge`},T1={key:2,class:`mt-4 flex gap-2`},E1=I({__name:`ListPage`,props:{data:{},current_page:{},last_page:{},path:{}},setup(e){let t=e,n=pc(()=>Q.path.includes(`/reviews`)?`reviews`:`pages`),r=pc(()=>n.value===`reviews`?`Reviews`:`Pages`),i=e=>n.value===`reviews`?e.author:e.title,a=e=>n.value===`reviews`?e.rating?`★`.repeat(e.rating):``:e.slug,o=e=>n.value===`reviews`?e.is_visible:e.is_published,s=e=>`${Q.path.split(`?`)[0]}?page=${e}`;return(e,n)=>(B(),V(R,null,[U(`h1`,v1,O(N(X)(r.value)),1),t.data.length?(B(),V(`ul`,b1,[(B(!0),V(R,null,L(t.data,e=>(B(),V(`li`,{key:e.id,class:`flex items-center justify-between gap-3 p-4`},[U(`div`,x1,[U(`p`,S1,O(i(e)),1),U(`p`,C1,O(a(e)),1)]),U(`span`,w1,O(o(e)?N(X)(`Published`):N(X)(`Draft`)),1)]))),128))])):(B(),V(`p`,y1,O(N(X)(`Nothing here yet.`)),1)),t.last_page>1?(B(),V(`nav`,T1,[t.current_page>1?(B(),H(Z,{key:0,href:s(t.current_page-1),class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Previous`)),1)]),_:1},8,[`href`])):K(``,!0),t.current_page[G(O(N(X)(`Next`)),1)]),_:1},8,[`href`])):K(``,!0)])):K(``,!0)],64))}}),D1={class:`space-y-5`},O1={key:0,class:`flex items-center gap-2 text-sm`},k1=[`onUpdate:modelValue`],A1=[`for`],j1={key:0,class:`text-muted`},M1=[`id`,`onUpdate:modelValue`],N1={key:0,value:``},P1=[`value`],F1=[`id`,`onUpdate:modelValue`,`rows`,`maxlength`,`required`],I1={key:3,class:`flex gap-2`},L1=[`id`,`onUpdate:modelValue`],R1=[`onClick`],z1=[`id`,`value`,`onInput`],B1={key:5,class:`space-y-2`},V1=[`src`],H1=[`onUpdate:modelValue`,`aria-label`],U1=[`onClick`],W1=[`onClick`],G1={key:6,class:`space-y-3`},K1=[`for`],q1=[`id`,`onUpdate:modelValue`],J1=[`id`,`onUpdate:modelValue`],Y1=[`onClick`],X1=[`onClick`],Z1=[`id`,`onUpdate:modelValue`,`type`,`maxlength`,`required`],Q1=[`src`],$1={key:2,class:`mt-1 text-xs text-muted`},e0={key:3,class:`m-help`},t0={key:4,class:`m-error`},n0=I({__name:`FormFields`,props:{fields:{},values:{},errors:{},prefix:{}},setup(e){let t=e,n=pc(()=>t.fields.filter(e=>!(e.advanced&&J.view===`simple`))),r=e=>J.view===`simple`&&e.simple_label||e.label,i=e=>J.view===`simple`&&e.simple_help||e.help,a=M(null),o=M(null),s=e=>t.values[e]=Array.isArray(t.values[e])?t.values[e]:[],c=e=>s(e).join(` +`),l=(e,n)=>t.values[e]=n.split(` +`),u=e=>Object.values(e.items??{}),d=e=>s(e.key).push(Object.fromEntries(u(e).map(e=>[e.key,``]))),f=J.permissions.includes(`media.view`);return(t,p)=>(B(),V(`div`,D1,[(B(!0),V(R,null,L(n.value,t=>(B(),V(`div`,{key:t.key},[t.type===`toggle`?(B(),V(`label`,O1,[F(U(`input`,{"onUpdate:modelValue":n=>e.values[t.key]=n,type:`checkbox`},null,8,k1),[[pu,e.values[t.key]]]),G(` `+O(N(X)(r(t))),1)])):(B(),V(R,{key:1},[U(`label`,{for:`f-`+t.key,class:`m-label`},[G(O(N(X)(r(t))),1),t.required?(B(),V(`span`,j1,` *`)):K(``,!0)],8,A1),t.type===`select`?F((B(),V(`select`,{key:0,id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,class:`m-input`},[t.required?K(``,!0):(B(),V(`option`,N1)),(B(!0),V(R,null,L(t.options,(e,t)=>(B(),V(`option`,{key:t,value:t},O(e),9,P1))),128))],8,M1)),[[gu,e.values[t.key]]]):t.type===`markdown`?(B(),H(uf,{key:1,id:`f-`+t.key,modelValue:e.values[t.key],"onUpdate:modelValue":n=>e.values[t.key]=n,required:t.required,maxlength:t.max??void 0},null,8,[`id`,`modelValue`,`onUpdate:modelValue`,`required`,`maxlength`])):t.type===`textarea`||t.type===`lines`?F((B(),V(`textarea`,{key:2,id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,rows:t.type===`lines`?5:4,maxlength:t.max??void 0,required:t.required,class:`m-input`},null,8,F1)),[[q,e.values[t.key]]]):t.type===`media`?(B(),V(`div`,I1,[F(U(`input`,{id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,maxlength:`2048`,class:`m-input`},null,8,L1),[[q,e.values[t.key]]]),N(f)?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary shrink-0`,onClick:e=>a.value=t.key},O(N(X)(`Choose`)),9,R1)):K(``,!0)])):t.type===`list`?(B(),V(`textarea`,{key:4,id:`f-`+t.key,value:c(t.key),rows:`5`,class:`m-input`,onInput:e=>l(t.key,e.target.value)},null,40,z1)):t.type===`media_list`?(B(),V(`div`,B1,[(B(!0),V(R,null,L(s(t.key),(n,i)=>(B(),V(`div`,{key:i,class:`flex items-center gap-2`},[U(`img`,{src:n,alt:``,class:`h-12 w-12 rounded border border-line object-cover`},null,8,V1),F(U(`input`,{"onUpdate:modelValue":n=>e.values[t.key][i]=n,maxlength:`2048`,class:`m-input`,"aria-label":N(X)(r(t))},null,8,H1),[[q,e.values[t.key][i]]]),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:n=>e.values[t.key].splice(i,1)},O(N(X)(`Remove`)),9,U1)]))),128)),N(f)?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>o.value=t.key},O(N(X)(`Add a picture`)),9,W1)):K(``,!0)])):t.type===`repeater`?(B(),V(`div`,G1,[(B(!0),V(R,null,L(s(t.key),(n,r)=>(B(),V(`div`,{key:r,class:`m-card space-y-2 p-3`},[(B(!0),V(R,null,L(u(t),e=>(B(),V(`div`,{key:e.key},[U(`label`,{class:`m-label`,for:`f-${t.key}-${r}-${e.key}`},O(N(X)(e.label)),9,K1),e.type===`textarea`?F((B(),V(`textarea`,{key:0,id:`f-${t.key}-${r}-${e.key}`,"onUpdate:modelValue":t=>n[e.key]=t,rows:`3`,class:`m-input`},null,8,q1)),[[q,n[e.key]]]):F((B(),V(`input`,{key:1,id:`f-${t.key}-${r}-${e.key}`,"onUpdate:modelValue":t=>n[e.key]=t,class:`m-input`},null,8,J1)),[[q,n[e.key]]])]))),128)),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:n=>e.values[t.key].splice(r,1)},O(N(X)(`Remove`)),9,Y1)]))),128)),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>d(t)},O(N(X)(`Add`)),9,X1)])):F((B(),V(`input`,{key:7,id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,type:t.type===`number`?`number`:t.type===`date`?`date`:`text`,maxlength:t.max??void 0,required:t.required,class:`m-input`},null,8,Z1)),[[xu,e.values[t.key]]]),t.type===`media`&&e.values[t.key]?(B(),V(`img`,{key:8,src:e.values[t.key],alt:``,class:`mt-2 h-24 w-auto rounded-lg border border-line object-cover`},null,8,Q1)):K(``,!0)],64)),t.type===`lines`||t.type===`list`?(B(),V(`p`,$1,O(N(X)(`One per line.`)),1)):K(``,!0),i(t)?(B(),V(`p`,e0,O(N(X)(i(t))),1)):K(``,!0),e.errors?.[(e.prefix??``)+t.key]?(B(),V(`p`,t0,O(e.errors[(e.prefix??``)+t.key]),1)):K(``,!0)]))),128)),a.value?(B(),H(Yd,{key:0,onPick:p[0]||=t=>{e.values[a.value]=t,a.value=null},onClose:p[1]||=e=>a.value=null})):K(``,!0),o.value?(B(),H(Yd,{key:1,onPick:p[2]||=e=>{s(o.value).push(e),o.value=null},onClose:p[3]||=e=>o.value=null})):K(``,!0)]))}}),r0=(e,t)=>J.view===`simple`&&t?t:e,i0={class:`mb-6 flex items-center justify-between gap-3`},a0={class:`font-display text-2xl font-bold`},o0=[`disabled`],s0=I({__name:`RecordForm`,props:{resource:{},record:{}},setup(e){let t=e,n=`${J.base}/records/${t.resource.key}`,r=Yu({...t.record.values});async function i(){(t.record.id===null?await r.send(`post`,n):await r.send(`put`,`${n}/${t.record.id}`))&&($(X(`Saved.`)),c4(n))}return(t,a)=>(B(),V(R,null,[U(`div`,i0,[U(`h1`,a0,O(e.record.id===null?N(X)(`New`)+`: `+N(X)(N(r0)(e.resource.singular,e.resource.simple_singular)):N(X)(N(r0)(e.resource.singular,e.resource.simple_singular))),1),W(Z,{href:n,class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Back`)),1)]),_:1})]),U(`form`,{class:`m-card max-w-3xl space-y-5 p-5`,onSubmit:Du(i,[`prevent`])},[W(n0,{fields:e.resource.fields,values:N(r).values,errors:N(r).errors},null,8,[`fields`,`values`,`errors`]),U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(r).busy},O(N(r).busy?N(X)(`Saving…`):N(X)(`Save`)),9,o0)],32)],64))}}),c0={class:`mb-4 font-display text-2xl font-bold`},l0={class:`mb-4 flex flex-wrap gap-2`,role:`tablist`},u0=[`aria-selected`,`onClick`],d0={class:`ml-1 text-xs opacity-75`},f0={key:0,class:`m-error mb-3`,role:`alert`},p0={key:1,class:`m-card p-5 text-sm text-muted`},m0={key:2,class:`space-y-3`},h0=[`aria-expanded`,`onClick`],g0=[`title`],_0={class:`min-w-0 flex-1`},v0={class:`block truncate font-semibold`},y0={class:`font-normal text-muted`},b0={class:`block truncate text-sm text-muted`},x0={class:`shrink-0 text-xs text-muted`},S0={key:0,class:`space-y-4 border-t border-line p-4 text-sm`},C0={key:0,class:`m-error`},w0={key:1,class:`whitespace-pre-line`},T0={key:2,class:`grid gap-1`},E0={class:`inline text-muted`},D0={class:`inline font-medium`},O0={key:0},k0={class:`inline text-muted`},A0={class:`inline font-medium`},j0={class:`flex flex-wrap gap-2`},M0=[`href`],N0=[`href`],P0=[`href`],F0=[`onClick`],I0=[`onClick`],L0=[`disabled`,`onClick`],R0=[`disabled`,`onClick`],z0={key:3,class:`space-y-1`},B0={class:`text-xs text-muted`},V0=[`onSubmit`],H0=[`onUpdate:modelValue`,`placeholder`,`aria-label`],U0=[`disabled`],W0={key:5,class:`space-y-2 border-t border-line pt-3`},G0={class:`text-xs text-muted`},K0={key:0,class:`list-disc pl-5 text-xs text-muted`},q0={class:`flex flex-wrap gap-2`},J0=[`onClick`],Y0=[`onClick`],X0=[`onClick`],Z0=[`onClick`],Q0=[`onClick`],$0=[`onClick`],ev=[`onClick`],tv={key:3,class:`m-card mt-8 p-4`},nv={class:`mb-1 font-semibold`},rv={class:`mb-3 text-sm text-muted`},iv={class:`grid gap-6 text-sm sm:grid-cols-2`},av={class:`mb-1 font-medium`},ov={class:`mb-1 font-medium`},sv={class:`truncate`},cv={class:`shrink-0`},lv={key:0,class:`text-muted`},uv={key:0,class:`text-muted`},dv={key:0},fv={class:`mb-1 font-medium`},pv={class:`truncate`},mv={key:4,class:`m-card mt-8 p-4`},hv={class:`mb-2 font-semibold`},gv={class:`divide-y divide-line text-sm`},_v={key:0,class:`text-muted`},vv=[`onClick`],yv=I({__name:`LeadsInbox`,props:{view:{},items:{},counts:{},open:{},blocks:{},can:{},report:{}},setup(e){let t=e,n=`${J.base}/leads`,r=M(t.open),i=an({}),a=M(``),o=pc(()=>[[`waiting`,X(`Waiting`)],[`handled`,X(`Handled`)],...t.can.manage?[[`other`,X(`Other`)],[`spam`,X(`Spam`)]]:[]]),s=e=>new Date(e).toLocaleString(J.locale===`nl`?`nl-NL`:`en-GB`,{dateStyle:`medium`,timeStyle:`short`});async function c(e){r.value=r.value===e.id?null:e.id,r.value===e.id&&e.is_new&&(await Y.post(`${n}/${e.id}/opened`),e.is_new=!1)}async function l(e,t){a.value=``;try{await e(),t&&$(t),await l4()}catch(e){if(e instanceof Gu&&e.status===422)a.value=e.errors?.message??Object.values(e.errors??{})[0]??X(`This could not be done.`);else throw e}}let u=(e,t)=>l(()=>Y.put(`${n}/${e.id}/handled`,{handled:!e.handled||!!t,outcome:t}),X(`Saved.`)),d=e=>l(async()=>{await Y.post(`${n}/${e.id}/notes`,{text:i[e.id]}),i[e.id]=``},X(`Note saved.`)),f=(e,t)=>l(()=>Y.put(`${n}/${e.id}/folder`,{folder:t}),X(`Moved.`)),p=(e,t)=>l(()=>Y.post(`${n}/${e.id}/block`,{type:t}),X(`Blocked.`)),m=e=>l(()=>Y.delete(`${n}/blocks/${e.id}`),X(`The block is lifted.`)),h=e=>window.confirm(X(`Are you sure?`))&&l(()=>Y.delete(`${n}/${e.id}`),X(`Deleted.`)),g=e=>c4(`${n}${e===`waiting`?``:`?view=`+e}`);return(t,n)=>(B(),V(R,null,[U(`h1`,c0,O(N(X)(`Requests`)),1),U(`div`,l0,[(B(!0),V(R,null,L(o.value,([t,n])=>(B(),V(`button`,{key:t,type:`button`,role:`tab`,"aria-selected":e.view===t,class:D([`m-btn`,e.view===t?`m-btn-primary`:`m-btn-secondary`]),onClick:e=>g(t)},[G(O(n)+` `,1),U(`span`,d0,O(e.counts[t]),1)],10,u0))),128))]),a.value?(B(),V(`p`,f0,O(a.value),1)):K(``,!0),e.items.length?(B(),V(`ul`,m0,[(B(!0),V(R,null,L(e.items,t=>(B(),V(`li`,{key:t.id,class:`m-card`},[U(`button`,{type:`button`,class:`flex w-full items-center gap-3 p-4 text-left`,"aria-expanded":r.value===t.id,onClick:e=>c(t)},[t.is_new?(B(),V(`span`,{key:0,class:`h-2.5 w-2.5 shrink-0 rounded-full bg-accent`,title:N(X)(`New`)},null,8,g0)):K(``,!0),U(`span`,_0,[U(`span`,v0,[G(O(t.name)+` `,1),U(`span`,y0,`· `+O(t.subject),1)]),U(`span`,b0,O(t.message??t.kind),1)]),U(`span`,x0,O(s(t.created_at)),1)],8,h0),r.value===t.id?(B(),V(`div`,S0,[t.notify_failed?(B(),V(`p`,C0,O(N(X)(`The mail about this request could not be sent.`)),1)):K(``,!0),t.message?(B(),V(`p`,w0,O(t.message),1)):K(``,!0),Object.keys(t.answers).length||t.location?(B(),V(`dl`,T0,[(B(!0),V(R,null,L(t.answers,(e,t)=>(B(),V(`div`,{key:t},[U(`dt`,E0,O(t)+`: `,1),U(`dd`,D0,O(e),1)]))),128)),t.location?(B(),V(`div`,O0,[U(`dt`,k0,O(N(X)(`Where`))+`: `,1),U(`dd`,A0,O(t.location),1)])):K(``,!0)])):K(``,!0),U(`div`,j0,[t.call_link?(B(),V(`a`,{key:0,href:t.call_link,class:`m-btn m-btn-primary`},O(N(X)(`Call`)),9,M0)):K(``,!0),t.whatsapp_link?(B(),V(`a`,{key:1,href:t.whatsapp_link,target:`_blank`,rel:`noopener`,class:`m-btn m-btn-secondary`},`WhatsApp`,8,N0)):K(``,!0),t.mail_link?(B(),V(`a`,{key:2,href:t.mail_link,class:`m-btn m-btn-secondary`},O(N(X)(`Mail`)),9,P0)):K(``,!0),e.can.handle&&!t.handled&&t.folder!==`spam`?(B(),V(`button`,{key:3,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>u(t)},O(N(X)(`Handled`)),9,F0)):K(``,!0),e.can.handle&&t.handled?(B(),V(R,{key:4},[U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>u(t)},O(N(X)(`Back to waiting`)),9,I0),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,disabled:t.outcome===`won`,onClick:e=>u(t,`won`)},O(N(X)(`It became a job`)),9,L0),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,disabled:t.outcome===`lost`,onClick:e=>u(t,`lost`)},O(N(X)(`No job`)),9,R0)],64)):K(``,!0)]),t.notes.length?(B(),V(`div`,z0,[(B(!0),V(R,null,L(t.notes,(e,t)=>(B(),V(`p`,{key:t,class:`rounded bg-surface-2 p-2`},[U(`span`,B0,O(e.at)+` · `+O(e.by),1),n[0]||=U(`br`,null,null,-1),G(O(e.text),1)]))),128))])):K(``,!0),e.can.handle?(B(),V(`form`,{key:4,class:`flex gap-2`,onSubmit:Du(e=>d(t),[`prevent`])},[F(U(`input`,{"onUpdate:modelValue":e=>i[t.id]=e,class:`m-input`,placeholder:N(X)(`A note for yourself`),"aria-label":N(X)(`A note for yourself`),maxlength:`2000`},null,8,H0),[[q,i[t.id]]]),U(`button`,{type:`submit`,class:`m-btn m-btn-secondary`,disabled:!i[t.id]},O(N(X)(`Add`)),9,U0)],40,V0)):K(``,!0),e.can.manage?(B(),V(`div`,W0,[U(`p`,G0,[G(O(N(X)(`Screening`))+`: `+O(t.folder),1),t.source?(B(),V(R,{key:0},[G(` · `+O(t.source),1)],64)):K(``,!0),t.ip?(B(),V(R,{key:1},[G(` · `+O(t.ip),1)],64)):K(``,!0)]),t.reasons?.length?(B(),V(`ul`,K0,[(B(!0),V(R,null,L(t.reasons,(e,t)=>(B(),V(`li`,{key:t},O(e),1))),128))])):K(``,!0),U(`div`,q0,[t.folder===`inbox`?K(``,!0):(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>f(t,`inbox`)},O(N(X)(`It is a real request`)),9,J0)),t.folder===`inbox`?(B(),V(`button`,{key:1,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>f(t,`other`)},O(N(X)(`This is not a request`)),9,Y0)):K(``,!0),t.email?(B(),V(`button`,{key:2,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>p(t,`email`)},O(N(X)(`Block this address`)),9,X0)):K(``,!0),t.email?(B(),V(`button`,{key:3,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>p(t,`domain`)},O(N(X)(`Block its domain`)),9,Z0)):K(``,!0),t.phone?(B(),V(`button`,{key:4,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>p(t,`phone`)},O(N(X)(`Block this number`)),9,Q0)):K(``,!0),t.ip?(B(),V(`button`,{key:5,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>p(t,`ip`)},O(N(X)(`Block the sender address`)),9,$0)):K(``,!0)])])):K(``,!0),e.can.delete?(B(),V(`button`,{key:6,type:`button`,class:`m-btn m-btn-danger`,onClick:e=>h(t)},O(N(X)(`Delete`)),9,ev)):K(``,!0)])):K(``,!0)]))),128))])):(B(),V(`p`,p0,O(N(X)(`Nothing here yet.`)),1)),e.report?(B(),V(`section`,tv,[U(`h2`,nv,O(N(X)(`What it brought in`)),1),U(`p`,rv,O(N(X)(`The last :days days`,{days:e.report.days}))+`: `+O(e.report.requests)+` `+O(N(X)(`requests`))+`, `+O(e.report.won)+` `+O(N(X)(`became a job`))+`, `+O(e.report.kept_away.other+e.report.kept_away.spam)+` `+O(N(X)(`kept away by the screening`))+`. `,1),U(`div`,iv,[U(`div`,null,[U(`h3`,av,O(N(X)(`Ways in`)),1),U(`ul`,null,[(B(!0),V(R,null,L(e.report.ways,e=>(B(),V(`li`,{key:e.name,class:`flex justify-between`},[U(`span`,null,O(e.name),1),U(`strong`,null,O(e.count),1)]))),128))])]),(B(!0),V(R,null,L([[N(X)(`Pages`),e.report.pages],[N(X)(`Sources`),e.report.sources],[N(X)(`About`),e.report.subjects]],([e,t])=>(B(),V(`div`,{key:e},[U(`h3`,ov,O(e),1),U(`ul`,null,[(B(!0),V(R,null,L(t,e=>(B(),V(`li`,{key:e.name,class:`flex justify-between gap-3`},[U(`span`,sv,O(e.name),1),U(`span`,cv,[U(`strong`,null,O(e.count),1),e.won?(B(),V(`span`,lv,` (`+O(e.won)+` ✓)`,1)):K(``,!0)])]))),128)),t.length?K(``,!0):(B(),V(`li`,uv,`—`))])]))),128)),e.report.tap_pages.length?(B(),V(`div`,dv,[U(`h3`,fv,O(N(X)(`Where the buttons are pressed`)),1),U(`ul`,null,[(B(!0),V(R,null,L(e.report.tap_pages,e=>(B(),V(`li`,{key:e.name,class:`flex justify-between gap-3`},[U(`span`,pv,O(e.name),1),U(`strong`,null,O(e.count),1)]))),128))])])):K(``,!0)])])):K(``,!0),e.blocks?.length?(B(),V(`section`,mv,[U(`h2`,hv,O(N(X)(`Blocked senders`)),1),U(`ul`,gv,[(B(!0),V(R,null,L(e.blocks,e=>(B(),V(`li`,{key:e.id,class:`flex items-center justify-between gap-3 py-2`},[U(`span`,null,[G(O(e.type)+`: `,1),U(`strong`,null,O(e.value),1),e.expires_at?(B(),V(`span`,_v,` · `+O(N(X)(`until`))+` `+O(s(e.expires_at)),1)):K(``,!0)]),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>m(e)},O(N(X)(`Lift`)),9,vv)]))),128))])])):K(``,!0)],64))}}),bv={class:`font-display mb-2 text-2xl font-bold`},xv={class:`mb-6 text-sm text-muted`},Sv={key:0,class:`m-card p-5 text-sm text-muted`},Cv={key:1,class:`space-y-4`},wv={class:`font-display text-lg font-bold`},Tv={key:0,class:`ml-2 text-sm font-normal text-muted`},Ev={key:0,class:`text-sm font-semibold`},Dv={class:`mt-1 list-disc space-y-1 pl-5 text-sm`},Ov=I({__name:`UpdatesList`,props:{releases:{}},setup(e){let t=e;return(e,n)=>(B(),V(R,null,[U(`h1`,bv,O(N(X)(`Updates`)),1),U(`p`,xv,O(N(X)(`What changed on your website`)),1),t.releases.length?(B(),V(`div`,Cv,[(B(!0),V(R,null,L(t.releases,e=>(B(),V(`section`,{key:e.version,class:`m-card p-5`},[U(`h2`,wv,[G(O(e.version)+` `,1),e.date?(B(),V(`span`,Tv,O(e.date),1)):K(``,!0)]),(B(!0),V(R,null,L(e.sections,(e,t)=>(B(),V(`div`,{key:t,class:`mt-3`},[e.title?(B(),V(`h3`,Ev,O(e.title),1)):K(``,!0),U(`ul`,Dv,[(B(!0),V(R,null,L(e.items,(e,t)=>(B(),V(`li`,{key:t},O(e),1))),128))])]))),128))]))),128))])):(B(),V(`p`,Sv,O(N(X)(`No changes recorded yet.`)),1))],64))}}),kv={class:`font-display mb-2 text-2xl font-bold`},Av={class:`mb-6 text-sm text-muted`},jv={class:`m-card mb-6 divide-y divide-line`},Mv={class:`font-semibold`},Nv={class:`text-xs text-muted`},Pv={class:`text-xs text-muted`},Fv={key:0,class:`flex gap-2`},Iv=[`onClick`],Lv=[`onClick`],Rv={class:`mb-3 font-semibold`},zv={key:0,class:`m-card p-5 text-sm text-muted`},Bv={key:1,class:`m-card divide-y divide-line`},Vv={class:`min-w-0`},Hv={class:`truncate font-semibold`},Uv={class:`truncate text-xs text-muted`},Wv={class:`m-badge`},Gv=I({__name:`SharingPage`,props:{live:{type:Boolean},platforms:{},shares:{},notice:{}},setup(e){let t=e,n={connected:[`The account is connected.`,!1],denied:[`The network did not give permission, or it was cancelled.`,!0],failed:[`Connecting did not complete. Try again.`,!0],state:[`Connecting did not complete. Try again.`,!0]};aa(()=>{t.notice&&n[t.notice]&&$(X(n[t.notice][0]),n[t.notice][1])});let r=e=>window.location.assign(`${J.base}/sharing/${e}/connect`);async function i(e){window.confirm(X(`Are you sure?`))&&(await Y.delete(`${J.base}/sharing/${e}`),$(X(`The account is disconnected. What was shared stays where it is.`)),await l4())}return(e,n)=>(B(),V(R,null,[U(`h1`,kv,O(N(X)(`Sharing`)),1),U(`p`,Av,O(t.live?N(X)(`Posts are shared for real.`):N(X)(`Dry run: nothing is sent to the networks. Turn on "Post for real" under Settings when the site is live.`)),1),U(`section`,jv,[(B(!0),V(R,null,L(t.platforms,e=>(B(),V(`div`,{key:e.platform,class:`flex flex-wrap items-center justify-between gap-3 p-4`},[U(`div`,null,[U(`p`,Mv,O(e.label),1),U(`p`,Nv,[e.connected?(B(),V(R,{key:0},[G(O(N(X)(`Connected`))+O(e.account?` · `+e.account:``),1)],64)):e.can_connect?(B(),V(R,{key:1},[G(O(N(X)(`Not connected`)),1)],64)):(B(),V(R,{key:2},[G(O(N(X)(`Fill in under Settings:`))+` `+O(e.missing),1)],64))]),U(`p`,Pv,[G(O(N(X)(`Return address for the app`))+`: `,1),U(`code`,null,O(e.callback_url),1)])]),N(J).permissions.includes(`sharing.manage`)?(B(),V(`div`,Fv,[e.can_connect?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>r(e.platform)},O(e.connected?N(X)(`Connect again`):N(X)(`Connect`)),9,Iv)):K(``,!0),e.connected?(B(),V(`button`,{key:1,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>i(e.platform)},O(N(X)(`Disconnect`)),9,Lv)):K(``,!0)])):K(``,!0)]))),128))]),U(`h2`,Rv,O(N(X)(`Recently shared`)),1),t.shares.length?(B(),V(`ul`,Bv,[(B(!0),V(R,null,L(t.shares,e=>(B(),V(`li`,{key:e.id,class:`flex items-center justify-between gap-3 p-4 text-sm`},[U(`div`,Vv,[U(`p`,Hv,O(e.post_title),1),U(`p`,Uv,[G(O(e.platform)+` · `+O(e.at),1),e.error?(B(),V(R,{key:0},[G(` · `+O(e.error),1)],64)):K(``,!0)])]),U(`span`,Wv,O(e.dry_run?N(X)(`Dry run`):e.status===`shared`?N(X)(`Shared`):N(X)(`Failed`)),1)]))),128))])):(B(),V(`p`,zv,O(N(X)(`Nothing has been shared yet.`)),1))],64))}}),Kv={class:`font-display mb-2 text-2xl font-bold`},qv={class:`mb-6 text-sm text-muted`},Jv={class:`grid gap-3 sm:grid-cols-3`},Yv={class:`m-card p-4`},Xv={class:`text-muted`},Zv={class:`text-2xl font-bold`},Qv={class:`text-sm text-muted`},$v={class:`m-card p-4`},ey={class:`text-muted`},ty={class:`text-2xl font-bold`},ny={class:`text-sm text-muted`},ry={class:`m-card p-4`},iy={class:`text-muted`},ay={class:`text-2xl font-bold`},oy={key:0,class:`text-sm text-muted`},sy={class:`m-card mt-3 p-4`},cy={class:`flex justify-between`},ly={key:0,class:`flex justify-between text-muted`},uy={class:`mt-1 flex justify-between text-lg`},dy={key:0,class:`mt-2 text-sm text-muted`},fy={key:1,class:`mt-1 text-sm text-muted`},py={key:2,class:`m-card mt-6 p-5 text-sm text-muted`},my={class:`font-display text-lg font-bold`},hy={key:0,class:`ml-2 text-sm font-normal text-muted`},gy={class:`float-right text-base`},_y={class:`mt-3 divide-y divide-line text-sm`},vy={class:`min-w-0`},yy={class:`text-muted`},by={class:`shrink-0 text-muted`},xy={class:`mt-6 text-xs text-muted`},Sy=I({__name:`CostsView`,props:{groups:{},costs:{},totals:{},source:{}},setup(e){let t=e=>e===null?`—`:new Intl.NumberFormat(void 0,{style:`currency`,currency:`EUR`}).format(e),n=e=>new Intl.NumberFormat().format(e);return(r,i)=>(B(),V(R,null,[U(`h1`,Kv,O(N(X)(`What it cost`)),1),U(`p`,qv,O(N(X)(`What was built, and what it cost`)),1),U(`div`,Jv,[U(`div`,Yv,[U(`p`,Xv,O(N(X)(`The work`)),1),U(`p`,Zv,O(t(e.costs.work_eur)),1),U(`p`,Qv,O(N(X)(`:hours hours at :rate an hour`,{hours:e.costs.hours,rate:t(e.costs.hourly_rate)})),1)]),U(`div`,$v,[U(`p`,ey,O(N(X)(`The AI model`)),1),U(`p`,ty,O(t(e.costs.ai_eur)),1),U(`p`,ny,O(N(X)(`:count tokens`,{count:n(e.totals.tokens)})),1)]),U(`div`,ry,[U(`p`,iy,O(N(X)(`Hosting`)),1),U(`p`,ay,O(t(e.costs.hosting.eur)),1),e.costs.hosting.from?(B(),V(`p`,oy,O(N(X)(`:amount a year, from :day`,{amount:t(e.costs.hosting.per_year),day:e.costs.hosting.from})),1)):K(``,!0)])]),U(`div`,sy,[U(`p`,cy,[U(`span`,null,O(N(X)(`Total`)),1),U(`b`,null,O(t(e.costs.total_eur)),1)]),e.costs.discount?(B(),V(`p`,ly,[U(`span`,null,O(N(X)(`:percent% discount on the work, until :day`,{percent:e.costs.discount.percent,day:e.costs.discount.until})),1),U(`span`,null,`− `+O(t(e.costs.discount.eur)),1)])):K(``,!0),U(`p`,uy,[U(`span`,null,O(N(X)(`To pay`)),1),U(`b`,null,O(t(e.costs.due_eur)),1)])]),e.costs.without_hours?(B(),V(`p`,dy,O(N(X)(`:count pieces of work have no hours yet.`,{count:e.costs.without_hours})),1)):K(``,!0),e.totals.unpriced?(B(),V(`p`,fy,O(N(X)(`:count pieces of work could not be priced yet.`,{count:e.totals.unpriced})),1)):K(``,!0),e.groups.length?K(``,!0):(B(),V(`p`,py,O(N(X)(`No work has been recorded yet.`)),1)),(B(!0),V(R,null,L(e.groups,e=>(B(),V(`section`,{key:e.version??`open`,class:`m-card mt-4 p-5`},[U(`h2`,my,[G(O(e.version??N(X)(`Not released yet`))+` `,1),e.date?(B(),V(`span`,hy,O(e.date),1)):K(``,!0),U(`span`,gy,O(t(e.eur+e.work_eur)),1)]),U(`ul`,_y,[(B(!0),V(R,null,L(e.items,(e,n)=>(B(),V(`li`,{key:n,class:`flex items-baseline justify-between gap-3 py-2`},[U(`span`,vy,[U(`span`,yy,O(e.date),1),G(` `+O(e.name),1)]),U(`span`,by,O(t((e.eur??0)+(e.work_eur??0))),1)]))),128))])]))),128)),U(`p`,xy,O(e.source===`config`?N(X)(`Priced with the fixed rates of the site.`):e.source===`mixed`?N(X)(`Priced with the price of each day, and for some rows with the fixed rates of the site.`):N(X)(`Priced with the price list and the euro rate of the day of each row.`)),1)],64))}}),Cy={class:`font-display mb-4 text-2xl font-bold`},wy=[`aria-label`],Ty={class:`mb-3 text-lg font-bold`},Ey={key:0,class:`m-card mb-5 p-4 text-muted`},Dy={class:`grid grid-cols-2 gap-3`},Oy={class:`m-card col-span-2 p-4`},ky={class:`text-muted`},Ay={class:`text-4xl font-bold`},jy={key:0,class:`text-muted`},My={class:`text-muted`},Ny={key:0,class:`m-card col-span-2 p-4`},Py={class:`text-muted`},Fy={class:`text-4xl font-bold`},Iy={key:0,class:`text-muted`},Ly={class:`m-card p-4`},Ry={class:`text-muted`},zy={class:`text-3xl font-bold`},By={class:`m-card p-4`},Vy={class:`text-muted`},Hy={class:`text-3xl font-bold`},Uy={key:1,class:`mt-8`},Wy={class:`mb-1 text-lg font-bold`},Gy={key:0,class:`mb-3 text-muted`},Ky={class:`m-card p-4`},qy=[`aria-label`],Jy=[`title`],Yy={class:`mt-2 flex justify-between text-sm text-muted`},Xy={key:2,class:`mt-8`},Zy={class:`mb-3 text-lg font-bold`},Qy={class:`m-card divide-y divide-line`},$y={class:`flex items-baseline justify-between gap-3`},e2={class:`min-w-0 break-words font-semibold`},t2={class:`shrink-0 text-muted`},n2={key:3,class:`mt-8`},r2={class:`mb-3 text-lg font-bold`},i2={class:`m-card divide-y divide-line`},a2={class:`flex items-baseline justify-between gap-3`},o2={class:`min-w-0 font-semibold`},s2={class:`shrink-0 text-muted`},c2={key:4,class:`mt-8`},l2={class:`mb-3 text-lg font-bold`},u2={class:`m-card divide-y divide-line`},d2={class:`min-w-0 font-semibold`},f2={class:`shrink-0 text-muted`},p2={key:5,class:`mt-8`},m2={class:`mb-3 text-lg font-bold`},h2={class:`m-card divide-y divide-line`},g2={class:`min-w-0 font-semibold`},_2={class:`shrink-0 text-muted`},v2={class:`mt-8 text-sm text-muted`},y2=I({__name:`NumbersView`,props:{period:{},periods:{},visitors:{},visitors_before:{},page_views:{},steps:{},pages:{},found:{},articles:{},contact:{},requests:{}},setup(e){let t=e,n=pc(()=>{if(t.visitors_before===null)return``;let e=t.visitors-t.visitors_before;return e===0?X(`The same as :period.`,{period:t.period.before}):X(e>0?`:count more than :period.`:`:count fewer than :period.`,{count:Math.abs(e),period:t.period.before})}),r=pc(()=>Math.max(1,...t.steps.map(e=>e.visitors))),i=pc(()=>t.steps.reduce((e,t)=>e===null||t.visitors>e.visitors?t:e,null)),a=(e,t)=>`${Math.round(e/Math.max(1,...t)*100)}%`,o=pc(()=>t.visitors===0&&(t.contact?.calls??0)===0&&(t.contact?.whatsapp??0)===0&&(t.requests?.count??0)===0);return(t,s)=>(B(),V(R,null,[U(`h1`,Cy,O(N(X)(`Numbers`)),1),U(`nav`,{class:`mb-5 flex flex-wrap gap-2`,"aria-label":N(X)(`Period`)},[(B(!0),V(R,null,L(e.periods,t=>(B(),H(Z,{key:t.key,href:`${N(J).base}/numbers?range=${t.key}`,class:D([`m-btn`,t.key===e.period.key?`m-btn-primary`:`m-btn-secondary`]),"aria-current":t.key===e.period.key?`true`:void 0},{default:P(()=>[G(O(t.button),1)]),_:2},1032,[`href`,`class`,`aria-current`]))),128))],8,wy),U(`h2`,Ty,O(e.period.label),1),o.value?(B(),V(`p`,Ey,O(N(X)(`Nothing has been counted in this period yet. As soon as people visit the site, you will see it here.`)),1)):K(``,!0),U(`div`,Dy,[U(`div`,Oy,[U(`p`,ky,O(N(X)(`Visitors`)),1),U(`p`,Ay,O(e.visitors),1),n.value?(B(),V(`p`,jy,O(n.value),1)):K(``,!0),U(`p`,My,O(N(X)(`Together they looked at :count pages.`,{count:e.page_views})),1)]),e.requests?(B(),V(`div`,Ny,[U(`p`,Py,O(N(X)(`Requests through the site`)),1),U(`p`,Fy,O(e.requests.count),1),e.requests.count?(B(),V(`p`,Iy,[e.requests.won?(B(),V(R,{key:0},[G(O(N(X)(`:count became a job.`,{count:e.requests.won})),1)],64)):K(``,!0),e.requests.waiting?(B(),V(R,{key:1},[G(O(N(X)(`:count still wait for an answer.`,{count:e.requests.waiting})),1)],64)):K(``,!0)])):K(``,!0),e.requests.waiting?(B(),H(Z,{key:1,href:`${N(J).base}/leads`,class:`m-btn m-btn-secondary mt-3`},{default:P(()=>[G(O(N(X)(`To the requests`)),1)]),_:1},8,[`href`])):K(``,!0)])):K(``,!0),e.contact?(B(),V(R,{key:1},[U(`div`,Ly,[U(`p`,Ry,O(N(X)(`Taps on Call`)),1),U(`p`,zy,O(e.contact.calls),1)]),U(`div`,By,[U(`p`,Vy,O(N(X)(`Taps on WhatsApp`)),1),U(`p`,Hy,O(e.contact.whatsapp),1)])],64)):K(``,!0)]),e.visitors>0?(B(),V(`section`,Uy,[U(`h2`,Wy,O(e.period.key===`12m`?N(X)(`Visitors per month`):N(X)(`Visitors per day`)),1),i.value&&i.value.visitors>0?(B(),V(`p`,Gy,O(N(X)(`Busiest: :when, with :count visitors.`,{when:i.value.label,count:i.value.visitors})),1)):K(``,!0),U(`div`,Ky,[U(`div`,{class:`flex h-36 items-end gap-px`,role:`img`,"aria-label":N(X)(`Visitors`)},[(B(!0),V(R,null,L(e.steps,(e,t)=>(B(),V(`div`,{key:t,class:`min-w-0 flex-1 rounded-t bg-brand`,style:ve({height:e.visitors>0?`${Math.max(4,Math.round(e.visitors/r.value*100))}%`:`2px`,opacity:e.visitors>0?1:.35}),title:`${e.label}: ${e.visitors}`},null,12,Jy))),128))],8,qy),U(`div`,Yy,[U(`span`,null,O(e.steps[0]?.label),1),U(`span`,null,O(e.steps[e.steps.length-1]?.label),1)])])])):K(``,!0),e.pages.length?(B(),V(`section`,Xy,[U(`h2`,Zy,O(N(X)(`Most viewed pages`)),1),U(`ul`,Qy,[(B(!0),V(R,null,L(e.pages,t=>(B(),V(`li`,{key:t.path,class:`p-4`},[U(`div`,$y,[U(`span`,e2,O(t.name),1),U(`span`,t2,O(N(X)(`:count times`,{count:t.views})),1)]),U(`div`,{class:`mt-2 h-1.5 rounded-full bg-brand`,style:ve({width:a(t.views,e.pages.map(e=>e.views))}),"aria-hidden":`true`},null,4)]))),128))])])):K(``,!0),e.found.length?(B(),V(`section`,n2,[U(`h2`,r2,O(N(X)(`How people find you`)),1),U(`ul`,i2,[(B(!0),V(R,null,L(e.found,t=>(B(),V(`li`,{key:t.name,class:`p-4`},[U(`div`,a2,[U(`span`,o2,O(t.name),1),U(`span`,s2,O(N(X)(`:count times`,{count:t.visits})),1)]),U(`div`,{class:`mt-2 h-1.5 rounded-full bg-brand`,style:ve({width:a(t.visits,e.found.map(e=>e.visits))}),"aria-hidden":`true`},null,4)]))),128))])])):K(``,!0),e.requests&&e.requests.subjects.length?(B(),V(`section`,c2,[U(`h2`,l2,O(N(X)(`What the requests were about`)),1),U(`ul`,u2,[(B(!0),V(R,null,L(e.requests.subjects,e=>(B(),V(`li`,{key:e.name,class:`flex items-baseline justify-between gap-3 p-4`},[U(`span`,d2,O(e.name),1),U(`span`,f2,O(e.count),1)]))),128))])])):K(``,!0),e.articles.length?(B(),V(`section`,p2,[U(`h2`,m2,O(N(X)(`Most read articles`)),1),U(`ul`,h2,[(B(!0),V(R,null,L(e.articles,e=>(B(),V(`li`,{key:e.title,class:`flex items-baseline justify-between gap-3 p-4`},[U(`span`,g2,O(e.title),1),U(`span`,_2,O(N(X)(`:count times`,{count:e.views})),1)]))),128))])])):K(``,!0),U(`p`,v2,[e.requests&&e.requests.kept_away?(B(),V(R,{key:0},[G(O(N(X)(`:count messages of spam or advertising were kept away from you.`,{count:e.requests.kept_away})),1)],64)):K(``,!0),G(` `+O(N(X)(`Visitors are counted without cookies. Search robots, and you yourself when you are logged in, are not counted.`)),1)])],64))}}),b2={class:`mb-6 flex items-center justify-between gap-3`},x2={class:`font-display text-2xl font-bold`},S2={key:0,class:`m-card p-5 text-sm text-muted`},C2={key:1,class:`m-card overflow-x-auto`},w2={class:`w-full text-left text-sm`},T2={class:`border-b border-line text-xs uppercase tracking-wide text-muted`},E2={key:0,class:`px-4 py-3`},D2={class:`divide-y divide-line`},O2={key:0,class:`flex justify-end gap-2 px-4 py-2`},k2=[`onClick`],A2={key:2,class:`mt-4 flex gap-2`},j2=I({__name:`RecordsIndex`,props:{resource:{},rows:{},current_page:{},last_page:{}},setup(e){let t=e,n=`${J.base}/records/${t.resource.key}`,r=e=>{let n=t.resource.fields.find(t=>t.key===e);return n?r0(n.label,n.simple_label):e};function i(e,n){let r=e.values[n],i=t.resource.fields.find(e=>e.key===n);return i?.type===`toggle`?r?`✓`:``:i?.type===`select`?i.options[r]??r:String(r??``)}async function a(e){window.confirm(X(`Are you sure?`))&&(await Y.delete(`${n}/${e.id}`),await l4())}return(t,o)=>(B(),V(R,null,[U(`div`,b2,[U(`h1`,x2,O(N(X)(N(r0)(e.resource.label,e.resource.simple_label))),1),e.resource.can_manage?(B(),H(Z,{key:0,href:n+`/create`,class:`m-btn m-btn-primary`},{default:P(()=>[G(O(N(X)(`Add`)),1)]),_:1},8,[`href`])):K(``,!0)]),e.rows.length?(B(),V(`div`,C2,[U(`table`,w2,[U(`thead`,T2,[U(`tr`,null,[(B(!0),V(R,null,L(e.resource.columns,e=>(B(),V(`th`,{key:e,class:`px-4 py-3 font-semibold`},O(N(X)(r(e))),1))),128)),e.resource.can_manage?(B(),V(`th`,E2)):K(``,!0)])]),U(`tbody`,D2,[(B(!0),V(R,null,L(e.rows,t=>(B(),V(`tr`,{key:t.id},[(B(!0),V(R,null,L(e.resource.columns,e=>(B(),V(`td`,{key:e,class:`max-w-xs truncate px-4 py-3`},O(i(t,e)),1))),128)),e.resource.can_manage?(B(),V(`td`,O2,[W(Z,{href:`${n}/${t.id}/edit`,class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Edit`)),1)]),_:1},8,[`href`]),U(`button`,{type:`button`,class:`m-btn m-btn-danger`,onClick:e=>a(t)},O(N(X)(`Delete`)),9,k2)])):K(``,!0)]))),128))])])])):(B(),V(`p`,S2,O(N(X)(`Nothing here yet.`)),1)),e.last_page>1?(B(),V(`nav`,A2,[e.current_page>1?(B(),H(Z,{key:0,href:`${n}?page=${e.current_page-1}`,class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Previous`)),1)]),_:1},8,[`href`])):K(``,!0),e.current_page[G(O(N(X)(`Next`)),1)]),_:1},8,[`href`])):K(``,!0)])):K(``,!0)],64))}}),M2={class:`mb-6 flex items-center justify-between gap-3`},N2={class:`font-display text-2xl font-bold`},P2={for:`title`,class:`m-label`},F2={key:0,class:`m-error`},I2={for:`meta`,class:`m-label`},L2={key:0,class:`m-error`},R2={for:`body`,class:`m-label`},z2={key:0,class:`m-error`},B2={class:`flex items-center gap-2 text-sm`},V2={class:`flex gap-3`},H2=[`disabled`],U2=I({__name:`PageForm`,props:{page:{}},setup(e){let t=e.page,n=Yu({title:t.title,meta_description:t.meta_description??``,...t.defined?{content:{...t.content}}:{body:t.body??``,is_published:t.is_published??!1}});async function r(){await n.send(`put`,`${J.base}/pages/${t.slug}`)&&$(X(`Saved.`))}async function i(){window.confirm(X(`Are you sure?`))&&(await Y.delete(`${J.base}/pages/${t.slug}`),c4(`${J.base}/pages`))}return(e,a)=>(B(),V(R,null,[U(`div`,M2,[U(`h1`,N2,O(N(r0)(N(t).title,N(t).simple_title)),1),W(Z,{href:N(J).base+`/pages`,class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Back`)),1)]),_:1},8,[`href`])]),U(`form`,{class:`m-card max-w-3xl space-y-5 p-5`,onSubmit:Du(r,[`prevent`])},[U(`div`,null,[U(`label`,P2,O(N(X)(`Title`)),1),F(U(`input`,{id:`title`,"onUpdate:modelValue":a[0]||=e=>N(n).values.title=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[q,N(n).values.title]]),N(n).errors.title?(B(),V(`p`,F2,O(N(n).errors.title),1)):K(``,!0)]),U(`div`,null,[U(`label`,I2,O(N(X)(`Description for search engines`)),1),F(U(`input`,{id:`meta`,"onUpdate:modelValue":a[1]||=e=>N(n).values.meta_description=e,maxlength:`255`,class:`m-input`},null,512),[[q,N(n).values.meta_description]]),N(n).errors.meta_description?(B(),V(`p`,L2,O(N(n).errors.meta_description),1)):K(``,!0)]),N(t).defined?(B(),H(n0,{key:0,fields:N(t).fields,values:N(n).values.content,errors:N(n).errors,prefix:`content.`},null,8,[`fields`,`values`,`errors`])):(B(),V(R,{key:1},[U(`div`,null,[U(`label`,R2,O(N(X)(`Text (Markdown)`)),1),W(uf,{id:`body`,modelValue:N(n).values.body,"onUpdate:modelValue":a[2]||=e=>N(n).values.body=e},null,8,[`modelValue`]),N(n).errors.body?(B(),V(`p`,z2,O(N(n).errors.body),1)):K(``,!0)]),U(`label`,B2,[F(U(`input`,{"onUpdate:modelValue":a[3]||=e=>N(n).values.is_published=e,type:`checkbox`},null,512),[[pu,N(n).values.is_published]]),G(` `+O(N(X)(`Publish`)),1)])],64)),U(`div`,V2,[U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(n).busy},O(N(n).busy?N(X)(`Saving…`):N(X)(`Save`)),9,H2),N(t).defined?K(``,!0):(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-danger`,onClick:i},O(N(X)(`Delete`)),1))])],32),N(t).id&&N(J).permissions.includes(`revisions.view`)?(B(),H(Ef,{key:0,type:`pages`,id:N(t).id},null,8,[`id`])):K(``,!0)],64))}}),W2={class:`font-display mb-6 text-2xl font-bold`},G2={class:`m-card divide-y divide-line`},K2={class:`min-w-0`},q2={class:`truncate font-semibold`},J2={class:`truncate text-xs text-muted`},Y2={class:`flex items-center gap-2`},X2={key:0,class:`m-badge`},Z2={key:0,class:`p-4 text-sm text-muted`},Q2={for:`new-title`,class:`m-label`},$2={key:0,class:`m-error`},e4={for:`new-slug`,class:`m-label`},t4={key:0,class:`m-error`},n4=[`disabled`],r4=[{pattern:/^\/?$/,component:_d,data:!0},{pattern:/^\/login$/,component:zd,guest:!0},{pattern:/^\/profile$/,component:rm,data:!0},{pattern:/^\/posts$/,component:Sp,data:!0},{pattern:/^\/posts\/create$/,component:lp,data:!0},{pattern:/^\/posts\/\d+\/edit$/,component:lp,data:!0},{pattern:/^\/media$/,component:eg,data:!0,source:`/media/items`},{pattern:/^\/audit$/,component:t_,data:!0},{pattern:/^\/settings$/,component:T_,data:!0},{pattern:/^\/leads$/,component:yv,data:!0},{pattern:/^\/updates$/,component:Ov,data:!0},{pattern:/^\/sharing$/,component:Gv,data:!0},{pattern:/^\/costs$/,component:Sy,data:!0},{pattern:/^\/numbers$/,component:y2,data:!0},{pattern:/^\/statistics$/,component:_1,data:!0},{pattern:/^\/accounts$/,component:Bm,data:!0},{pattern:/^\/groups$/,component:lh,data:!0},{pattern:/^\/labels$/,component:Ch,data:!0},{pattern:/^\/pages$/,component:I({__name:`PagesIndex`,props:{pages:{}},setup(e){let t=Yu({slug:``,title:``});async function n(){await t.send(`post`,`${J.base}/pages`)&&c4(`${J.base}/pages/${t.values.slug}`)}return(r,i)=>(B(),V(R,null,[U(`h1`,W2,O(N(X)(`Pages`)),1),U(`ul`,G2,[(B(!0),V(R,null,L(e.pages,e=>(B(),V(`li`,{key:e.slug,class:`flex items-center justify-between gap-3 p-4`},[U(`div`,K2,[U(`p`,q2,O(N(r0)(e.title,e.simple_title)),1),U(`p`,J2,`/`+O(e.slug),1)]),U(`div`,Y2,[e.defined?K(``,!0):(B(),V(`span`,X2,O(e.is_published?N(X)(`Published`):N(X)(`Draft`)),1)),W(Z,{href:`${N(J).base}/pages/${e.slug}`,class:`m-btn m-btn-secondary`},{default:P(()=>[G(O(N(X)(`Edit`)),1)]),_:1},8,[`href`])])]))),128)),e.pages.length?K(``,!0):(B(),V(`li`,Z2,O(N(X)(`Nothing here yet.`)),1))]),U(`form`,{class:`m-card mt-6 grid max-w-3xl gap-4 p-5 sm:grid-cols-[1fr_1fr_auto] sm:items-end`,onSubmit:Du(n,[`prevent`])},[U(`div`,null,[U(`label`,Q2,O(N(X)(`Title`)),1),F(U(`input`,{id:`new-title`,"onUpdate:modelValue":i[0]||=e=>N(t).values.title=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[q,N(t).values.title]]),N(t).errors.title?(B(),V(`p`,$2,O(N(t).errors.title),1)):K(``,!0)]),U(`div`,null,[U(`label`,e4,O(N(X)(`Address (slug)`)),1),F(U(`input`,{id:`new-slug`,"onUpdate:modelValue":i[1]||=e=>N(t).values.slug=e,required:``,maxlength:`120`,class:`m-input`},null,512),[[q,N(t).values.slug]]),N(t).errors.slug?(B(),V(`p`,t4,O(N(t).errors.slug),1)):K(``,!0)]),U(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:N(t).busy},O(N(X)(`New page`)),9,n4)],32)],64))}}),data:!0},{pattern:/^\/pages\/[a-z0-9]+(?:-[a-z0-9]+)*$/,component:U2,data:!0},{pattern:/^\/records\/[a-z][a-z0-9_]*$/,component:j2,data:!0},{pattern:/^\/records\/[a-z][a-z0-9_]*\/(create|\d+\/edit)$/,component:s0,data:!0},{pattern:/^\/reviews$/,component:E1,data:!0}];function i4(e,t,n={}){r4.unshift({pattern:new RegExp(e),component:t,data:n.data,source:n.source})}var Q=an({path:``,component:null,props:{},loading:!0,forbidden:!1,tour:J.tutorial,toast:null}),a4;function $(e,t=!1){Q.toast={text:e,error:t},window.clearTimeout(a4),a4=window.setTimeout(()=>Q.toast=null,4e3)}function o4(e){return e.split(`?`)[0].slice(J.base.length)||`/`}async function s4(e){let t=r4.find(t=>t.pattern.test(o4(e)));if(!J.user&&!t?.guest)window.location.assign(J.base+`/login`);else{if(J.user&&t?.guest)return c4(J.base,!0);Q.loading=!0,Q.forbidden=!1,Q.path=e,Q.component=t?.component??bd,Q.props={};try{Q.props=t?.data?await Y.get(t.source?J.base+t.source:e):{}}catch(e){e instanceof Gu&&e.status===401?window.location.assign(J.base+`/login`):e instanceof Gu&&e.status===403?Q.forbidden=!0:$(X(`Something went wrong. Try again.`),!0)}finally{Q.loading=!1}}}function c4(e,t=!1){return window.history[t?`replaceState`:`pushState`]({},``,e),window.scrollTo(0,0),s4(e)}function l4(){return s4(Q.path)}function u4(){window.addEventListener(`popstate`,()=>s4(window.location.pathname+window.location.search));let e=window.location.pathname.replace(/\/+$/,``);J.user&&J.start&&e===J.base&&!window.sessionStorage.getItem(`manager-start`)?(window.sessionStorage.setItem(`manager-start`,`1`),c4(J.start,!0)):s4(window.location.pathname+window.location.search)}var d4=[`aria-label`],f4={key:0,class:`absolute inset-0 bg-black/60`},p4=[`aria-label`],m4={class:`flex items-start gap-3`},h4={class:`m-bob m-glow -ml-1 shrink-0 rounded-full`},g4={class:`min-w-0 pr-6`,"aria-live":`polite`},_4={class:`font-display text-lg font-bold leading-snug`},v4={class:`mt-1.5 text-sm leading-relaxed text-muted`},y4={class:`mt-4 flex items-center justify-between gap-2`},b4={class:`flex gap-1`,"aria-hidden":`true`},x4={class:`text-xs text-muted`},S4={class:`mt-4 flex flex-wrap items-center gap-2`},C4=I({__name:`Tutorial`,setup(e){let t=(J.user?.name??``).split(` `)[0],n=e=>J.navigation.some(t=>t.href.endsWith(e)),r=()=>window.matchMedia(`(min-width: 768px)`).matches;function i(e){if(!(e instanceof HTMLElement))return null;let t=e.getBoundingClientRect();return t.width>0&&t.height>0&&t.left>=0&&t.right<=window.innerWidth&&t.top>=0&&t.bottom<=window.innerHeight?e:null}let a=e=>()=>i(document.querySelector(`nav[aria-label="Manager"] a[href$="${e}"]`));function o(){let e=[{id:`welcome`,image:`welcome`,title:X(`Hi :name! Welcome!`,{name:t}),text:X(`I will show you around in a few small steps. Looking around cannot break anything, and you can stop whenever you like: press the cross.`)},{id:`menu`,image:`point`,title:X(`This is the menu`),text:X(`Everything you can do lives here. Press a name and you are there.`),target:()=>i(r()?document.querySelector(`nav[aria-label="Manager"]`):document.querySelector(`header button`))},{id:`start`,image:`calm`,title:X(`Your start page`),text:X(`Lost? Press Dashboard, at the top of the menu, and you are back here. Nice and calm.`),target:a(`/manager`)}];n(`/posts`)&&e.push({id:`posts`,image:`write`,title:X(`Write news`),text:X(`Here you write articles and news for your website. Keep it as a draft until you are happy, then put it online.`),target:a(`/posts`)}),n(`/media`)&&e.push({id:`media`,image:`photos`,title:X(`Your photos`),text:X(`All photos and files live here. Upload them once and use them in posts and pages.`),target:a(`/media`)}),n(`/pages`)&&e.push({id:`pages`,image:`pages`,title:X(`Your pages`),text:X(`Change the texts and photos of the pages of your website here.`),target:a(`/pages`)});for(let[t,n]of(J.tutorial_steps??[]).entries())e.push({id:`module-`+t,image:n.image??`point`,title:X(n.title),text:X(n.text),target:n.href?a(n.href):void 0});return J.permissions.includes(`revisions.view`)&&(n(`/posts`)||n(`/pages`))&&e.push({id:`undo`,image:`undo`,title:X(`Changed your mind?`),text:X(`Every time you save a post or a page I keep the old version. You can always put an earlier one back.`)}),e.push({id:`oops`,image:`oops`,title:X(`Something went wrong?`),text:X(`A message tells you what. Read it, fix it and try again. Nothing is deleted without asking you first.`)}),e.push({id:`profile`,image:`profile`,title:X(`Your own corner`),text:X(`Here you choose your language and your colours, and change your password.`),target:()=>i(document.querySelector(`a[href="${J.base}/profile"]`))}),e.push({id:`party`,image:`party`,title:X(`That is it!`),text:X(`Want to see this again? Press Show the tour in the menu. Have fun!`)}),e}let s=o(),c=M(0),l=pc(()=>s[c.value]),u=pc(()=>c.value===s.length-1),d=M(null),f=M(null),p=M(null),m=M(null),h=M(!1);async function g(){await ar();let e=l.value.target?.()??null;if(!e){p.value=null,m.value=null,h.value=!1,f.value?.focus();return}let t=e.getBoundingClientRect(),n=d.value?.offsetHeight??320,i=d.value?.offsetWidth??380;if(p.value={top:t.top-6,left:t.left-6,width:t.width+12,height:t.height+12},!r()){m.value=null,h.value=!1,f.value?.focus();return}let a=t.right+28;m.value={left:a+ivoid 0)}function v(e){let t=c.value+e;if(t>=s.length)return _(!0);c.value=Math.max(0,t),g()}function y(e){e.key===`Escape`?_(!1):e.key===`ArrowRight`?v(1):e.key===`ArrowLeft`&&c.value>0&&v(-1)}return aa(()=>{window.addEventListener(`keydown`,y),window.addEventListener(`resize`,g),g()}),ca(()=>{window.removeEventListener(`keydown`,y),window.removeEventListener(`resize`,g)}),(e,t)=>(B(),V(`div`,{class:`fixed inset-0 z-50`,role:`dialog`,"aria-modal":`true`,"aria-label":N(X)(`Tour`)},[p.value?(B(),V(`div`,{key:1,class:`m-spot pointer-events-none absolute rounded-xl`,style:ve({top:p.value.top+`px`,left:p.value.left+`px`,width:p.value.width+`px`,height:p.value.height+`px`})},null,4)):(B(),V(`div`,f4)),U(`div`,{ref_key:`card`,ref:d,class:D([`m-card absolute w-[min(24rem,calc(100vw-2rem))] p-5 shadow-2xl`,m.value?``:`bottom-4 left-1/2 -translate-x-1/2 md:bottom-auto md:top-1/2 md:-translate-y-1/2`]),style:ve(m.value?{top:m.value.top+`px`,left:m.value.left+`px`}:void 0)},[U(`button`,{type:`button`,class:`absolute right-3 top-3 rounded-lg p-1.5 text-muted hover:bg-text/10 hover:text-text`,"aria-label":N(X)(`Stop the tour`),onClick:t[0]||=e=>_(!1)},[...t[4]||=[U(`svg`,{class:`h-5 w-5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`,"stroke-linecap":`round`,"aria-hidden":`true`},[U(`path`,{d:`M6 6l12 12M18 6L6 18`})],-1)]],8,p4),U(`div`,m4,[U(`div`,h4,[(B(),H(wp,{key:l.value.image,name:l.value.image,flip:h.value,size:128},null,8,[`name`,`flip`]))]),U(`div`,g4,[U(`h2`,_4,O(l.value.title),1),U(`p`,v4,O(l.value.text),1)])]),U(`div`,y4,[U(`span`,b4,[(B(!0),V(R,null,L(N(s),(e,t)=>(B(),V(`span`,{key:t,class:D([`h-1.5 w-1.5 rounded-full`,t===c.value?`bg-brand`:`bg-line`])},null,2))),128))]),U(`span`,x4,O(c.value+1)+` / `+O(N(s).length),1)]),U(`div`,S4,[U(`button`,{type:`button`,class:`text-sm text-muted underline hover:text-text`,onClick:t[1]||=e=>_(!1)},O(N(X)(`Stop the tour`)),1),t[5]||=U(`span`,{class:`flex-1`},null,-1),c.value>0?(B(),V(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t[2]||=e=>v(-1)},O(N(X)(`Back`)),1)):K(``,!0),U(`button`,{ref_key:`next`,ref:f,type:`button`,class:`m-btn m-btn-primary`,onClick:t[3]||=e=>v(1)},O(u.value?N(X)(`Done`):N(X)(`Next`)),513)])],6)],8,d4))}}),w4={class:`min-h-screen`},T4={class:`fixed inset-x-0 top-0 z-40 flex h-14 items-center justify-between border-b border-line bg-panel px-4 md:hidden`},E4={class:`font-display font-bold`},D4=[`aria-expanded`],O4={class:`hidden h-16 items-center gap-2 px-5 md:flex`},k4=[`src`],A4={class:`font-display text-lg font-bold`},j4={class:`flex-1 space-y-0.5 overflow-y-auto px-3 py-3`,"aria-label":`Manager`},M4={key:0,class:`my-3 border-line`},N4={key:1,class:`px-3 pb-1 pt-4 text-xs font-semibold uppercase tracking-wide text-muted`},P4=[`href`],F4={class:`border-t border-line p-4`},I4={class:`truncate text-sm font-semibold group-hover:text-brand`},L4={class:`truncate text-xs text-muted`},R4={key:0,class:`truncate text-xs text-muted`},z4={class:`px-4 pb-16 pt-20 md:ml-60 md:px-8 md:pt-8`},B4={class:`mx-auto max-w-5xl`},V4=I({__name:`Layout`,setup(e){let t=M(!1),n=pc(()=>{let e=[];for(let t of[{label:`Dashboard`,href:J.base,icon:`home`},...J.navigation]){let n=t.section??``,r=e[e.length-1];r&&r.title===n?r.items.push(t):e.push({title:n,items:[t]})}return e}),r=M(J.view);async function i(){await Y.put(J.base+`/profile/view`,{view:r.value===`simple`?`full`:`simple`}),window.location.assign(J.base)}function a(e){let t=Q.path.split(`?`)[0];return e===J.base?t===e:t===e||t.startsWith(e+`/`)}async function o(){let{redirect:e}=await Y.post(J.base+`/logout`);window.location.assign(e)}return Pr(()=>Q.path,()=>t.value=!1),(e,s)=>(B(),V(`div`,w4,[U(`header`,T4,[U(`span`,E4,O(N(J).name),1),U(`button`,{type:`button`,class:`m-btn m-btn-secondary`,"aria-expanded":t.value,onClick:s[0]||=e=>t.value=!t.value},O(N(X)(`Menu`)),9,D4)]),U(`aside`,{class:D([`fixed inset-y-0 left-0 z-30 flex w-60 flex-col border-r border-line bg-panel pt-14 transition-transform md:translate-x-0 md:pt-0`,t.value?`translate-x-0`:`-translate-x-full`])},[U(`div`,O4,[N(J).logo?(B(),V(`img`,{key:0,src:N(J).logo,alt:``,class:`h-7 w-auto`},null,8,k4)):K(``,!0),U(`span`,A4,O(N(J).name),1)]),U(`nav`,j4,[(B(!0),V(R,null,L(n.value,(e,t)=>(B(),V(R,{key:e.title+t},[!e.title&&t>0?(B(),V(`hr`,M4)):K(``,!0),e.title?(B(),V(`p`,N4,O(N(X)(e.title)),1)):K(``,!0),(B(!0),V(R,null,L(e.items,e=>(B(),V(R,{key:e.href},[e.new_tab?(B(),V(`a`,{key:0,href:e.href,target:`_blank`,rel:`noopener`,class:`flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-muted transition hover:bg-text/5 hover:text-text`},[W(ed,{name:e.icon},null,8,[`name`]),G(O(N(X)(e.label)),1)],8,P4)):(B(),H(Z,{key:1,href:e.href,class:D([`flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition`,a(e.href)?`bg-brand/15 text-text`:`text-muted hover:bg-text/5 hover:text-text`]),"aria-current":a(e.href)?`page`:void 0},{default:P(()=>[W(ed,{name:e.icon},null,8,[`name`]),G(O(N(X)(e.label)),1)]),_:2},1032,[`href`,`class`,`aria-current`]))],64))),128))],64))),128))]),U(`div`,F4,[W(Z,{href:N(J).base+`/profile`,class:`group block`},{default:P(()=>[U(`p`,I4,O(N(J).user?.name),1),U(`p`,L4,O(N(J).user?.email),1),N(J).user?.group?(B(),V(`p`,R4,O(N(J).user.group),1)):K(``,!0)]),_:1},8,[`href`]),N(J).tutorial_state?(B(),V(`button`,{key:0,type:`button`,class:`mt-2 block text-xs text-muted underline hover:text-text`,onClick:s[1]||=e=>N(Q).tour=!0},O(N(X)(`Show the tour`)),1)):K(``,!0),N(J).can_switch?(B(),V(`button`,{key:1,type:`button`,class:`m-btn m-btn-secondary mt-3 w-full justify-center`,onClick:i},O(r.value===`simple`?N(X)(`Show everything`):N(X)(`Simple view`)),1)):K(``,!0),U(`button`,{type:`button`,class:`m-btn m-btn-secondary mt-3 w-full justify-center`,onClick:o},O(N(X)(`Log out`)),1)])],2),t.value?(B(),V(`div`,{key:0,class:`fixed inset-0 z-20 bg-black/60 md:hidden`,onClick:s[2]||=e=>t.value=!1})):K(``,!0),N(Q).tour?(B(),H(C4,{key:1})):K(``,!0),U(`main`,z4,[U(`div`,B4,[Ca(e.$slots,`default`)])])]))}}),H4={key:0,class:`m-card p-5 text-sm`},U4={key:1,class:`text-sm text-muted`},W4=I({__name:`App`,setup(e){return(e,t)=>(B(),V(R,null,[N(Q).component&&!N(J).user?(B(),H(va(N(Q).component),{key:0})):N(Q).component?(B(),H(V4,{key:1},{default:P(()=>[N(Q).forbidden?(B(),V(`p`,H4,O(N(X)(`You may not open this page.`)),1)):N(Q).loading?(B(),V(`p`,U4,O(N(X)(`Loading…`)),1)):(B(),H(va(N(Q).component),Ce(zs({key:2},N(Q).props)),null,16))]),_:1})):K(``,!0),N(Q).toast?(B(),V(`div`,{key:2,role:`status`,class:D([`fixed bottom-5 right-5 z-50 rounded-lg border border-l-4 border-line bg-panel px-4 py-3 text-sm font-medium text-text shadow-xl`,N(Q).toast.error?`border-l-red-500`:`border-l-emerald-500`])},O(N(Q).toast.text),3)):K(``,!0)],64))}});Qu(J.locale),J.view===`simple`&&document.documentElement.classList.add(`is-simple`),window.IriksManager={Vue:Uu,boot:J,api:Y,t:X,flash:$,navigate:c4,register:i4,components:{Link:Z,FormFields:n0,Icon:ed,MediaPicker:Yd}};async function G4(){for(let e of J.extensions??[])try{await import(e)}catch(t){console.error(`Manager extension ${e} did not load`,t)}Lu(W4).mount(`#manager`),u4()}G4(); \ No newline at end of file diff --git a/resources/dist/vue.js b/resources/dist/vue.js new file mode 100644 index 0000000..826b71d --- /dev/null +++ b/resources/dist/vue.js @@ -0,0 +1,174 @@ +const Vue = window.IriksManager.Vue; +export const BaseTransition = Vue.BaseTransition; +export const BaseTransitionPropsValidators = Vue.BaseTransitionPropsValidators; +export const Comment = Vue.Comment; +export const DeprecationTypes = Vue.DeprecationTypes; +export const EffectScope = Vue.EffectScope; +export const ErrorCodes = Vue.ErrorCodes; +export const ErrorTypeStrings = Vue.ErrorTypeStrings; +export const Fragment = Vue.Fragment; +export const KeepAlive = Vue.KeepAlive; +export const ReactiveEffect = Vue.ReactiveEffect; +export const Static = Vue.Static; +export const Suspense = Vue.Suspense; +export const Teleport = Vue.Teleport; +export const Text = Vue.Text; +export const TrackOpTypes = Vue.TrackOpTypes; +export const Transition = Vue.Transition; +export const TransitionGroup = Vue.TransitionGroup; +export const TriggerOpTypes = Vue.TriggerOpTypes; +export const VueElement = Vue.VueElement; +export const __esModule = Vue.__esModule; +export const assertNumber = Vue.assertNumber; +export const callWithAsyncErrorHandling = Vue.callWithAsyncErrorHandling; +export const callWithErrorHandling = Vue.callWithErrorHandling; +export const camelize = Vue.camelize; +export const capitalize = Vue.capitalize; +export const cloneVNode = Vue.cloneVNode; +export const compatUtils = Vue.compatUtils; +export const compile = Vue.compile; +export const computed = Vue.computed; +export const createApp = Vue.createApp; +export const createBlock = Vue.createBlock; +export const createCommentVNode = Vue.createCommentVNode; +export const createElementBlock = Vue.createElementBlock; +export const createElementVNode = Vue.createElementVNode; +export const createHydrationRenderer = Vue.createHydrationRenderer; +export const createPropsRestProxy = Vue.createPropsRestProxy; +export const createRenderer = Vue.createRenderer; +export const createSSRApp = Vue.createSSRApp; +export const createSlots = Vue.createSlots; +export const createStaticVNode = Vue.createStaticVNode; +export const createTextVNode = Vue.createTextVNode; +export const createVNode = Vue.createVNode; +export const customRef = Vue.customRef; +export const defineAsyncComponent = Vue.defineAsyncComponent; +export const defineComponent = Vue.defineComponent; +export const defineCustomElement = Vue.defineCustomElement; +export const defineEmits = Vue.defineEmits; +export const defineExpose = Vue.defineExpose; +export const defineModel = Vue.defineModel; +export const defineOptions = Vue.defineOptions; +export const defineProps = Vue.defineProps; +export const defineSSRCustomElement = Vue.defineSSRCustomElement; +export const defineSlots = Vue.defineSlots; +export const devtools = Vue.devtools; +export const effect = Vue.effect; +export const effectScope = Vue.effectScope; +export const getCurrentInstance = Vue.getCurrentInstance; +export const getCurrentScope = Vue.getCurrentScope; +export const getCurrentWatcher = Vue.getCurrentWatcher; +export const getTransitionRawChildren = Vue.getTransitionRawChildren; +export const guardReactiveProps = Vue.guardReactiveProps; +export const h = Vue.h; +export const handleError = Vue.handleError; +export const hasInjectionContext = Vue.hasInjectionContext; +export const hydrate = Vue.hydrate; +export const hydrateOnIdle = Vue.hydrateOnIdle; +export const hydrateOnInteraction = Vue.hydrateOnInteraction; +export const hydrateOnMediaQuery = Vue.hydrateOnMediaQuery; +export const hydrateOnVisible = Vue.hydrateOnVisible; +export const initCustomFormatter = Vue.initCustomFormatter; +export const initDirectivesForSSR = Vue.initDirectivesForSSR; +export const inject = Vue.inject; +export const isMemoSame = Vue.isMemoSame; +export const isProxy = Vue.isProxy; +export const isReactive = Vue.isReactive; +export const isReadonly = Vue.isReadonly; +export const isRef = Vue.isRef; +export const isRuntimeOnly = Vue.isRuntimeOnly; +export const isShallow = Vue.isShallow; +export const isVNode = Vue.isVNode; +export const markRaw = Vue.markRaw; +export const mergeDefaults = Vue.mergeDefaults; +export const mergeModels = Vue.mergeModels; +export const mergeProps = Vue.mergeProps; +export const nextTick = Vue.nextTick; +export const nodeOps = Vue.nodeOps; +export const normalizeClass = Vue.normalizeClass; +export const normalizeProps = Vue.normalizeProps; +export const normalizeStyle = Vue.normalizeStyle; +export const onActivated = Vue.onActivated; +export const onBeforeMount = Vue.onBeforeMount; +export const onBeforeUnmount = Vue.onBeforeUnmount; +export const onBeforeUpdate = Vue.onBeforeUpdate; +export const onDeactivated = Vue.onDeactivated; +export const onErrorCaptured = Vue.onErrorCaptured; +export const onMounted = Vue.onMounted; +export const onRenderTracked = Vue.onRenderTracked; +export const onRenderTriggered = Vue.onRenderTriggered; +export const onScopeDispose = Vue.onScopeDispose; +export const onServerPrefetch = Vue.onServerPrefetch; +export const onUnmounted = Vue.onUnmounted; +export const onUpdated = Vue.onUpdated; +export const onWatcherCleanup = Vue.onWatcherCleanup; +export const openBlock = Vue.openBlock; +export const patchProp = Vue.patchProp; +export const popScopeId = Vue.popScopeId; +export const provide = Vue.provide; +export const proxyRefs = Vue.proxyRefs; +export const pushScopeId = Vue.pushScopeId; +export const queuePostFlushCb = Vue.queuePostFlushCb; +export const reactive = Vue.reactive; +export const readonly = Vue.readonly; +export const ref = Vue.ref; +export const registerRuntimeCompiler = Vue.registerRuntimeCompiler; +export const render = Vue.render; +export const renderList = Vue.renderList; +export const renderSlot = Vue.renderSlot; +export const resolveComponent = Vue.resolveComponent; +export const resolveDirective = Vue.resolveDirective; +export const resolveDynamicComponent = Vue.resolveDynamicComponent; +export const resolveFilter = Vue.resolveFilter; +export const resolveTransitionHooks = Vue.resolveTransitionHooks; +export const setBlockTracking = Vue.setBlockTracking; +export const setDevtoolsHook = Vue.setDevtoolsHook; +export const setTransitionHooks = Vue.setTransitionHooks; +export const shallowReactive = Vue.shallowReactive; +export const shallowReadonly = Vue.shallowReadonly; +export const shallowRef = Vue.shallowRef; +export const ssrContextKey = Vue.ssrContextKey; +export const ssrUtils = Vue.ssrUtils; +export const stop = Vue.stop; +export const toDisplayString = Vue.toDisplayString; +export const toHandlerKey = Vue.toHandlerKey; +export const toHandlers = Vue.toHandlers; +export const toRaw = Vue.toRaw; +export const toRef = Vue.toRef; +export const toRefs = Vue.toRefs; +export const toValue = Vue.toValue; +export const transformVNodeArgs = Vue.transformVNodeArgs; +export const triggerRef = Vue.triggerRef; +export const unref = Vue.unref; +export const useAttrs = Vue.useAttrs; +export const useCssModule = Vue.useCssModule; +export const useCssVars = Vue.useCssVars; +export const useHost = Vue.useHost; +export const useId = Vue.useId; +export const useModel = Vue.useModel; +export const useSSRContext = Vue.useSSRContext; +export const useShadowRoot = Vue.useShadowRoot; +export const useSlots = Vue.useSlots; +export const useTemplateRef = Vue.useTemplateRef; +export const useTransitionState = Vue.useTransitionState; +export const vModelCheckbox = Vue.vModelCheckbox; +export const vModelDynamic = Vue.vModelDynamic; +export const vModelRadio = Vue.vModelRadio; +export const vModelSelect = Vue.vModelSelect; +export const vModelText = Vue.vModelText; +export const vShow = Vue.vShow; +export const version = Vue.version; +export const warn = Vue.warn; +export const watch = Vue.watch; +export const watchEffect = Vue.watchEffect; +export const watchPostEffect = Vue.watchPostEffect; +export const watchSyncEffect = Vue.watchSyncEffect; +export const withAsyncContext = Vue.withAsyncContext; +export const withCtx = Vue.withCtx; +export const withDefaults = Vue.withDefaults; +export const withDirectives = Vue.withDirectives; +export const withKeys = Vue.withKeys; +export const withMemo = Vue.withMemo; +export const withModifiers = Vue.withModifiers; +export const withScopeId = Vue.withScopeId; +export default Vue; diff --git a/resources/js/pulse.js b/resources/js/pulse.js new file mode 100644 index 0000000..fcff87d --- /dev/null +++ b/resources/js/pulse.js @@ -0,0 +1,105 @@ +/* + * Reports a page view of the public site to the statistics of the manager, and how long the page was in view. + * No cookies, no storage, nothing about the visitor: the server decides what it keeps (see the README). A browser that + * asks not to be followed (Do Not Track, Global Privacy Control) is not counted, here and on the server. + * + * + * + * `data-spa` on the script tag: also report the pages a client-side router moves to (history.pushState). + */ +(function () { + 'use strict'; + + var script = document.currentScript; + var base = script && script.src ? script.src.replace(/\/pulse\.js(\?.*)?$/, '') : '/pulse'; + + if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl === true) { + return; + } + + var token = null; + var visible = 0; + var shownAt = document.visibilityState === 'visible' ? Date.now() : null; + var sent = false; + + function params() { + return new URLSearchParams(location.search); + } + + function other(referrer) { + try { + return new URL(referrer).host !== location.host ? referrer : ''; + } catch (e) { + return ''; + } + } + + function report(path, referrer) { + var query = params(); + + fetch(base + '/view', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + credentials: 'omit', + keepalive: true, + body: JSON.stringify({ + path: path, + referrer: referrer, + via: query.get('via') || query.get('utm_source') || '', + campaign: query.get('utm_campaign') || '', + }), + }) + .then(function (response) { return response.ok ? response.json() : null; }) + .then(function (data) { token = data && data.token ? data.token : null; }) + .catch(function () {}); + } + + function leave() { + if (shownAt !== null) { + visible += Date.now() - shownAt; + shownAt = null; + } + + if (token && !sent && visible > 0) { + sent = true; + var body = JSON.stringify({ token: token, seconds: Math.min(Math.round(visible / 1000), 7200) }); + + if (!(navigator.sendBeacon && navigator.sendBeacon(base + '/leave', new Blob([body], { type: 'application/json' })))) { + fetch(base + '/leave', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: body, keepalive: true, credentials: 'omit' }).catch(function () {}); + } + } + } + + function resume() { + shownAt = shownAt === null && document.visibilityState === 'visible' ? Date.now() : shownAt; + sent = false; + } + + document.addEventListener('visibilitychange', function () { + document.visibilityState === 'hidden' ? leave() : resume(); + }); + window.addEventListener('pagehide', leave); + + report(location.pathname, other(document.referrer)); + + if (script && script.hasAttribute('data-spa')) { + var previous = location.pathname; + var push = history.pushState; + + history.pushState = function () { + var result = push.apply(this, arguments); + + if (location.pathname !== previous) { + leave(); + visible = 0; + token = null; + shownAt = Date.now(); + sent = false; + report(location.pathname, location.origin + previous); + previous = location.pathname; + } + + return result; + }; + } +})(); diff --git a/resources/lang/nl.json b/resources/lang/nl.json new file mode 100644 index 0000000..9a651ae --- /dev/null +++ b/resources/lang/nl.json @@ -0,0 +1,264 @@ +{ + "Audit log": "Auditlog", + "Banned an address": "Een adres geblokkeerd", + "Lifted the ban of an address": "De blokkade van een adres opgeheven", + "Banned the addresses of a group": "De adressen van een groep geblokkeerd", + "Lifted the bans of a group": "De blokkades van een groep opgeheven", + "Wrote or removed the note about an address": "Een notitie over een adres geschreven of verwijderd", + "Changed the rules of the audit log": "De regels van de auditlog gewijzigd", + "Opened the audit log": "De auditlog geopend", + "See the audit log: who logged in and what was done, with addresses and browsers": "De auditlog zien: wie er inlogde en wat er gedaan is, met adressen en browsers", + "Ban addresses and lift bans, write notes about addresses, and set the rules of the audit log": "Adressen blokkeren en weer vrijgeven, notities over adressen schrijven en de regels van de auditlog instellen", + "Media": "Media", + "Uploaded a file": "Een bestand geüpload", + "Changed a file": "Een bestand gewijzigd", + "Deleted a file": "Een bestand verwijderd", + "Opened the media library": "De mediabibliotheek geopend", + "See the media library and pick files from it": "De mediabibliotheek zien en er bestanden uit kiezen", + "Upload files": "Bestanden uploaden", + "Change the name, description and focus point of a file": "De naam, omschrijving en het scherpstelpunt van een bestand wijzigen", + "Delete files": "Bestanden verwijderen", + "Pages": "Pagina's", + "Opened the pages": "De pagina's geopend", + "Opened the updates": "De updates geopend", + "What customers say": "Wat klanten zeggen", + "Our jobs": "Onze klussen", + "Buttons at the top": "Knoppen bovenaan", + "Your pages on other sites": "Je pagina's op andere sites", + "Updates": "Updates", + "What changed on your website": "Wat er op je website veranderd is", + "See what changed on the site": "Zien wat er op de site veranderd is", + "Change the texts of the pages": "De teksten van de pagina's wijzigen", + "Site content": "Inhoud van de site", + "Posts": "Berichten", + "Categories and tags": "Categorieën en tags", + "Created a post": "Een bericht gemaakt", + "Changed a post": "Een bericht gewijzigd", + "Put a post on the site, or took it off": "Een bericht online gezet of offline gehaald", + "Deleted a post": "Een bericht verwijderd", + "Made a category or tag": "Een categorie of tag gemaakt", + "Renamed a category or tag": "Een categorie of tag hernoemd", + "Removed a category or tag": "Een categorie of tag verwijderd", + "Opened the posts": "De berichten geopend", + "Opened the form for a new post": "Het formulier voor een nieuw bericht geopend", + "Opened a post": "Een bericht geopend", + "Opened the preview of a post": "De voorvertoning van een bericht geopend", + "Opened the categories and tags": "De categorieën en tags geopend", + "See the posts, drafts included": "De berichten zien, concepten inbegrepen", + "Write posts: create drafts and change them": "Berichten schrijven: concepten maken en wijzigen", + "Publish, schedule and unpublish posts, and change posts that are live": "Berichten publiceren, plannen en offline halen, en berichten wijzigen die online staan", + "Delete posts (one that is live only together with publishing)": "Berichten verwijderen (een online bericht alleen samen met publiceren)", + "Manage the categories and tags: make them, and rename, merge and remove them on all posts": "De categorieën en tags beheren: maken, hernoemen, samenvoegen en verwijderen op alle berichten", + "Reviews": "Reviews", + "Opened the reviews": "De reviews geopend", + "Manage the reviews": "De reviews beheren", + "Statistics": "Statistieken", + "Exported the statistics": "De statistieken geëxporteerd", + "Opened the statistics": "De statistieken geopend", + "See the visitor statistics and download them": "De bezoekersstatistieken zien en downloaden", + "Accounts": "Accounts", + "Groups": "Groepen", + "Created an account": "Een account aangemaakt", + "Changed an account": "Een account gewijzigd", + "Deleted an account": "Een account verwijderd", + "Created a group": "Een groep aangemaakt", + "Changed a group": "Een groep gewijzigd", + "Deleted a group": "Een groep verwijderd", + "Opened the accounts": "De accounts geopend", + "Opened the groups": "De groepen geopend", + "Create, change and delete accounts, and put them in groups": "Accounts maken, wijzigen en verwijderen, en in groepen zetten", + "Users": "Gebruikers", + "Changed own account": "Eigen account gewijzigd", + "Logged in": "Ingelogd", + "Logged out": "Uitgelogd", + "Asked for :request": ":request opgevraagd", + "Was not allowed: :what": "Mocht dit niet: :what", + "The address was banned after too many failed logins": "Het adres is geblokkeerd na te veel mislukte inlogpogingen", + "Dark": "Donker", + "Light": "Licht", + "category": "categorie", + "tag": "tag", + "The :type \":name\" already exists.": "De :type \":name\" bestaat al.", + "You cannot delete your own account.": "Je kunt je eigen account niet verwijderen.", + "Another account already uses this email address.": "Een ander account gebruikt dit e-mailadres al.", + "You can only choose groups that allow nothing more than your own account.": "Je kunt alleen groepen kiezen die niet meer toestaan dan je eigen account.", + "The current password is not right.": "Het huidige wachtwoord klopt niet.", + "The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.": "De mediabibliotheek is vol: dit bestand past niet in de ruimte die over is. Verwijder bestanden die niet meer gebruikt worden, of verhoog manager.media.max_total_gb.", + "The file storage is not available right now. Try again in a moment.": "De bestandsopslag is nu niet beschikbaar. Probeer het zo opnieuw.", + ":ip is banned from the whole site.": ":ip is geblokkeerd voor de hele site.", + ":ip is banned from the manager.": ":ip is geblokkeerd voor de manager.", + "The ban of :ip is lifted.": "De blokkade van :ip is opgeheven.", + "The note about :ip is removed.": "De notitie over :ip is verwijderd.", + "The note about :ip is saved.": "De notitie over :ip is opgeslagen.", + "Rules saved.": "Regels opgeslagen.", + "That is the address you are on yourself.": "Dat is het adres waar je zelf op zit.", + "This address is on the list that is never banned.": "Dit adres staat op de lijst die nooit geblokkeerd wordt.", + "this site": "deze site", + "the manager": "de manager", + "This address is blocked from :where.": "Dit adres is geblokkeerd voor :where.", + "This address is blocked from :where until :when.": "Dit adres is geblokkeerd voor :where tot :when.", + "Switched between the simple and the whole manager": "Gewisseld tussen de simpele en de hele manager", + "See the whole manager, not only the simple screens": "De hele manager zien, niet alleen de simpele schermen", + "Switch between the simple and the whole manager": "Wisselen tussen de simpele en de hele manager", + "Manager": "Manager", + "Created a page": "Een pagina gemaakt", + "Changed a page": "Een pagina gewijzigd", + "Removed a page": "Een pagina verwijderd", + "Opened a page": "Een pagina geopend", + "A page with fields of its own cannot be removed.": "Een pagina met eigen velden kan niet verwijderd worden.", + "Resources": "Lijsten", + "Added a record": "Een item toegevoegd", + "Changed a record": "Een item gewijzigd", + "Removed a record": "Een item verwijderd", + "Opened a list": "Een lijst geopend", + "Opened the form for a new record": "Het formulier voor een nieuw item geopend", + "Opened a record": "Een item geopend", + "See :label": ":label bekijken", + "Add, change and delete :label": ":label toevoegen, wijzigen en verwijderen", + "History": "Geschiedenis", + "See the history of posts and pages": "De geschiedenis van berichten en pagina's zien", + "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", + "Settings": "Instellingen", + "Switch parts and features on or off and change settings": "Onderdelen en functies aan- of uitzetten en instellingen wijzigen", + "Change keys, passwords and addresses of integrations": "Sleutels, wachtwoorden en adressen van koppelingen wijzigen", + "Changed the settings": "Instellingen gewijzigd", + "Refreshed the settings": "Instellingen ververst", + "Opened the settings": "Instellingen geopend", + "This setting does not exist or you may not change it.": "Deze instelling bestaat niet of je mag hem niet wijzigen.", + "This value is not valid.": "Deze waarde is niet geldig.", + "Type your own password to change this.": "Typ je eigen wachtwoord om dit te wijzigen.", + "Parts of the manager": "Onderdelen van de manager", + "IriksIT API": "IriksIT API", + "Login": "Inloggen", + "Site": "Site", + "Disk for new media files": "Schijf voor nieuwe mediabestanden", + "IriksIT API: address": "IriksIT API: adres", + "IriksIT API: account": "IriksIT API: account", + "IriksIT API: password": "IriksIT API: wachtwoord", + "Turnstile: site key": "Turnstile: sitesleutel", + "Turnstile: secret key": "Turnstile: geheime sleutel", + "With its version, for example https://api.iriks-it.nl/v1": "Met de versie erbij, bijvoorbeeld https://api.iriks-it.nl/v1", + "There is nothing to try here.": "Hier valt niets te proberen.", + "The address, the account and the password are not all filled in.": "Het adres, het account en het wachtwoord zijn niet alle drie ingevuld.", + "Logging in at the IriksIT API failed:": "Inloggen bij de IriksIT API is mislukt:", + "Logged in at the IriksIT API.": "Ingelogd bij de IriksIT API.", + "Turnstile is off: the site key and the secret are not both filled in.": "Turnstile staat uit: de site key en de secret zijn niet allebei ingevuld.", + "Cloudflare does not know this secret key.": "Cloudflare kent deze geheime sleutel niet.", + "Cloudflare did not answer properly.": "Cloudflare gaf geen goed antwoord.", + "Cloudflare knows this secret key.": "Cloudflare kent deze geheime sleutel.", + "The check could not be run.": "De controle kon niet worden uitgevoerd.", + "Trying…": "Bezig met proberen…", + "Try it": "Proberen", + "Save first: it tries what is saved.": "Sla eerst op: er wordt geprobeerd met wat is opgeslagen.", + "Tried a connection of the settings": "Een verbinding van de instellingen geprobeerd", + "Features of the site": "Onderdelen van de site", + "Requests": "Aanvragen", + "See the requests that came in": "De binnengekomen aanvragen zien", + "Handle requests: mark as handled, add notes": "Aanvragen afhandelen: afhandelen en notities toevoegen", + "See what the screening kept away, move requests and block senders": "Zien wat de screening heeft tegengehouden, aanvragen verplaatsen en afzenders blokkeren", + "Delete requests": "Aanvragen verwijderen", + "The messages and requests from your website": "De berichten en aanvragen van je website", + "Marked a request as handled or open": "Een aanvraag afgehandeld of weer open gezet", + "Added a note to a request": "Een notitie bij een aanvraag gezet", + "Moved a request to another folder": "Een aanvraag naar een andere map verplaatst", + "Blocked a sender": "Een afzender geblokkeerd", + "Lifted the block of a sender": "De blokkade van een afzender opgeheven", + "Deleted a request": "Een aanvraag verwijderd", + "Opened the requests": "De aanvragen geopend", + "Opened a request": "Een aanvraag geopend", + "Callback request": "Terugbelverzoek", + "Question": "Vraag", + "Quote request": "Offerteaanvraag", + "Mail new requests to": "Nieuwe aanvragen mailen naar", + "The mail address that is told about every real request": "Het e-mailadres dat elke echte aanvraag te horen krijgt", + "Mail the visitor a confirmation": "De bezoeker een bevestiging mailen", + "Days a request is kept": "Dagen dat een aanvraag bewaard blijft", + "Days spam is kept": "Dagen dat spam bewaard blijft", + "We received your message": "We hebben je bericht ontvangen", + "Thank you, :name. We received your message and get back to you.": "Dank je wel, :name. We hebben je bericht ontvangen en komen bij je terug.", + "Open in the manager": "Openen in de manager", + "Where": "Waar", + "Call": "Bel", + "Mail": "Mail", + "This request has nothing of that kind to block.": "Deze aanvraag heeft niets van die soort om te blokkeren.", + "Everyone uses :domain: block the mail address instead of the whole domain.": "Iedereen gebruikt :domain: blokkeer het e-mailadres in plaats van het hele domein.", + "Prove you are not a program, then send it again.": "Laat zien dat je geen programma bent en verstuur het dan opnieuw.", + "This does not look like a mail address.": "Dit lijkt geen e-mailadres. Kijk het even na.", + "This does not look like a phone number.": "Dit lijkt geen telefoonnummer. Kijk het even na.", + "Give a phone number or a mail address, so we can answer.": "Vul een telefoonnummer of e-mailadres in, zodat we kunnen antwoorden.", + "When suits you?": "Wanneer schikt het?", + "Calls (taps on the number)": "Bellen (tik op het nummer)", + "WhatsApp (taps on the button)": "WhatsApp (tik op de knop)", + "Sharing": "Delen", + "Only a post that is live can be shared.": "Alleen een bericht dat live staat kan gedeeld worden.", + ":platform is not connected. Connect it under Sharing.": ":platform is niet gekoppeld. Koppel het onder Delen.", + "This platform is not connected. Connect it under Sharing.": "Dit netwerk is niet gekoppeld. Koppel het onder Delen.", + "The site did not say where its posts live (manager.sharing.post_url).": "De site heeft niet opgegeven waar de berichten staan (manager.sharing.post_url).", + "Something went wrong on this site while sharing. It is in the log.": "Er ging iets mis op deze site bij het delen. Het staat in het log.", + "This platform is not known.": "Dit netwerk is onbekend.", + "LinkedIn: client id and client secret": "LinkedIn: client-id en client-secret", + "The LinkedIn app is not set up: fill in its client id and client secret.": "De LinkedIn-app is niet ingesteld: vul het client-id en de client-secret in.", + "LinkedIn did not give a token": "LinkedIn gaf geen token", + "LinkedIn did not say whose account this is": "LinkedIn zei niet van wie dit account is", + "Check that the app has the product \"Sign In with LinkedIn using OpenID Connect\".": "Controleer of de app het product \"Sign In with LinkedIn using OpenID Connect\" heeft.", + "LinkedIn is not connected.": "LinkedIn is niet gekoppeld.", + "The connection with LinkedIn has expired. Connect again under Sharing.": "De koppeling met LinkedIn is verlopen. Koppel opnieuw onder Delen.", + "LinkedIn refused the connection. Connect again under Sharing.": "LinkedIn weigerde de koppeling. Koppel opnieuw onder Delen.", + "LinkedIn does not allow this app to post. Check that it has the product \"Share on LinkedIn\".": "LinkedIn laat deze app niet posten. Controleer of ze het product \"Share on LinkedIn\" heeft.", + "LinkedIn says there were too many posts. Try again later.": "LinkedIn zegt dat er te veel berichten waren. Probeer het later opnieuw.", + "LinkedIn did not accept the post": "LinkedIn nam het bericht niet aan", + "LinkedIn could not be reached.": "LinkedIn was niet te bereiken.", + "See where posts are shared": "Zien waar berichten gedeeld zijn", + "Share a post on a social network": "Een bericht delen op een sociaal netwerk", + "Connect and disconnect the accounts of the social networks": "De accounts van de sociale netwerken koppelen en ontkoppelen", + "Post for real": "Echt posten", + "Off: a share is written down as a dry run and nothing is sent. Keep it off on a test site.": "Uit: een deling wordt als proefrun genoteerd en er wordt niets verstuurd. Laat het uit op een testsite.", + "Address of a post": "Adres van een bericht", + "Where a post lives on the site, with {slug} for its address, for example https://example.test/blog/{slug}": "Waar een bericht op de site staat, met {slug} voor het adres, bijvoorbeeld https://example.test/blog/{slug}", + "LinkedIn: client id": "LinkedIn: client-id", + "LinkedIn: client secret": "LinkedIn: client-secret", + "Went to a social network to connect an account": "Naar een sociaal netwerk gegaan om een account te koppelen", + "Connected an account of a social network": "Een account van een sociaal netwerk gekoppeld", + "Disconnected an account of a social network": "Een account van een sociaal netwerk ontkoppeld", + "Shared a post on a social network": "Een bericht gedeeld op een sociaal netwerk", + "Opened the sharing screen": "Het deelscherm geopend", + "Opened how a post is shared": "Geopend hoe een bericht gedeeld wordt", + "Costs": "Kosten", + "What it cost": "Wat het kostte", + "What was built, and what it cost": "Wat er gebouwd is, en wat het kostte", + "See what the work on the site has cost": "Zien wat het werk aan de site heeft gekost", + "Opened the costs": "De kosten geopend", + "Numbers": "Cijfers", + "How your website is doing": "Hoe je website het doet", + "See how the site is doing, in plain words": "Zien hoe de site het doet, in gewone woorden", + "Opened the numbers": "De cijfers geopend", + "7 days": "7 dagen", + "30 days": "30 dagen", + "A year": "Een jaar", + "The last 7 days": "De afgelopen 7 dagen", + "The last 30 days": "De afgelopen 30 dagen", + "The last 12 months": "De afgelopen 12 maanden", + "the 7 days before": "de 7 dagen ervoor", + "the 30 days before": "de 30 dagen ervoor", + "the 12 months before": "de 12 maanden ervoor", + "Through Google or another search engine": "Via Google of een andere zoekmachine", + "Straight to the site: the address typed or saved": "Rechtstreeks: het adres getypt of opgeslagen", + "Through social media": "Via sociale media", + "Through a post the site shared itself": "Via een bericht dat de site zelf deelde", + "Through a link on another site": "Via een link op een andere site", + "Through a campaign or an advertisement": "Via een eigen actie of advertentie", + "In another way": "Op een andere manier", + "Something else": "Iets anders", + "Nothing is waiting for an answer.": "Er wacht niets op antwoord.", + ":new of them new": "waarvan :new nieuw", + "{1} :count is waiting for an answer|[2,*] :count are waiting for an answer": "{1} :count wacht op antwoord|[2,*] :count wachten op antwoord", + "{1} :count post is waiting for you.|[2,*] :count posts are waiting for you.": "{1} :count bericht wacht op jou.|[2,*] :count berichten wachten op jou.", + "{1} :count visitor in the last 7 days.|[2,*] :count visitors in the last 7 days.": "{1} :count bezoeker in de afgelopen 7 dagen.|[2,*] :count bezoekers in de afgelopen 7 dagen." +} diff --git a/resources/mascot/calm.webp b/resources/mascot/calm.webp new file mode 100644 index 0000000..14438c5 Binary files /dev/null and b/resources/mascot/calm.webp differ diff --git a/resources/mascot/oops.webp b/resources/mascot/oops.webp new file mode 100644 index 0000000..45f6e44 Binary files /dev/null and b/resources/mascot/oops.webp differ diff --git a/resources/mascot/pages.webp b/resources/mascot/pages.webp new file mode 100644 index 0000000..47f1884 Binary files /dev/null and b/resources/mascot/pages.webp differ diff --git a/resources/mascot/party.webp b/resources/mascot/party.webp new file mode 100644 index 0000000..a92ecc4 Binary files /dev/null and b/resources/mascot/party.webp differ diff --git a/resources/mascot/peek.webp b/resources/mascot/peek.webp new file mode 100644 index 0000000..66b6294 Binary files /dev/null and b/resources/mascot/peek.webp differ diff --git a/resources/mascot/photos.webp b/resources/mascot/photos.webp new file mode 100644 index 0000000..4c391a0 Binary files /dev/null and b/resources/mascot/photos.webp differ diff --git a/resources/mascot/point.webp b/resources/mascot/point.webp new file mode 100644 index 0000000..5206c9e Binary files /dev/null and b/resources/mascot/point.webp differ diff --git a/resources/mascot/profile.webp b/resources/mascot/profile.webp new file mode 100644 index 0000000..39d1829 Binary files /dev/null and b/resources/mascot/profile.webp differ diff --git a/resources/mascot/undo.webp b/resources/mascot/undo.webp new file mode 100644 index 0000000..009f897 Binary files /dev/null and b/resources/mascot/undo.webp differ diff --git a/resources/mascot/welcome.webp b/resources/mascot/welcome.webp new file mode 100644 index 0000000..6f9e882 Binary files /dev/null and b/resources/mascot/welcome.webp differ diff --git a/resources/mascot/write.webp b/resources/mascot/write.webp new file mode 100644 index 0000000..fd5504d Binary files /dev/null and b/resources/mascot/write.webp differ diff --git a/resources/views/banned.blade.php b/resources/views/banned.blade.php new file mode 100644 index 0000000..16528f3 --- /dev/null +++ b/resources/views/banned.blade.php @@ -0,0 +1,13 @@ + + + + + + + {{ $status === 429 ? 'Too many attempts' : 'Blocked' }} + + +

{{ $status === 429 ? 'Too many attempts' : 'Blocked' }}

+

{{ $message }}

+ + diff --git a/resources/views/components/pulse.blade.php b/resources/views/components/pulse.blade.php new file mode 100644 index 0000000..94f40d9 --- /dev/null +++ b/resources/views/components/pulse.blade.php @@ -0,0 +1,5 @@ +{{-- Counts the page in the statistics of the manager (module `statistics`). Put it once in the layout of the public site. --}} +@props(['spa' => false]) +@if (\Illuminate\Support\Facades\Route::has(\IriksIT\Manager\Support\Names::route('pulse.script'))) + +@endif diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php new file mode 100644 index 0000000..c9fa81f --- /dev/null +++ b/resources/views/dashboard.blade.php @@ -0,0 +1,16 @@ + + + + + + Manager + + +

Manager

+ + + diff --git a/resources/views/mail/lead-confirmation.blade.php b/resources/views/mail/lead-confirmation.blade.php new file mode 100644 index 0000000..a1c7e81 --- /dev/null +++ b/resources/views/mail/lead-confirmation.blade.php @@ -0,0 +1,4 @@ +

{{ __('Thank you, :name. We received your message and get back to you.', ['name' => $lead->name]) }}

+@if ($lead->message) +
{{ $lead->message }}
+@endif diff --git a/resources/views/mail/lead-received.blade.php b/resources/views/mail/lead-received.blade.php new file mode 100644 index 0000000..f9eeb74 --- /dev/null +++ b/resources/views/mail/lead-received.blade.php @@ -0,0 +1,16 @@ +

{{ $lead->kindLabel() }} — {{ $lead->name }}@if ($lead->subject): {{ $lead->subject }}@endif

+@if ($lead->message) +

{{ $lead->message }}

+@endif +@foreach (($lead->answers ?? []) as $question => $answer) +

{{ $question }}: {{ $answer }}

+@endforeach +@if ($lead->location) +

{{ __('Where') }}: {{ $lead->location }}

+@endif +

+ @if ($callLink) {{ __('Call') }} @endif + @if ($whatsappLink) · WhatsApp @endif + @if ($mailLink) · {{ __('Mail') }} @endif + · {{ __('Open in the manager') }} +

diff --git a/resources/views/shell.blade.php b/resources/views/shell.blade.php new file mode 100644 index 0000000..ae2868e --- /dev/null +++ b/resources/views/shell.blade.php @@ -0,0 +1,21 @@ + + + + + + + {{ $title }} + {{-- The theme: values were checked by IriksIT\Manager\Support\Themes, nothing else goes in here. --}} + + + + + @if ($extensions !== []) + {{-- A bundle of the site imports `vue`: this makes it the Vue of the screens. Before any module script. --}} + + @endif +
+ + + + diff --git a/routes/guest.php b/routes/guest.php new file mode 100644 index 0000000..2179397 --- /dev/null +++ b/routes/guest.php @@ -0,0 +1,12 @@ +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'); diff --git a/routes/manager.php b/routes/manager.php new file mode 100644 index 0000000..d7e82e8 --- /dev/null +++ b/routes/manager.php @@ -0,0 +1,19 @@ +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'); + +// A screen that exists only in the bundle of the site (`manager.extensions`) has no route of its own: a browser that +// asks for it gets the shell, which shows the screen. Anything else that asks for data gets a plain 404. +Route::fallback(fn () => abort(404)); diff --git a/src/Concerns/HasManagerAccess.php b/src/Concerns/HasManagerAccess.php new file mode 100644 index 0000000..c0cf0b8 --- /dev/null +++ b/src/Concerns/HasManagerAccess.php @@ -0,0 +1,83 @@ + */ + public function managerGroups(): BelongsToMany + { + return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id')->withPivot('is_primary'); + } + + /** + * The group this account is filed under: a label and a start screen, nothing more. What the account may do is + * always the sum of all its groups, the primary one included. + */ + public function managerPrimaryGroup(): ?Group + { + // A group that was attached without a choice (by the site itself) makes the first one the primary one. + return $this->managerGroups->first(fn (Group $group) => (bool) $group->pivot->is_primary) ?? $this->managerGroups->sortBy('id')->first(); + } + + public function isManagerSuperAdmin(): bool + { + return (bool) $this->getAttribute('is_super_admin'); + } + + /** + * Everything this account may do in the manager. + * + * @return list + */ + public function managerPermissions(): array + { + $registry = app(ModuleRegistry::class); + + if ($this->isManagerSuperAdmin()) { + return $registry->permissionValues(); + } + + $fromGroups = Sources::usesGroups() ? $this->managerGroups->flatMap(fn (Group $group) => $group->allowed())->all() : []; + + return $registry->complete([...$fromGroups, ...Sources::fromHost($this)]); + } + + public function hasManagerPermission(string $permission): bool + { + return in_array($permission, $this->managerPermissions(), true); + } + + /** + * Whether this account may do everything $other may. Someone who manages accounts only + * touches accounts that stay within their own rights; otherwise a new password for a + * mightier account would be a way up. + */ + public function managerOutranks(self $other): bool + { + if ($this->isManagerSuperAdmin()) { + return true; + } + + return ! $other->isManagerSuperAdmin() && array_diff($other->managerPermissions(), $this->managerPermissions()) === []; + } + + /** Whether this account may put someone in $group: only when the group gives nothing it lacks itself. */ + public function managerMayGive(Group $group): bool + { + return $this->isManagerSuperAdmin() || array_diff($group->allowed(), $this->managerPermissions()) === []; + } +} diff --git a/src/Console/CostsPriceCommand.php b/src/Console/CostsPriceCommand.php new file mode 100644 index 0000000..fb9f00e --- /dev/null +++ b/src/Console/CostsPriceCommand.php @@ -0,0 +1,29 @@ +items(); + $kept = count(array_filter($items, fn (array $item) => $item['priced_by'] === 'service')); + $fixed = count(array_filter($items, fn (array $item) => $item['priced_by'] === 'config')); + $open = count(array_filter($items, fn (array $item) => $item['tokens'] > 0 && $item['priced_by'] === null)); + + $this->info(count($items)." rows: {$kept} with a kept price, {$fixed} priced with the fixed rates, {$open} without a price."); + + return self::SUCCESS; + } +} diff --git a/src/Console/DoctorCommand.php b/src/Console/DoctorCommand.php new file mode 100644 index 0000000..555c44b --- /dev/null +++ b/src/Console/DoctorCommand.php @@ -0,0 +1,206 @@ + */ + private array $checks = []; + + public function handle(ModuleRegistry $modules): int + { + $this->checkUserModel($modules); + $this->checkTables($modules); + $this->checkRoutes(); + $this->checkNames(); + $this->checkModules($modules); + + $failed = collect($this->checks)->contains('status', 'fail'); + + if ($this->option('json')) { + $this->line(json_encode(['ok' => ! $failed, 'checks' => $this->checks], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + } else { + foreach ($this->checks as $check) { + $line = sprintf('[%s] %s: %s', strtoupper($check['status']), $check['check'], $check['message']); + $check['status'] === 'fail' ? $this->error($line) : ($check['status'] === 'warn' ? $this->warn($line) : $this->info($line)); + + if ($check['fix'] !== null && $check['status'] !== 'ok') { + $this->line(' fix: '.$check['fix']); + } + } + } + + return $failed ? self::FAILURE : self::SUCCESS; + } + + private function add(string $check, string $status, string $message, ?string $fix = null): void + { + $this->checks[] = ['check' => $check, 'status' => $status, 'message' => $message, 'fix' => $fix]; + } + + private function checkUserModel(ModuleRegistry $modules): void + { + $model = config('manager.user_model'); + + if (! is_string($model) || ! class_exists($model)) { + $this->add('user_model', 'fail', 'manager.user_model is not a class: '.var_export($model, true), 'Set MANAGER_USER_MODEL (or manager.user_model) to your User model, for example App\\Models\\User.'); + + return; + } + + $this->add('user_model', 'ok', "The user model is {$model}."); + + $guard = config('auth.defaults.guard'); + $loggedIn = config('auth.providers.'.config("auth.guards.{$guard}.provider").'.model'); + + if (is_string($loggedIn) && $loggedIn !== $model && ! is_subclass_of($loggedIn, $model) && ! is_subclass_of($model, $loggedIn)) { + $this->add('auth_model', 'fail', "People log in as {$loggedIn} (config/auth.php), but manager.user_model is {$model}: the manager would not know their rights.", 'Point manager.user_model (MANAGER_USER_MODEL) at the same model as the auth provider.'); + } + + if (! in_array(HasManagerAccess::class, class_uses_recursive($model), true)) { + $this->add('user_trait', 'fail', "{$model} does not use HasManagerAccess.", "Add `use \\IriksIT\\Manager\\Concerns\\HasManagerAccess;` inside the class {$model}."); + + return; + } + + $this->add('user_trait', 'ok', 'The user model uses HasManagerAccess.'); + + if (in_array('is_super_admin', (new $model)->getFillable(), true)) { + $this->add('super_admin_fillable', 'fail', 'is_super_admin is mass assignable: anyone who can fill the model could make themselves a super admin.', 'Remove is_super_admin from $fillable of the user model.'); + } + + if ($modules->enabled('users') && Schema::hasTable((new $model)->getTable()) && Schema::hasTable(Names::table('groups'))) { + $admins = $model::query()->where('is_super_admin', true)->count(); + $admins > 0 + ? $this->add('super_admin', 'ok', "{$admins} super admin(s) exist.") + : $this->add('super_admin', 'warn', 'There is no super admin yet: nobody can manage groups.', 'php artisan manager:create-user --name=... --email=... --password=...'); + } + } + + private function checkTables(ModuleRegistry $modules): void + { + $missing = []; + + foreach ($modules->active() as $module) { + foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) { + if (! Schema::hasTable(Names::table($table))) { + $missing[] = Names::table($table); + } + } + } + + $missing === [] + ? $this->add('tables', 'ok', 'The tables of every active module exist.') + : $this->add('tables', 'fail', 'Missing tables: '.implode(', ', $missing), 'php artisan migrate'); + + // A table of the site that the package adopted (`manager.tables`) may lack columns the package writes. + $lacking = []; + + foreach ($modules->active() as $module) { + foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) { + if ($missingColumns = Tables::missingColumns($table)) { + $lacking[] = Names::table($table).' ('.implode(', ', $missingColumns).')'; + } + } + } + + if ($lacking !== []) { + $this->add('columns', 'fail', 'Columns the manager needs are missing: '.implode('; ', $lacking), 'Add them with a migration of the site, or run `php artisan migrate` when the manager migrations have not run yet.'); + } + } + + private function checkRoutes(): void + { + Route::has(Names::route('dashboard')) + ? $this->add('routes', 'ok', 'The manager routes are registered under /'.trim((string) config('manager.path'), '/').'.') + : $this->add('routes', 'fail', 'The manager routes are not registered.', 'Run `composer dump-autoload` and make sure the package service provider is discovered (not in dont-discover).'); + + if (Route::has('login')) { + $this->add('login', 'ok', 'The app has a login route.'); + } elseif (Route::has(Names::route('login'))) { + $this->add('login', 'ok', 'The app has no login of its own: visitors use the login of the manager.'); + } else { + $this->add('login', 'warn', 'There is no login: the auth middleware has nowhere to send visitors.', 'Set MANAGER_UI=package (the manager brings a login), or add a login to the app.'); + } + } + + /** Route names or addresses of the site that the package would share with its own. */ + private function checkNames(): void + { + $prefix = Names::routePrefix(); + $path = trim((string) config('manager.path'), '/'); + $names = []; + $foreign = []; + + foreach (Route::getRoutes()->getRoutes() as $route) { + $name = (string) $route->getName(); + $mine = $route->isFallback || ($route->getActionName() === 'Closure' && str_starts_with($name, $prefix)) || str_starts_with(ltrim($route->getActionName(), '\\'), 'IriksIT\\Manager\\'); + + if ($prefix !== '' && str_starts_with($name, $prefix) && $name !== $prefix) { + $names[$name] = ($names[$name] ?? 0) + 1; + } + + if (! $mine && ($route->uri() === $path || str_starts_with($route->uri(), $path.'/'))) { + $foreign[] = $route->uri(); + } + } + + $twice = array_keys(array_filter($names, fn (int $count) => $count > 1)); + + if ($twice !== []) { + $this->add('names', 'warn', 'Route names used twice: '.implode(', ', array_slice($twice, 0, 5)).'. The site and the manager share them, and one of the two stops working.', "Set 'route_name' in config/manager.php to something the site does not use, for example 'cms'."); + } elseif ($foreign !== []) { + $this->add('names', 'warn', 'The site has routes under the address of the manager: '.implode(', ', array_slice($foreign, 0, 5)).'.', "Move them, or set 'path' in config/manager.php (MANAGER_PATH) to another address."); + } else { + $this->add('names', 'ok', 'No route name or address is shared with the site.'); + } + } + + private function checkModules(ModuleRegistry $modules): void + { + $active = array_keys($modules->active()); + $this->add('modules', 'ok', 'Active modules: '.implode(', ', $active).'.'); + + if ($modules->enabled('media')) { + $disk = config('manager.media.disk'); + config("filesystems.disks.{$disk}") === null + ? $this->add('media_disk', 'fail', "The media disk \"{$disk}\" is not in config/filesystems.php.", 'Set MANAGER_MEDIA_DISK to a disk that exists.') + : $this->add('media_disk', 'ok', "The media disk is \"{$disk}\"."); + + if ($disk === 'public' && ! file_exists(public_path('storage'))) { + $this->add('storage_link', 'warn', 'public/storage does not exist: uploaded files cannot be served from the public disk.', 'php artisan storage:link'); + } + } + + if ($modules->enabled('audit')) { + $this->add('proxies', 'warn', 'The audit log stores the visitor address. Behind a proxy or load balancer, trusted proxies must be configured, or every visitor looks like one address and one bad actor can lock the manager out.', 'Configure trusted proxies (bootstrap/app.php: $middleware->trustProxies(...)) and set MANAGER_NEVER_BAN to your own address.'); + } + + if ($modules->enabled('statistics')) { + $pages = (array) config('manager.statistics.pages'); + $pages === ['/'] && ! config('manager.statistics.posts_path') + ? $this->add('statistics_pages', 'warn', 'Only the home page counts in the statistics.', 'Set manager.statistics.pages (and posts_path), or register a resolver with CountedPages::register().') + : $this->add('statistics_pages', 'ok', 'The statistics count '.count($pages).' page(s) and '.(config('manager.statistics.posts_path') ? 'the posts' : 'no posts').'.'); + } + } +} diff --git a/src/Console/ImportCommand.php b/src/Console/ImportCommand.php new file mode 100644 index 0000000..bdb25e8 --- /dev/null +++ b/src/Console/ImportCommand.php @@ -0,0 +1,84 @@ +` (`table`, `connection`, `map`). + */ +class ImportCommand extends Command +{ + protected $signature = 'manager:import {target : posts, pages, reviews, media, leads or taps} + {--table= : Table to read (default: config manager.import..table)} + {--connection= : Database connection of that table (default: the default one)} + {--map=* : package_column=source_column, repeat for each column that is named differently} + {--set=* : package_column=value, a value for every row that has none (for media: --set=disk=iriksit)} + {--limit= : Only the first rows} + {--dry-run : Count what would happen and write nothing}'; + + protected $description = 'Copy the existing posts, pages, reviews, media, leads or taps rows of the site into the package tables'; + + public function handle(Importer $importer): int + { + $target = (string) $this->argument('target'); + $config = (array) config('manager.import.'.$target, []); + $table = $this->option('table') ?: ($config['table'] ?? null); + + if (! is_string($table) || $table === '') { + $this->error('Which table? Give --table=... or set manager.import.'.$target.'.table.'); + + return self::FAILURE; + } + + $map = (array) ($config['map'] ?? []); + + foreach ((array) $this->option('map') as $pair) { + if (! str_contains((string) $pair, '=')) { + $this->error("--map wants package_column=source_column, got {$pair}"); + + return self::FAILURE; + } + + [$to, $from] = explode('=', (string) $pair, 2); + $map[trim($to)] = trim($from); + } + + $fixed = []; + + foreach ((array) $this->option('set') as $pair) { + if (! str_contains((string) $pair, '=')) { + $this->error("--set wants package_column=value, got {$pair}"); + + return self::FAILURE; + } + + [$column, $value] = explode('=', (string) $pair, 2); + $fixed[trim($column)] = $value; + } + + try { + $connection = DB::connection($this->option('connection') ?: ($config['connection'] ?? null)); + $result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null, $fixed); + } catch (InvalidArgumentException $e) { + $this->error($e->getMessage()); + + return self::FAILURE; + } + + foreach ($result['problems'] as $problem) { + $this->warn($problem); + } + + $this->info(($this->option('dry-run') ? 'Dry run: ' : '')."{$result['created']} created, {$result['updated']} updated, {$result['skipped']} skipped."); + + return self::SUCCESS; + } +} diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php new file mode 100644 index 0000000..82745e4 --- /dev/null +++ b/src/Console/InstallCommand.php @@ -0,0 +1,96 @@ +callSilently('vendor:publish', ['--tag' => 'manager-config']); + + $env = []; + + if ($list = $this->option('modules')) { + $wanted = array_filter(array_map('trim', explode(',', $list))); + $unknown = array_diff($wanted, array_keys($modules->all())); + + if ($unknown !== []) { + $this->error('Unknown module(s): '.implode(', ', $unknown).'. Known: '.implode(', ', array_keys($modules->all())).'.'); + + return self::FAILURE; + } + + foreach (array_keys($modules->all()) as $key) { + if (in_array($key, ['users', 'media'], true)) { + continue; // switched in config, on by default + } + + $env['MANAGER_'.strtoupper($key)] = in_array($key, $wanted, true) ? 'true' : 'false'; + } + } + + if ($model = $this->option('user-model')) { + $env['MANAGER_USER_MODEL'] = $model; + } + + if ($path = $this->option('path')) { + $env['MANAGER_PATH'] = trim($path, '/'); + } + + foreach ($env as $key => $value) { + $this->writeEnv($key, $value); + } + + if ($env !== []) { + $this->line('Wrote to .env: '.implode(', ', array_map(fn ($k, $v) => "{$k}={$v}", array_keys($env), $env)).'. Run `php artisan config:clear` if the config is cached.'); + } + + if ($this->option('migrate')) { + // The switches were just written: a fresh process sees them, this one still has the old config. + $this->line('Run `php artisan migrate` (a new process) so the migrations of the modules you switched on are loaded.'); + } + + if ($env !== []) { + // This process still has the old config: its check would report the old state. A new process is right. + $this->line('Next: add the HasManagerAccess trait to the user model, run `php artisan config:clear && php artisan migrate && php artisan storage:link`, then `php artisan manager:doctor --json`.'); + + return self::SUCCESS; + } + + return Artisan::call('manager:doctor', $this->option('json') ? ['--json' => true] : [], $this->output) === 0 ? self::SUCCESS : self::FAILURE; + } + + private function writeEnv(string $key, string $value): void + { + $file = base_path('.env'); + $contents = file_exists($file) ? file_get_contents($file) : ''; + $line = "{$key}={$value}"; + + $contents = preg_match("/^{$key}=.*$/m", $contents) + ? preg_replace("/^{$key}=.*$/m", $line, $contents) + : rtrim($contents, "\n")."\n{$line}\n"; + + file_put_contents($file, $contents); + } +} diff --git a/src/Console/LeadsPruneCommand.php b/src/Console/LeadsPruneCommand.php new file mode 100644 index 0000000..4988c26 --- /dev/null +++ b/src/Console/LeadsPruneCommand.php @@ -0,0 +1,38 @@ +where(fn ($q) => $q->whereNull('outcome')->orWhere('outcome', '!=', Lead::WON)) + ->where('folder', '!=', Lead::SPAM)->where('created_at', '<', now()->subDays(max(1, (int) config('manager.leads.keep_days', 365)))); + $spam = Lead::query()->where('folder', Lead::SPAM)->where('created_at', '<', now()->subDays(max(1, (int) config('manager.leads.keep_spam_days', 30)))); + $blocks = LeadBlock::query()->whereNotNull('expires_at')->where('expires_at', '<', now()); + + $counts = ['requests' => $old->count(), 'spam' => $spam->count(), 'blocks' => $blocks->count()]; + + if (! $this->option('dry-run')) { + $old->delete(); + $spam->delete(); + $blocks->delete(); + } + + $this->components->info(($this->option('dry-run') ? 'Would remove' : 'Removed')." {$counts['requests']} requests, {$counts['spam']} spam, {$counts['blocks']} blocks."); + + return self::SUCCESS; + } +} diff --git a/src/Console/MakeThemeCommand.php b/src/Console/MakeThemeCommand.php new file mode 100644 index 0000000..5bd6920 --- /dev/null +++ b/src/Console/MakeThemeCommand.php @@ -0,0 +1,95 @@ +argument('key'); + + if (! preg_match('/^[a-z0-9][a-z0-9-]{0,40}$/', $key)) { + $this->error('The key may only hold lowercase letters, numbers and dashes.'); + + return self::FAILURE; + } + + $raw = [ + 'label' => $this->option('label') ?: ucfirst($key), + 'scheme' => $this->option('light') ? 'light' : 'dark', + 'name' => $this->option('name'), + 'logo' => $this->option('logo'), + 'font' => $this->option('font'), + 'font_display' => $this->option('font-display'), + 'radius' => $this->option('radius'), + 'colors' => array_filter([ + 'brand' => $this->option('brand'), 'brand_alt' => $this->option('brand-alt'), 'ink' => $this->option('ink'), + 'panel' => $this->option('panel'), 'text' => $this->option('text'), + ]), + ]; + + // What the manager would accept: tell what was thrown away instead of silently writing a different theme. + $clean = $themes->sanitize($key, $raw); + $rejected = []; + + foreach ($raw['colors'] as $name => $value) { + ($clean['colors'][$name] ?? null) === $value || $rejected[] = $name.' ('.$value.')'; + } + + foreach (['radius', 'font', 'font_display', 'logo'] as $option) { + $raw[$option] !== null && ($clean[$option] ?? null) !== $raw[$option] && $rejected[] = $option.' ('.$raw[$option].')'; + } + + if ($rejected !== []) { + $this->error('Not accepted: '.implode(', ', $rejected).'. Colours are #rgb or #rrggbb; no quotes or semicolons in fonts.'); + + return self::FAILURE; + } + + $folder = $this->option('path') ?: (config('manager.themes_path') ?: resource_path('manager-themes')); + $file = rtrim($folder, '/')."/{$key}.json"; + + if (file_exists($file) && ! $this->option('force')) { + $this->error("{$file} exists. Use --force to overwrite it."); + + return self::FAILURE; + } + + is_dir($folder) || mkdir($folder, 0775, true); + $out = array_filter(['label' => $clean['label'], 'scheme' => $clean['scheme'], 'name' => $clean['name'], 'logo' => $clean['logo'], 'font' => $clean['font'], 'font_display' => $clean['font_display'], 'radius' => $clean['radius'], 'colors' => $clean['colors']], fn ($value) => $value !== null); + file_put_contents($file, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n"); + + $this->info("Wrote {$file}. Everyone sees it with MANAGER_THEME={$key}; each account can pick it in its profile."); + + return self::SUCCESS; + } +} diff --git a/src/Console/MediaMoveCommand.php b/src/Console/MediaMoveCommand.php new file mode 100644 index 0000000..75d5ee0 --- /dev/null +++ b/src/Console/MediaMoveCommand.php @@ -0,0 +1,97 @@ +argument('to'); + + if (config("filesystems.disks.{$to}") === null) { + $this->error("There is no disk called {$to}."); + + return self::FAILURE; + } + + $dryRun = (bool) $this->option('dry-run'); + $limit = max((int) $this->option('limit'), 0); + $maxBytes = max(1, (int) config('manager.media.max_file_mb')) * 1024 * 1024; + [$moved, $skipped, $failed] = [0, 0, 0]; + + $query = Media::query()->where('disk', '!=', $to)->when($this->option('from'), fn ($q, $from) => $q->where('disk', $from))->orderBy('id'); + + foreach ($query->get() as $media) { + if ($limit > 0 && $moved + $failed >= $limit) { + break; + } + + $label = "#{$media->id} {$media->filename}"; + + if (! Storage::disk($media->disk)->exists($media->location)) { + $this->warn("{$label}: not on the `{$media->disk}` disk, skipped."); + $skipped++; + + continue; + } + + if ((int) $media->size > $maxBytes) { + $this->warn("{$label}: larger than manager.media.max_file_mb, stays where it is."); + $skipped++; + + continue; + } + + if ($dryRun) { + $this->line("{$label}: would be moved from `{$media->disk}`."); + $moved++; + + continue; + } + + try { + $library->move($media, $to, (bool) $this->option('delete-source'), (bool) $this->option('verify')); + } catch (MediaStorageException|Throwable $e) { + $this->error("{$label}: could not be moved, left where it is ({$e->getMessage()})"); + $failed++; + + continue; + } + + $this->line("{$label}: moved."); + $moved++; + } + + $this->info(($dryRun ? 'Would move' : 'Moved')." {$moved}, skipped {$skipped}, failed {$failed}."); + + if (! $dryRun && $failed === 0 && config('manager.media.disk') !== $to) { + $this->warn("manager.media.disk is not `{$to}` yet: new uploads still go to `".config('manager.media.disk').'`.'); + } + + return $failed === 0 ? self::SUCCESS : self::FAILURE; + } +} diff --git a/src/Console/MediaPruneCommand.php b/src/Console/MediaPruneCommand.php new file mode 100644 index 0000000..a85e210 --- /dev/null +++ b/src/Console/MediaPruneCommand.php @@ -0,0 +1,104 @@ +option('orphans') ? $this->orphans() : $this->unused($library); + } + + private function unused(MediaLibrary $library): int + { + $days = max(0, (int) $this->option('older-than')); + $candidates = Media::query()->where('created_at', '<', now()->subDays($days))->orderBy('id')->get(); + $counts = $library->usageCounts($candidates); + $found = $deleted = $failed = 0; + + foreach ($candidates as $media) { + if (($counts[$media->id] ?? 0) > 0) { + continue; + } + + $found++; + $label = "#{$media->id} {$media->filename} (".round($media->size / 1024).' KB)'; + + if (! $this->option('delete')) { + $this->line("{$label}: not used."); + + continue; + } + + try { + $library->delete($media); + $this->line("{$label}: deleted."); + $deleted++; + } catch (Throwable $e) { + $this->error("{$label}: could not be deleted ({$e->getMessage()})"); + $failed++; + } + } + + $this->info($this->option('delete') ? "Deleted {$deleted}, failed {$failed}." : "{$found} not used. Run again with --delete to remove them."); + + return $failed === 0 ? self::SUCCESS : self::FAILURE; + } + + private function orphans(): int + { + $name = (string) ($this->option('disk') ?: config('manager.media.disk')); + $known = Media::query()->where('disk', $name)->pluck('location')->flip(); + $disk = Storage::disk($name); + + try { + $files = $disk->allFiles('media'); + } catch (Throwable) { + $files = []; + } + + if ($files === [] && Media::query()->where('disk', $name)->exists()) { + $this->warn("The disk `{$name}` cannot list its files (or has none), so there is nothing to compare."); + + return self::SUCCESS; + } + + $found = 0; + + foreach ($files as $file) { + if ($known->has($file)) { + continue; + } + + $found++; + $this->line($this->option('delete') ? "{$file}: ".($disk->delete($file) ? 'deleted.' : 'could not be deleted.') : "{$file}: no row knows it."); + } + + $this->info($this->option('delete') ? "Looked at {$found} unknown files." : "{$found} files that no row knows. Run again with --delete to remove them."); + + return self::SUCCESS; + } +} diff --git a/src/Console/SettingsCommand.php b/src/Console/SettingsCommand.php new file mode 100644 index 0000000..114d8f2 --- /dev/null +++ b/src/Console/SettingsCommand.php @@ -0,0 +1,144 @@ +argument('action'); + + if ($action === 'refresh') { + $this->info($writer->refresh() ? 'Refreshed.' : 'The caches are emptied, but the file bootstrap/cache/manager-settings.php could not be written.'); + + return self::SUCCESS; + } + + if ($action === 'list') { + return $this->list($definitions, $store); + } + + if (! in_array($action, ['get', 'set', 'reset'], true)) { + $this->error('Use one of: list, get, set, reset, refresh.'); + + return self::FAILURE; + } + + $key = (string) $this->argument('key'); + $definition = $definitions->find($key); + + if ($definition === null) { + $this->error("There is no setting {$key}. See: php artisan manager:settings list"); + + return self::FAILURE; + } + + if ($action === 'get') { + $this->line($definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key))); + + return self::SUCCESS; + } + + if ($action === 'reset') { + $result = $writer->apply([$key => null]); + $this->info("{$key} is back to what the config says.".($result['file_written'] ? '' : ' (The compiled file could not be written.)')); + + return self::SUCCESS; + } + + return $this->set($definitions, $writer, $definition); + } + + /** @param array $definition */ + private function set(Definitions $definitions, Writer $writer, array $definition): int + { + $key = $definition['key']; + + if ($this->option('stdin')) { + $raw = rtrim((string) stream_get_contents(STDIN), "\r\n"); + } elseif ($definition['type'] === 'secret') { + if ($this->argument('value') !== null) { + $this->error('Do not type a secret as an argument: it stays in the history of the shell. Leave it out to be asked, or use --stdin.'); + + return self::FAILURE; + } + + $raw = (string) $this->secret($definition['label']); + } else { + $raw = $this->argument('value'); + + if ($raw === null) { + $this->error('Which value? php artisan manager:settings set '.$key.' '); + + return self::FAILURE; + } + } + + try { + $value = $definitions->cast($definition, $raw); + } catch (\InvalidArgumentException) { + $this->error('This value is not valid for '.$key.' ('.$definition['type'].').'); + + return self::FAILURE; + } + + $result = $writer->apply([$key => $value]); + $this->info("{$key} is set.".($result['env_written'] ? ' Written into .env too.' : '').($result['file_written'] ? '' : ' (The compiled file could not be written: run `manager:settings refresh` when it can.)')); + + return self::SUCCESS; + } + + private function list(Definitions $definitions, Store $store): int + { + $rows = []; + + foreach ($definitions->all() as $key => $definition) { + $rows[] = [ + 'key' => $key, + 'type' => $definition['type'], + 'value' => $definition['type'] === 'secret' ? (filled(config($key)) ? 'set' : 'not set') : $this->show(config($key)), + 'saved' => $store->has($key), + ]; + } + + if ($this->option('json')) { + $this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + + return self::SUCCESS; + } + + $this->table(['Setting', 'Type', 'Value', 'Saved here'], array_map(fn ($row) => [$row['key'], $row['type'], $row['value'], $row['saved'] ? 'yes' : ''], $rows)); + + return self::SUCCESS; + } + + private function show(mixed $value): string + { + return is_bool($value) ? ($value ? 'true' : 'false') : (string) ($value ?? ''); + } +} diff --git a/src/Console/StorageCheckCommand.php b/src/Console/StorageCheckCommand.php new file mode 100644 index 0000000..8d44eda --- /dev/null +++ b/src/Console/StorageCheckCommand.php @@ -0,0 +1,66 @@ +option('disk') ?: config('manager.media.disk')); + $disk = Storage::disk($name); + $location = 'manager-check/'.bin2hex(random_bytes(6)).'.txt'; + $content = 'manager storage check '.now()->toIso8601String(); + + $this->line("Disk: {$name}"); + + try { + $step = 'write'; + if (! $disk->put($location, $content)) { + $this->components->error('The file could not be written. See the log of the app for the reason.'); + + return self::FAILURE; + } + $this->components->info('Written.'); + + $step = 'read'; + $back = $disk->get($location); + if ($back !== $content) { + $this->components->error('What was read back is not what was written.'); + + return self::FAILURE; + } + $this->components->info('Read back: the same.'); + + $step = 'delete'; + if (! $disk->delete($location)) { + $this->components->error("The test file could not be deleted: {$location}"); + + return self::FAILURE; + } + $this->components->info('Deleted.'); + } catch (MediaStorageException|Throwable $e) { + $this->components->error("Could not {$step}: ".$e->getMessage()); + + return self::FAILURE; + } + + $this->components->info('The storage works.'); + + return self::SUCCESS; + } +} diff --git a/src/Console/UserListCommand.php b/src/Console/UserListCommand.php new file mode 100644 index 0000000..4bc544f --- /dev/null +++ b/src/Console/UserListCommand.php @@ -0,0 +1,49 @@ +with('managerGroups')->orderBy('id')->get() as $user) { + $primary = $user->managerPrimaryGroup(); + + $rows[] = [ + 'id' => $user->getKey(), + 'name' => (string) $user->name, + 'email' => (string) $user->email, + 'super_admin' => $user->isManagerSuperAdmin(), + 'primary_group' => $primary?->name, + 'groups' => $user->managerGroups->pluck('name')->sort()->values()->all(), + ]; + } + + if ($this->option('json')) { + $this->line(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + + return self::SUCCESS; + } + + $this->table(['Id', 'Name', 'Email', 'Super admin', 'Primary group', 'Groups'], array_map( + fn ($row) => [$row['id'], $row['name'], $row['email'], $row['super_admin'] ? 'yes' : '', $row['primary_group'] ?? '', implode(', ', $row['groups'])], + $rows, + )); + + return self::SUCCESS; + } +} diff --git a/src/Console/UserPasswordCommand.php b/src/Console/UserPasswordCommand.php new file mode 100644 index 0000000..0ded31d --- /dev/null +++ b/src/Console/UserPasswordCommand.php @@ -0,0 +1,57 @@ +where('email', strtolower((string) $this->argument('email')))->first(); + + if ($user === null) { + $this->error('There is no account with that email address.'); + + return self::FAILURE; + } + + if ($this->option('generate')) { + $password = Str::password(20, symbols: false); + } else { + $password = (string) $this->secret('New password (min 12 characters)'); + + if (mb_strlen($password) < 12) { + $this->error('The password must be at least 12 characters.'); + + return self::FAILURE; + } + + if ($password !== (string) $this->secret('Once more')) { + $this->error('The two passwords are not the same.'); + + return self::FAILURE; + } + } + + $user->forceFill(['password' => Hash::make($password)])->save(); + $this->info("New password for {$user->email} is set."); + $this->option('generate') && $this->line($password); + + return self::SUCCESS; + } +} diff --git a/src/Contracts/LoginCheck.php b/src/Contracts/LoginCheck.php new file mode 100644 index 0000000..37cf31d --- /dev/null +++ b/src/Contracts/LoginCheck.php @@ -0,0 +1,30 @@ +> + */ + public function fields(): array; + + /** Runs first, before the password is looked at: a captcha belongs here. */ + public function before(Request $request): void; + + /** + * Runs when the email and password are right, before anyone is logged in: a second factor belongs here. When it refuses, the + * attempt counts as a failed login (the audit log and the bans see it). + */ + public function after(Request $request, Authenticatable $user): void; +} diff --git a/src/Contracts/Module.php b/src/Contracts/Module.php new file mode 100644 index 0000000..39f1707 --- /dev/null +++ b/src/Contracts/Module.php @@ -0,0 +1,73 @@ + keys of modules this one cannot work without */ + public function requires(): array; + + /** + * Permissions this module adds. Values are prefixed by the module key. + * + * @return list + */ + public function permissions(): array; + + /** @return list */ + public function navigation(): array; + + /** Absolute path of the routes file, or null. */ + public function routes(): ?string; + + /** Absolute path of a routes file outside the manager (no prefix, no manager middleware), or null. */ + public function publicRoutes(): ?string; + + /** Absolute path of the migrations folder, or null. */ + public function migrations(): ?string; + + /** @return list Artisan commands this module adds */ + public function commands(): array; + + /** + * What the audit log calls each thing that is done through this module's routes, by route + * name without the `manager.` prefix: `[label]` or `[label, [form fields that may be kept]]`. + * Never list a field a secret could be typed in. + * + * @return array}> + */ + public function actions(): array; + + /** + * What the audit log calls opening a page (a GET route), by route name without `manager.`. + * + * @return array + */ + public function views(): array; + + /** + * Middleware this module wants around every manager route: `before` runs ahead of the site's + * own manager middleware (session, login), `after` behind it. + * + * @return array{before?: list, after?: list} + */ + public function middleware(): array; + + /** Runs at boot, only when the module is on (register rate limiters, usage sources, ...). */ + public function boot(): void; +} diff --git a/src/Contracts/PermissionResolver.php b/src/Contracts/PermissionResolver.php new file mode 100644 index 0000000..17ccd59 --- /dev/null +++ b/src/Contracts/PermissionResolver.php @@ -0,0 +1,15 @@ + permission values such as `posts.write` */ + public function permissions(Authenticatable $user): array; +} diff --git a/src/Contracts/Sharer.php b/src/Contracts/Sharer.php new file mode 100644 index 0000000..d1b247d --- /dev/null +++ b/src/Contracts/Sharer.php @@ -0,0 +1,55 @@ + 'application/javascript', 'manager.css' => 'text/css', 'vue.js' => 'application/javascript']; + + public function __invoke(string $file): BinaryFileResponse + { + abort_unless(isset(self::FILES[$file]) && is_file($path = __DIR__.'/../../../resources/dist/'.$file), 404); + + return response()->file($path, [ + 'Content-Type' => self::FILES[$file], + 'Cache-Control' => 'public, max-age=31536000, immutable', + 'X-Content-Type-Options' => 'nosniff', + ]); + } +} diff --git a/src/Http/Controllers/DashboardController.php b/src/Http/Controllers/DashboardController.php new file mode 100644 index 0000000..852e5a2 --- /dev/null +++ b/src/Http/Controllers/DashboardController.php @@ -0,0 +1,39 @@ +user(); + + // Only what this account may reach, in the face it looks at. + $navigation = $menu->for($user, array_values(array_filter($modules->permissionValues(), fn (string $permission) => $user?->can($permission)))); + + // What the big buttons of the simple start screen say: by the address of the menu item. + $facts = []; + + foreach ($tiles->for($user) as $route => $fact) { + $facts[route($route, [], false)] = $fact; + } + + $help = (array) config('manager.simple.help', []); + $site = config('manager.simple.site_link', '/'); + + return $request->wantsJson() + ? response()->json([ + 'navigation' => $navigation, + 'facts' => (object) $facts, + // A way to ask for help (a name and a link, for example a WhatsApp link) and a link to the site, under the buttons. + 'help' => is_string($help['link'] ?? null) && ($help['link'] ?? '') !== '' ? ['name' => (string) ($help['name'] ?? ''), 'link' => $help['link']] : null, + 'site' => is_string($site) && $site !== '' ? $site : null, + ]) + : view('manager::dashboard', ['navigation' => $navigation]); + } +} diff --git a/src/Http/Controllers/LoginController.php b/src/Http/Controllers/LoginController.php new file mode 100644 index 0000000..ec787f4 --- /dev/null +++ b/src/Http/Controllers/LoginController.php @@ -0,0 +1,57 @@ +before($request); + + $credentials = $request->validate([ + 'email' => ['required', 'string', 'email', 'max:255'], + 'password' => ['required', 'string', 'max:200'], + ]); + + $refused = null; + + // `attemptWhen` runs the second checks after the password is right and before the login begins; a refusal is a failed login. + $loggedIn = Auth::attemptWhen($credentials, function ($user) use ($checks, $request, &$refused) { + try { + $checks->after($request, $user); + } catch (ValidationException $e) { + $refused = $e; + + return false; + } + + return true; + }, $request->boolean('remember')); + + if (! $loggedIn) { + throw $refused ?? ValidationException::withMessages(['email' => trans('auth.failed')]); + } + + $request->session()->regenerate(); + + return response()->json(['redirect' => '/'.trim((string) config('manager.path'), '/')]); + } + + public function destroy(Request $request): JsonResponse + { + Auth::guard()->logout(); + $request->session()->invalidate(); + $request->session()->regenerateToken(); + + return response()->json(['redirect' => Route::has(Names::route('login')) ? route(Names::route('login'), [], false) : '/']); + } +} diff --git a/src/Http/Controllers/MarkdownController.php b/src/Http/Controllers/MarkdownController.php new file mode 100644 index 0000000..c67d6d6 --- /dev/null +++ b/src/Http/Controllers/MarkdownController.php @@ -0,0 +1,18 @@ +validate(['text' => ['nullable', 'string', 'max:200000']]); + + return response()->json(['html' => Markdown::toHtml((string) ($data['text'] ?? ''))]); + } +} diff --git a/src/Http/Controllers/MascotController.php b/src/Http/Controllers/MascotController.php new file mode 100644 index 0000000..6f2e422 --- /dev/null +++ b/src/Http/Controllers/MascotController.php @@ -0,0 +1,43 @@ +.webp` or `.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 '' + .'' + .'' + .''; + } +} diff --git a/src/Http/Controllers/ProfileController.php b/src/Http/Controllers/ProfileController.php new file mode 100644 index 0000000..2e894b5 --- /dev/null +++ b/src/Http/Controllers/ProfileController.php @@ -0,0 +1,87 @@ +user(); + + return response()->json(['profile' => [ + 'name' => (string) $user->name, + 'email' => (string) $user->email, + '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() + : [], + ]]); + } + + /** The face of the manager (`full` or `simple`) an account that may switch looks at. */ + public function view(Request $request, Menu $menu): JsonResponse + { + 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']]); + + 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(); + app(AuditTrail::class)->about($user); + + $data = $request->validate([ + 'name' => ['required', 'string', 'max:255'], + '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())) { + return response()->json(['message' => $wrong = __('The current password is not right.'), 'errors' => ['current_password' => [$wrong]]], 422); + } + + $user->name = $data['name']; + ($data['password'] ?? '') !== '' && $user->password = Hash::make($data['password']); + $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]); + } + + return response()->json(['saved' => true]); + } +} diff --git a/src/Http/Middleware/Authenticate.php b/src/Http/Middleware/Authenticate.php new file mode 100644 index 0000000..ae86f6e --- /dev/null +++ b/src/Http/Middleware/Authenticate.php @@ -0,0 +1,21 @@ +expectsJson()) { + return null; + } + + return Route::has('login') ? route('login') : (Route::has(Names::route('login')) ? route(Names::route('login')) : null); + } +} diff --git a/src/Http/Middleware/RequireFeature.php b/src/Http/Middleware/RequireFeature.php new file mode 100644 index 0000000..44ce11a --- /dev/null +++ b/src/Http/Middleware/RequireFeature.php @@ -0,0 +1,19 @@ +middleware('manager.feature:services')`. When the feature is off the page is not there. */ +final class RequireFeature +{ + public function handle(Request $request, Closure $next, string $feature): Response + { + abort_unless(Features::on($feature), 404); + + return $next($request); + } +} diff --git a/src/Http/Middleware/ServeShell.php b/src/Http/Middleware/ServeShell.php new file mode 100644 index 0000000..e2bd54a --- /dev/null +++ b/src/Http/Middleware/ServeShell.php @@ -0,0 +1,33 @@ +isMethodSafe() || $request->wantsJson() || $request->ajax()) { + return $next($request); + } + + $name = (string) $request->route()?->getName(); + + if (in_array($name, [Names::route('assets'), Names::route('mascot')], true) || str_ends_with($name, '.export') || str_ends_with($name, '.connect') || str_ends_with($name, '.callback')) { + return $next($request); + } + + return response()->view('manager::shell', app(Shell::class)->data($request)); + } +} diff --git a/src/Http/Middleware/SetLocale.php b/src/Http/Middleware/SetLocale.php new file mode 100644 index 0000000..e5b10ad --- /dev/null +++ b/src/Http/Middleware/SetLocale.php @@ -0,0 +1,26 @@ +user(), 'locale'); + + if (in_array($chosen, UserSetting::LOCALES, true)) { + app()->setLocale($chosen); + } + + return $next($request); + } +} diff --git a/src/Mail/LeadConfirmation.php b/src/Mail/LeadConfirmation.php new file mode 100644 index 0000000..daabf8b --- /dev/null +++ b/src/Mail/LeadConfirmation.php @@ -0,0 +1,24 @@ + $this->lead]); + } +} diff --git a/src/Mail/LeadReceived.php b/src/Mail/LeadReceived.php new file mode 100644 index 0000000..9adc7e1 --- /dev/null +++ b/src/Mail/LeadReceived.php @@ -0,0 +1,41 @@ +lead->kindLabel().' — '.$this->lead->name.($this->lead->subject ? ': '.$this->lead->subject : ''), + replyTo: $this->lead->email ? [new Address($this->lead->email, $this->lead->name)] : [], + ); + } + + public function content(): Content + { + $digits = $this->lead->phone ? Phone::international($this->lead->phone) : null; + + return new Content(view: 'manager::mail.lead-received', with: [ + 'lead' => $this->lead, + 'callLink' => $digits ? 'tel:+'.$digits : null, + 'whatsappLink' => $digits ? 'https://wa.me/'.$digits : null, + 'mailLink' => $this->lead->email ? 'mailto:'.$this->lead->email : null, + 'managerLink' => url(config('manager.path').'/leads').'?open='.$this->lead->id, + ]); + } +} diff --git a/src/ManagerServiceProvider.php b/src/ManagerServiceProvider.php new file mode 100644 index 0000000..1c07886 --- /dev/null +++ b/src/ManagerServiceProvider.php @@ -0,0 +1,168 @@ +mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager'); + + // What was set on the settings screen goes over the config before anything reads it. + Support\Settings\Store::overlay(); + + $this->app->singleton(Support\MediaUsage::class); + $this->app->singleton(Support\AuditTrail::class); + $this->app->singleton(Modules\Posts\PostLabels::class); + + $this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry( + // A config that was published before resources existed does not list their module. + array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class, Modules\Settings\SettingsModule::class, Modules\Leads\LeadsModule::class])), + $app['config']->get('manager.modules', []), + )); + } + + public function boot(ModuleRegistry $modules): void + { + $modules->validate(); + + $this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config'); + $this->loadJsonTranslationsFrom(__DIR__.'/../resources/lang'); + $this->loadViewsFrom(__DIR__.'/../resources/views', 'manager'); + $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); + + foreach ([ + 'manager.auth' => Http\Middleware\Authenticate::class, + 'manager.shell' => Http\Middleware\ServeShell::class, + 'manager.locale' => Http\Middleware\SetLocale::class, + 'manager.feature' => Http\Middleware\RequireFeature::class, + ] as $alias => $class) { + $this->claimAlias($alias, $class); + } + // @feature('services') … @endfeature: what only shows when the feature is on. + Blade::if('feature', fn (string $key) => Support\Features::on($key)); + RateLimiter::for('manager-login', fn (Request $request) => Limit::perMinute(5)->by(strtolower((string) $request->input('email')).'|'.$request->ip())); + + $this->registerIriksStorage(); + + foreach ($modules->active() as $module) { + if ($module->migrations() !== null) { + $this->loadMigrationsFrom($module->migrations()); + } + + if ($this->app->runningInConsole() && $module->commands() !== []) { + $this->commands($module->commands()); + } + + $module->boot(); + } + + if ($this->app->runningInConsole()) { + $this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class, Console\StorageCheckCommand::class, Console\MediaMoveCommand::class, Console\SettingsCommand::class, Console\UserListCommand::class, Console\UserPasswordCommand::class, Console\MediaPruneCommand::class]); + } + + $this->registerGates($modules); + $this->registerRoutes($modules); + } + + /** + * The disk `iriksit`: files at the IriksIT API. A site that wants it sets `manager.media.disk` to `iriksit` (or any disk + * of its own with `driver` => `iriksit` in config/filesystems.php) and gives the address and the account + * in `manager.media.iriksit`. The disk is added here when the site has not made one itself. + */ + private function registerIriksStorage(): void + { + Storage::extend('iriksit', function ($app, array $config) { + $adapter = new IriksStorage\Adapter(new IriksStorage\Client($config)); + + return new FilesystemAdapter(new Filesystem($adapter, $config), $adapter, $config); + }); + + if (config('filesystems.disks.iriksit') === null) { + config(['filesystems.disks.iriksit' => ['driver' => 'iriksit', ...(array) config('manager.media.iriksit', [])]]); + } + } + + /** + * One gate per permission, and no Gate::before: a package must never answer for abilities + * of the host app. A super admin passes inside hasManagerPermission, for these gates only. + */ + private function registerGates(ModuleRegistry $modules): void + { + foreach ($modules->permissionValues() as $permission) { + Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission)); + } + + Gate::define(self::MANAGE_GROUPS, fn ($user) => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin()); + } + + /** What the routes of the package say for each of its middleware aliases: always the class, never the alias. */ + private array $aliases = []; + + /** + * Offer an alias for a middleware of the package, unless the app already has one of that name for something else + * (a site that had its own manager before the package, whose alias may even be set after this provider has booted). + * The routes of the package never go through the alias, only through the class, so the site's alias keeps meaning + * the site's middleware. + */ + private function claimAlias(string $alias, string $class): void + { + $this->aliases[$alias] = $class; + + $taken = $this->app['router']->getMiddleware()[$alias] ?? null; + + if ($taken === null || $taken === $class) { + $this->app['router']->aliasMiddleware($alias, $class); + } + } + + private function registerRoutes(ModuleRegistry $modules): void + { + $screens = config('manager.ui') === 'package'; + + if ($screens) { + // Outside `auth`, but behind the bans of the modules. + Route::middleware(['web', ...$modules->middleware('before'), $this->aliases['manager.shell']]) + ->prefix(config('manager.path')) + ->name(Names::routePrefix()) + ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/guest.php')); + } + + Route::middleware([...$modules->middleware('before'), ...array_map(fn ($name) => $this->aliases[$name] ?? $name, config('manager.middleware')), $this->aliases['manager.locale'], ...($screens ? [$this->aliases['manager.shell']] : []), ...$modules->middleware('after')]) + ->prefix(config('manager.path')) + ->name(Names::routePrefix()) + ->group(function () use ($modules) { + $this->loadRoutesFrom(__DIR__.'/../routes/manager.php'); + + foreach ($modules->active() as $module) { + if ($module->routes() !== null) { + $this->loadRoutesFrom($module->routes()); + } + } + }); + + // Files for visitors: outside the manager, no prefix and none of its middleware. + foreach ($modules->active() as $module) { + if ($module->publicRoutes() !== null) { + $this->loadRoutesFrom($module->publicRoutes()); + } + } + } +} diff --git a/src/Models/AuditLog.php b/src/Models/AuditLog.php new file mode 100644 index 0000000..107e807 --- /dev/null +++ b/src/Models/AuditLog.php @@ -0,0 +1,39 @@ +|null $details + * @property Carbon $created_at + */ +class AuditLog extends Model +{ + public const LOGIN = 'login'; + + public const LOGIN_FAILED = 'login_failed'; + + public const LOGOUT = 'logout'; + + /** Something that was done in the manager. */ + public const ACTION = 'action'; + + /** A page of the manager that was opened. */ + public const VIEWED = 'viewed'; + + /** Something the account was not allowed to do. */ + public const REFUSED = 'refused'; + + public const BAN = 'ban'; + + public $timestamps = false; + + protected function casts(): array + { + return ['details' => 'array', 'created_at' => 'datetime']; + } +} diff --git a/src/Models/AuditSetting.php b/src/Models/AuditSetting.php new file mode 100644 index 0000000..fda4cb0 --- /dev/null +++ b/src/Models/AuditSetting.php @@ -0,0 +1,60 @@ + */ + protected $attributes = [ + 'auto_ban' => true, + // This many failed logins from one address ... + 'max_failures' => 10, + // ... within this many minutes ... + 'window_minutes' => 30, + // ... keep it out this long. 0: until someone lifts the ban. + 'ban_minutes' => 1440, + 'keep_days' => 90, + ]; + + protected function casts(): array + { + return [ + 'auto_ban' => 'boolean', + 'max_failures' => 'integer', + 'window_minutes' => 'integer', + 'ban_minutes' => 'integer', + 'keep_days' => 'integer', + ]; + } + + /** The longest the log may be kept (config `manager.audit.max_keep_days`): what a privacy policy promises. */ + public static function maxKeepDays(): int + { + return max(7, (int) config('manager.audit.max_keep_days', 90)); + } + + /** The rules as they are now: the saved row, or the defaults while nothing was saved. */ + public static function current(): self + { + return static::query()->find(1) ?? new self; + } + + /** + * @return array{auto_ban: bool, max_failures: int, window_minutes: int, ban_minutes: int, keep_days: int} + */ + public function rules(): array + { + return [ + 'auto_ban' => (bool) $this->auto_ban, + 'max_failures' => (int) $this->max_failures, + 'window_minutes' => (int) $this->window_minutes, + 'ban_minutes' => (int) $this->ban_minutes, + // Also for a row that was saved when more was allowed. + 'keep_days' => min(self::maxKeepDays(), (int) $this->keep_days), + ]; + } +} diff --git a/src/Models/Group.php b/src/Models/Group.php new file mode 100644 index 0000000..6c17d7f --- /dev/null +++ b/src/Models/Group.php @@ -0,0 +1,37 @@ +|null $permissions + */ +class Group extends Model +{ + protected function casts(): array + { + return ['permissions' => 'array']; + } + + public function users(): BelongsToMany + { + return $this->belongsToMany(config('manager.user_model'), Names::table('group_user'), 'group_id', 'user_id'); + } + + /** + * What the group allows, without anything that is no permission (any more), for instance + * of a module that was switched off. + * + * @return list + */ + public function allowed(): array + { + return app(ModuleRegistry::class)->complete($this->permissions ?? []); + } +} diff --git a/src/Models/IpBan.php b/src/Models/IpBan.php new file mode 100644 index 0000000..4aa51e9 --- /dev/null +++ b/src/Models/IpBan.php @@ -0,0 +1,45 @@ + 'boolean', 'whole_site' => 'boolean', 'hits' => 'integer', 'last_hit_at' => 'datetime', 'expires_at' => 'datetime', 'created_at' => 'datetime']; + } + + /** The list of bans for the whole site is kept in the cache (IpBans::wholeSite): any change makes it stale. */ + protected static function booted(): void + { + static::saved(fn () => IpBans::forgetWholeSite()); + static::deleted(fn () => IpBans::forgetWholeSite()); + } + + /** + * Bans that still keep their address out. + * + * @param Builder $query + */ + public function scopeActive(Builder $query): void + { + $query->where(fn (Builder $q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now())); + } + + public function isActive(): bool + { + return $this->expires_at === null || $this->expires_at->isFuture(); + } +} diff --git a/src/Models/IpNote.php b/src/Models/IpNote.php new file mode 100644 index 0000000..df69745 --- /dev/null +++ b/src/Models/IpNote.php @@ -0,0 +1,21 @@ + 'array', 'answers' => 'array', 'notes' => 'array', 'notify_failed' => 'boolean', + 'subject_id' => 'integer', 'opened_at' => 'datetime', 'handled_at' => 'datetime', 'notified_at' => 'datetime', + ]; + } + + /** The real requests that still wait for the owner. */ + public function scopeWaiting(Builder $query): void + { + $query->where('folder', self::INBOX)->whereNull('handled_at'); + } + + /** The real requests that were handled. */ + public function scopeHandled(Builder $query): void + { + $query->where('folder', self::INBOX)->whereNotNull('handled_at'); + } + + /** What the owner reads for the kind: a name from `manager.leads.kinds`, else the kind itself. */ + public function kindLabel(): string + { + return (string) __((string) (config('manager.leads.kinds')[$this->kind] ?? ucfirst($this->kind))); + } + + /** What it is about, in a few words: the subject the site gave, or the kind of request. */ + public function aboutLine(): string + { + return $this->subject !== null && $this->subject !== '' ? $this->subject : $this->kindLabel(); + } + + /** The text as it is compared with earlier ones: lowercase, without the spaces and marks around the words. */ + public static function hashOf(?string $message): ?string + { + $text = trim(preg_replace('/[^\p{L}\p{N}]+/u', ' ', mb_strtolower((string) $message)) ?? ''); + + // A few words ("call me") are the same for many honest people. + return mb_strlen($text) < 40 ? null : hash('sha256', $text); + } +} diff --git a/src/Models/LeadBlock.php b/src/Models/LeadBlock.php new file mode 100644 index 0000000..0a3b222 --- /dev/null +++ b/src/Models/LeadBlock.php @@ -0,0 +1,29 @@ + 'datetime']; + } +} diff --git a/src/Models/LeadTap.php b/src/Models/LeadTap.php new file mode 100644 index 0000000..38170b9 --- /dev/null +++ b/src/Models/LeadTap.php @@ -0,0 +1,18 @@ + 'integer']; + } +} diff --git a/src/Models/Media.php b/src/Models/Media.php new file mode 100644 index 0000000..7301b3b --- /dev/null +++ b/src/Models/Media.php @@ -0,0 +1,92 @@ + 'integer', 'width' => 'integer', 'height' => 'integer', 'focus_x' => 'float', 'focus_y' => 'float']; + } + + public function uploader(): BelongsTo + { + return $this->belongsTo(config('manager.user_model'), 'uploaded_by'); + } + + public function isImage(): bool + { + return str_starts_with($this->mime_type, 'image/'); + } + + /** + * The start of this file's address. It holds the id, so it stays the same when the file is + * renamed, and is what content is searched for to see where a file is used. + */ + public function urlPrefix(): string + { + return '/media-files/'.$this->id.'/'; + } + + /** + * The address visitors load the file from. It ends in /view on purpose: web servers tend to + * answer anything that ends in .jpg themselves, as a file on disk, and never ask the app. + */ + public function url(): string + { + return $this->urlPrefix().rawurlencode($this->filename).'/view'; + } + + /** + * The focus point of the image behind an address from the library, as a CSS `object-position` + * value ("30% 65%"). Null for any other address, or when no focus point was set. + */ + public static function focusFor(?string $url): ?string + { + if ($url === null || preg_match('#^/media-files/(\d+)/#', $url, $match) !== 1) { + return null; + } + + $media = static::query()->whereKey((int) $match[1])->whereNotNull('focus_x')->whereNotNull('focus_y')->first(['id', 'focus_x', 'focus_y']); + + return $media instanceof self + ? round((float) $media->focus_x * 100, 2).'% '.round((float) $media->focus_y * 100, 2).'%' + : null; + } + + /** What the manager shows. Never includes where the file is stored. */ + public function toLibraryItem(int $usageCount = 0): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'filename' => $this->filename, + 'url' => $this->url(), + 'mime_type' => $this->mime_type, + 'is_image' => $this->isImage(), + 'size' => $this->size, + 'width' => $this->width, + 'height' => $this->height, + 'alt' => $this->alt, + 'focus_x' => $this->focus_x, + 'focus_y' => $this->focus_y, + 'uploaded_by' => $this->uploader?->name, + 'created_at' => $this->created_at?->toIso8601String(), + 'usage_count' => $usageCount, + ]; + } +} diff --git a/src/Models/Model.php b/src/Models/Model.php new file mode 100644 index 0000000..617ed86 --- /dev/null +++ b/src/Models/Model.php @@ -0,0 +1,17 @@ +table ?? Names::table(parent::getTable()); + } +} diff --git a/src/Models/Page.php b/src/Models/Page.php new file mode 100644 index 0000000..d2c0ba3 --- /dev/null +++ b/src/Models/Page.php @@ -0,0 +1,51 @@ + 'array', 'is_published' => 'boolean']; + } + + /** + * The definitions of the pages: slug => ['title' => ..., 'fields' => normalized fields]. + * + * @return array>}> + */ + public static function definitions(): array + { + $out = []; + + foreach ((array) config('manager.pages.definitions', []) as $slug => $definition) { + if (is_string($slug) && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) && is_array($definition)) { + $out[$slug] = ['title' => (string) ($definition['title'] ?? ucfirst(str_replace('-', ' ', $slug))), 'simple_title' => Fields::simpleText($definition, 'title'), 'fields' => Fields::normalize((array) ($definition['fields'] ?? []))]; + } + } + + return $out; + } + + /** + * What the public site shows on a page: every defined key, stored or default. + * + * @return array + */ + public static function contentFor(string $slug): array + { + $fields = self::definitions()[$slug]['fields'] ?? []; + $page = self::query()->where('slug', $slug)->first(); + + return Fields::values($fields, is_array($page?->content) ? $page->content : []); + } +} diff --git a/src/Models/PageView.php b/src/Models/PageView.php new file mode 100644 index 0000000..8c485c4 --- /dev/null +++ b/src/Models/PageView.php @@ -0,0 +1,26 @@ + 'datetime', 'hour' => 'integer', 'seconds' => 'integer']; + } + + /** @return BelongsTo */ + public function visit(): BelongsTo + { + return $this->belongsTo(Visit::class); + } +} diff --git a/src/Models/Post.php b/src/Models/Post.php new file mode 100644 index 0000000..239fdf4 --- /dev/null +++ b/src/Models/Post.php @@ -0,0 +1,84 @@ + 'array', + 'is_featured' => 'boolean', + 'published_at' => 'datetime', + ]; + } + + /** + * Posts that are visible on the public site: published and not scheduled for later. + * + * @param Builder $query + */ + public function scopePublished(Builder $query): void + { + $query->whereNotNull('published_at')->where('published_at', '<=', now()); + } + + public function isPublished(): bool + { + return $this->published_at !== null && $this->published_at->lte(now()); + } + + /** `draft`, `scheduled` or `published`. */ + public function status(): string + { + return match (true) { + $this->published_at === null => 'draft', + $this->published_at->isFuture() => 'scheduled', + default => 'published', + }; + } + + /** A slug for $title that no other post uses yet. */ + public static function uniqueSlug(string $title, ?int $ignoreId = null): string + { + $base = Str::slug($title) ?: 'post'; + $slug = $base; + $suffix = 2; + + while (static::query()->where('slug', $slug)->when($ignoreId, fn (Builder $q) => $q->whereKeyNot($ignoreId))->exists()) { + $slug = $base.'-'.$suffix++; + } + + return $slug; + } + + public function readingMinutes(): int + { + return max(1, (int) ceil(str_word_count(strip_tags($this->body)) / 220)); + } + + /** + * The fields a post card or listing needs, for the host's public pages. + * + * @return array + */ + public function toCard(): array + { + return [ + 'title' => $this->title, + 'slug' => $this->slug, + 'excerpt' => $this->excerpt ?? Str::limit(Markdown::toPlainText($this->body), 160), + 'cover_image' => $this->cover_image, + 'cover_focus' => Media::focusFor($this->cover_image), + 'category' => $this->category, + 'tags' => $this->tags ?? [], + 'is_featured' => $this->is_featured, + 'published_at' => $this->published_at?->toIso8601String(), + 'reading_minutes' => $this->readingMinutes(), + ]; + } +} diff --git a/src/Models/PostShare.php b/src/Models/PostShare.php new file mode 100644 index 0000000..8f22b64 --- /dev/null +++ b/src/Models/PostShare.php @@ -0,0 +1,28 @@ + 'boolean', 'shared_at' => 'datetime']; + } + + /** @return BelongsTo */ + public function post(): BelongsTo + { + return $this->belongsTo(Post::class); + } +} diff --git a/src/Models/Record.php b/src/Models/Record.php new file mode 100644 index 0000000..a322098 --- /dev/null +++ b/src/Models/Record.php @@ -0,0 +1,12 @@ + 'array']; + } +} diff --git a/src/Models/Review.php b/src/Models/Review.php new file mode 100644 index 0000000..1a930fd --- /dev/null +++ b/src/Models/Review.php @@ -0,0 +1,5 @@ + 'array', 'changed' => 'array']; + } +} diff --git a/src/Models/SocialConnection.php b/src/Models/SocialConnection.php new file mode 100644 index 0000000..b172651 --- /dev/null +++ b/src/Models/SocialConnection.php @@ -0,0 +1,29 @@ + 'encrypted', + 'refresh_token' => 'encrypted', + 'expires_at' => 'datetime', + 'refresh_token_expires_at' => 'datetime', + 'details' => 'array', + ]; + } +} diff --git a/src/Models/UserSetting.php b/src/Models/UserSetting.php new file mode 100644 index 0000000..32dd5bd --- /dev/null +++ b/src/Models/UserSetting.php @@ -0,0 +1,35 @@ +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); + } + + public function getTable(): string + { + return Names::table('user_settings'); + } +} diff --git a/src/Models/Visit.php b/src/Models/Visit.php new file mode 100644 index 0000000..bdde6d7 --- /dev/null +++ b/src/Models/Visit.php @@ -0,0 +1,34 @@ + 'datetime', + 'last_seen_at' => 'datetime', + 'hour' => 'integer', + 'weekday' => 'integer', + 'page_views' => 'integer', + 'seconds' => 'integer', + ]; + } + + /** @return HasMany */ + public function pageViews(): HasMany + { + return $this->hasMany(PageView::class); + } +} diff --git a/src/Models/VisitorSalt.php b/src/Models/VisitorSalt.php new file mode 100644 index 0000000..de340f4 --- /dev/null +++ b/src/Models/VisitorSalt.php @@ -0,0 +1,52 @@ +toDateString(); + $salt = static::query()->where('day', $today)->value('salt'); + + if (is_string($salt)) { + return $salt; + } + + static::forgetOld(); + + try { + return static::query()->create(['day' => $today, 'salt' => Str::random(64)])->salt; + } catch (UniqueConstraintViolationException) { + // Another visitor arrived in the same instant and made today's key. + return static::query()->where('day', $today)->sole()->salt; + } + } + + /** Deletes every key that is not today's. Returns how many. */ + public static function forgetOld(): int + { + $deleted = static::query()->where('day', '<', now()->toDateString())->delete(); + + return is_int($deleted) ? $deleted : 0; + } +} diff --git a/src/Models/WorkCost.php b/src/Models/WorkCost.php new file mode 100644 index 0000000..a46e9df --- /dev/null +++ b/src/Models/WorkCost.php @@ -0,0 +1,32 @@ + 'datetime']; + + public function getTable(): string + { + return Names::table('work_costs'); + } +} diff --git a/src/Modules/Audit/AuditController.php b/src/Modules/Audit/AuditController.php new file mode 100644 index 0000000..a0712bd --- /dev/null +++ b/src/Modules/Audit/AuditController.php @@ -0,0 +1,336 @@ +string('show')->toString(); + + $filters = [ + 'show' => in_array($show, self::SHOW, true) ? $show : 'all', + 'user' => $request->integer('user') ?: null, + 'ip' => $request->string('ip')->trim()->toString(), + 'q' => $request->string('q')->trim()->toString(), + ]; + + $query = AuditLog::query(); + + match ($filters['show']) { + 'logins' => $query->whereIn('event', [AuditLog::LOGIN, AuditLog::LOGOUT]), + 'failed' => $query->where('event', AuditLog::LOGIN_FAILED), + 'actions' => $query->where('event', AuditLog::ACTION), + 'viewed' => $query->where('event', AuditLog::VIEWED), + 'refused' => $query->where('event', AuditLog::REFUSED), + 'bans' => $query->where(fn (Builder $q) => $q->where('event', AuditLog::BAN)->orWhere('subject_type', 'ip_ban')), + default => $query, + }; + + if ($filters['user'] !== null) { + $query->where('user_id', $filters['user']); + } + + if ($filters['ip'] !== '') { + $query->where('ip', $filters['ip']); + } + + if ($filters['q'] !== '') { + $like = '%'.addcslashes($filters['q'], '%_\\').'%'; + $query->where(fn (Builder $q) => $q->where('summary', 'like', $like)->orWhere('subject_label', 'like', $like) + ->orWhere('user_name', 'like', $like)->orWhere('email', 'like', $like)); + } + + $total = (clone $query)->count(); + $pages = max(1, (int) ceil($total / self::PER_PAGE)); + $page = min($pages, max(1, $request->integer('page', 1))); + $rows = $query->orderByDesc('id')->forPage($page, self::PER_PAGE)->get(); + + $banned = array_values(array_filter(IpBan::query()->active()->pluck('ip')->all(), fn (mixed $ip) => is_string($ip) && ! IpBans::isNeverBanned($ip))); + $posts = $this->existingPosts($rows->where('subject_type', 'post')->pluck('subject_id')->filter()->all()); + $day = now()->subDay(); + + return response()->json([ + 'entries' => $rows->map(fn (AuditLog $entry) => [ + 'id' => $entry->id, + 'at' => $entry->created_at->toIso8601String(), + 'event' => $entry->event, + 'summary' => $entry->summary, + 'subject' => $entry->subject_label === null ? null : [ + 'type' => str_replace('_', ' ', (string) $entry->subject_type), + 'label' => $entry->subject_label, + 'url' => $entry->subject_type === 'post' && in_array($entry->subject_id, $posts, true) + ? route(Names::route('posts.edit'), $entry->subject_id, false) + : null, + ], + 'details' => $entry->details ?? [], + 'user_id' => $entry->user_id, + 'who' => $entry->user_name, + 'email' => $entry->email, + 'ip' => $entry->ip, + 'browser' => $entry->user_agent === null ? null : self::browser($entry->user_agent), + 'user_agent' => $entry->user_agent, + 'banned' => $entry->ip !== null && in_array($entry->ip, $banned, true), + 'never_banned' => $entry->ip !== null && IpBans::isNeverBanned($entry->ip), + ])->values(), + 'pagination' => ['page' => $page, 'pages' => $pages, 'total' => $total], + 'filters' => $filters, + 'accounts' => $this->accounts(), + 'summary' => [ + 'logins' => AuditLog::query()->where('event', AuditLog::LOGIN)->where('created_at', '>=', $day)->count(), + 'failed' => AuditLog::query()->where('event', AuditLog::LOGIN_FAILED)->where('created_at', '>=', $day)->count(), + 'refused' => AuditLog::query()->where('event', AuditLog::REFUSED)->where('created_at', '>=', $day)->count(), + 'banned' => count($banned), + ], + 'bans' => IpBan::query()->orderByDesc('created_at')->get()->map(fn (IpBan $ban) => [ + 'id' => $ban->id, + 'ip' => $ban->ip, + 'reason' => $ban->reason, + 'automatic' => $ban->automatic, + 'whole_site' => $ban->whole_site, + 'by' => $ban->user_name, + 'hits' => $ban->hits, + 'last_hit_at' => $ban->last_hit_at?->toIso8601String(), + 'expires_at' => $ban->expires_at?->toIso8601String(), + 'created_at' => $ban->created_at->toIso8601String(), + 'active' => $ban->isActive() && ! IpBans::isNeverBanned($ban->ip), + ])->sortByDesc('active')->values(), + // What was written down about addresses, by address. Kept until removed, also after the log is gone. + 'notes' => IpNote::query()->orderByDesc('updated_at')->get()->map(fn (IpNote $note) => [ + 'ip' => $note->ip, + 'group' => $note->group_name, + 'note' => $note->note, + 'by' => $note->user_name, + 'updated_at' => $note->updated_at?->toIso8601String(), + ])->values(), + 'settings' => AuditSetting::current()->rules(), + 'max_keep_days' => AuditSetting::maxKeepDays(), + 'can_manage' => Gate::allows('audit.manage'), + 'my_ip' => $request->ip(), + // The addresses that are never banned (config manager.audit.never_ban): no button for those. + 'never_banned' => IpBans::neverBanned(), + 'whole_site_bans' => (bool) config('manager.audit.whole_site_bans'), + ]); + } + + public function ban(Request $request): JsonResponse + { + $request->validate([ + 'ip' => ['required', 'ip'], + 'reason' => ['nullable', 'string', 'max:200'], + // 0: until someone lifts it. At most a year. + 'minutes' => ['required', 'integer', 'min:0', 'max:525600'], + // Off the whole site, not only out of the manager. + 'whole_site' => ['boolean'], + ]); + + $ip = $request->string('ip')->trim()->toString(); + + // Nobody bans the address they are on: the next click would be refused. + if ($ip === $request->ip()) { + return $this->refuse('ip', 'That is the address you are on yourself.'); + } + + if (IpBans::isNeverBanned($ip)) { + return $this->refuse('ip', 'This address is on the list that is never banned.'); + } + + $wholeSite = $request->boolean('whole_site') && config('manager.audit.whole_site_bans'); + $reason = $request->string('reason')->trim()->toString(); + $ban = $this->bans->ban($ip, $reason !== '' ? $reason : null, $request->integer('minutes'), Auth::user(), wholeSite: $wholeSite); + + // Also when the address was banned before: the line of the log is filed under it either way. + if ($ban !== null) { + $this->trail->about($ban); + } + + return response()->json(['message' => $wholeSite ? __(':ip is banned from the whole site.', ['ip' => $ip]) : __(':ip is banned from the manager.', ['ip' => $ip])], 201); + } + + public function unban(int $ban): JsonResponse + { + $ipBan = IpBan::query()->findOrFail($ban); + $this->trail->about($ipBan); + $this->bans->lift($ipBan); + + return response()->json(['message' => __('The ban of :ip is lifted.', ['ip' => $ipBan->ip])]); + } + + /** Bans every address of a group at once, with the same time, reason and reach. */ + public function banGroup(Request $request): JsonResponse + { + $request->validate([ + 'group' => ['required', 'string', 'max:60'], + 'reason' => ['nullable', 'string', 'max:200'], + 'minutes' => ['required', 'integer', 'min:0', 'max:525600'], + 'whole_site' => ['boolean'], + ]); + + $group = $request->string('group')->trim()->toString(); + $reason = $request->string('reason')->trim()->toString(); + $wholeSite = $request->boolean('whole_site') && config('manager.audit.whole_site_bans'); + $banned = 0; + $skipped = 0; + + // The line of the log is about the group, not about the first address of it. + $this->trail->about(null); + + foreach ($this->addressesOf($group) as $ip) { + // The address one is on and the ones that are never banned stay in, as with a ban of one address. + $ban = $ip === $request->ip() ? null : $this->bans->ban($ip, $reason !== '' ? $reason : "Group: {$group}", $request->integer('minutes'), Auth::user(), wholeSite: $wholeSite); + $ban === null ? $skipped++ : $banned++; + } + + if ($banned === 0) { + return $this->refuse('group', $skipped === 0 + ? "The group \"{$group}\" has no addresses." + : "None of the addresses of \"{$group}\" can be banned: your own and the ones that are never banned stay in."); + } + + return response()->json(['message' => sprintf( + '%d %s of "%s" banned from %s%s.', + $banned, + $banned === 1 ? 'address' : 'addresses', + $group, + $wholeSite ? 'the whole site' : 'the manager', + $skipped > 0 ? " ({$skipped} left alone: your own or never banned)" : '', + ), 'banned' => $banned, 'skipped' => $skipped], 201); + } + + /** Lets every address of a group back in. */ + public function unbanGroup(Request $request): JsonResponse + { + $request->validate(['group' => ['required', 'string', 'max:60']]); + + $group = $request->string('group')->trim()->toString(); + $bans = IpBan::query()->whereIn('ip', $this->addressesOf($group))->get(); + $this->trail->about(null); + $bans->each(fn (IpBan $ban) => $this->bans->lift($ban)); + + return response()->json(['message' => sprintf('%d %s of "%s" lifted.', $bans->count(), $bans->count() === 1 ? 'ban' : 'bans', $group), 'lifted' => $bans->count()]); + } + + /** Writes the note about an address and the group it is in, or removes both when they are left empty. */ + public function note(Request $request): JsonResponse + { + $request->validate([ + 'ip' => ['required', 'ip'], + 'note' => ['nullable', 'string', 'max:2000'], + // Addresses with the same group are banned and let back in together. + 'group' => ['nullable', 'string', 'max:60'], + ]); + + $ip = IpNote::spell($request->string('ip')->toString()); + $text = $request->string('note')->trim()->toString(); + $group = $request->string('group')->trim()->toString(); + $note = IpNote::query()->where('ip', $ip)->first(); + + if ($text === '' && $group === '') { + if ($note !== null) { + $this->trail->about($note); + $note->delete(); + } + + return response()->json(['message' => __('The note about :ip is removed.', ['ip' => $ip])]); + } + + $note ??= new IpNote(['ip' => $ip]); + $user = Auth::user(); + $name = data_get($user, 'name'); + $note->fill(['note' => $text, 'group_name' => $group !== '' ? $group : null, 'user_id' => $user?->getAuthIdentifier(), 'user_name' => is_string($name) ? $name : null])->save(); + $this->trail->about($note); + + return response()->json(['message' => __('The note about :ip is saved.', ['ip' => $ip])]); + } + + public function settings(Request $request): JsonResponse + { + /** @var array $rules */ + $rules = $request->validate([ + 'auto_ban' => ['required', 'boolean'], + 'max_failures' => ['required', 'integer', 'min:3', 'max:100'], + 'window_minutes' => ['required', 'integer', 'min:1', 'max:1440'], + 'ban_minutes' => ['required', 'integer', 'min:0', 'max:525600'], + // What the site promises about how long the log is kept (config manager.audit.max_keep_days). + 'keep_days' => ['required', 'integer', 'min:7', 'max:'.AuditSetting::maxKeepDays()], + ]); + + AuditSetting::current()->forceFill(['id' => 1, ...$rules])->save(); + + return response()->json(['message' => __('Rules saved.'), 'settings' => AuditSetting::current()->rules()]); + } + + private function refuse(string $field, string $message): JsonResponse + { + return response()->json(['message' => $message = __($message), 'errors' => [$field => [$message]]], 422); + } + + /** + * @return list + */ + private function addressesOf(string $group): array + { + return array_values(array_filter(IpNote::query()->where('group_name', $group)->orderBy('id')->pluck('ip')->all(), is_string(...))); + } + + /** + * @param list $ids + * @return list + */ + private function existingPosts(array $ids): array + { + if ($ids === [] || ! Route::has(Names::route('posts.edit'))) { + return []; + } + + return Post::query()->whereIn('id', $ids)->pluck('id')->map(fn ($id) => (int) $id)->all(); + } + + /** @return list */ + private function accounts(): array + { + /** @var class-string $model */ + $model = config('manager.user_model'); + + return $model::query()->orderBy('name')->get()->map(fn ($user) => ['id' => $user->getKey(), 'name' => $user->name])->values()->all(); + } + + /** "Firefox on Linux": enough to recognise a browser; the whole line is there to hover. */ + private static function browser(string $line): string + { + $agent = new UserAgent($line); + + if ($agent->isBot()) { + return $agent->bot()['name'] ?? 'A program'; + } + + return $agent->browser().' on '.$agent->os(); + } +} diff --git a/src/Modules/Audit/AuditModule.php b/src/Modules/Audit/AuditModule.php new file mode 100644 index 0000000..636421e --- /dev/null +++ b/src/Modules/Audit/AuditModule.php @@ -0,0 +1,142 @@ + 'Audit log', 'route' => Names::route('audit.index'), 'permission' => 'audit.view']]; + } + + public function commands(): array + { + return [PruneAuditLog::class, LiftBan::class]; + } + + public function actions(): array + { + return [ + 'audit.bans.store' => ['Banned an address', ['reason', 'whole_site']], + 'audit.bans.destroy' => ['Lifted the ban of an address'], + 'audit.groups.ban' => ['Banned the addresses of a group', ['group', 'reason', 'whole_site']], + 'audit.groups.unban' => ['Lifted the bans of a group', ['group']], + 'audit.notes.update' => ['Wrote or removed the note about an address', ['ip', 'group']], + 'audit.settings' => ['Changed the rules of the audit log'], + ]; + } + + public function views(): array + { + return ['audit.index' => 'Opened the audit log']; + } + + /** A banned address is refused before the session starts; every request of a manager account is written down. */ + public function middleware(): array + { + return ['before' => [RefuseBannedAddress::class], 'after' => [RecordActions::class]]; + } + + public function boot(): void + { + app()->singleton(IpBans::class); + + app('router')->aliasMiddleware('manager.not-banned', RefuseBannedAddress::class); + + // The first thing a request makes is what the line of the log is about. + Event::listen('eloquent.created: *', function (string $event, array $data) { + if (($data[0] ?? null) instanceof Model) { + app(AuditTrail::class)->made($data[0]); + } + }); + + $this->listenForLogins(); + + if (config('manager.audit.whole_site_bans') && ($kernel = app(Kernel::class)) && method_exists($kernel, 'pushMiddleware')) { + $kernel->pushMiddleware(RefuseBannedFromTheSite::class); + } + + // Only the console runs the schedule; a web request never needs to resolve it. + if (app()->runningInConsole()) { + app()->afterResolving(Schedule::class, fn (Schedule $schedule) => $schedule->command(PruneAuditLog::class)->dailyAt('03:40')); + } + } + + /** The host owns the login: Laravel's own events say what happened, whatever the login looks like. */ + private function listenForLogins(): void + { + $model = config('manager.user_model'); + + Event::listen(Login::class, function (Login $event) use ($model) { + if ($event->user instanceof $model) { + app(AuditTrail::class)->record(AuditLog::LOGIN, __('Logged in'), $event->user); + } + }); + + Event::listen(Logout::class, function (Logout $event) use ($model) { + if ($event->user instanceof $model) { + app(AuditTrail::class)->record(AuditLog::LOGOUT, __('Logged out'), $event->user); + } + }); + + Event::listen(Failed::class, function (Failed $event) { + $email = $event->credentials['email'] ?? null; + $email = is_string($email) ? $email : null; + + app(AuditTrail::class)->record( + AuditLog::LOGIN_FAILED, + $event->user === null ? 'Failed login: no such account' : 'Failed login: wrong password', + $event->user, + email: $email, + ); + + app(IpBans::class)->afterFailedLogin(request()->ip()); + }); + } +} diff --git a/src/Modules/Audit/IpBans.php b/src/Modules/Audit/IpBans.php new file mode 100644 index 0000000..95e4b7d --- /dev/null +++ b/src/Modules/Audit/IpBans.php @@ -0,0 +1,189 @@ + */ + public static function neverBanned(): array + { + $addresses = config('manager.audit.never_ban'); + + return is_array($addresses) ? array_values(array_filter($addresses, is_string(...))) : []; + } + + /** Compared in packed form: an IPv6 address has more than one spelling. */ + public static function isNeverBanned(string $ip): bool + { + $packed = @inet_pton($ip); + + foreach (self::neverBanned() as $address) { + if ($address === $ip || ($packed !== false && @inet_pton($address) === $packed)) { + return true; + } + } + + return false; + } + + /** The ban that keeps this address out of the manager now, if any. */ + public function for(?string $ip): ?IpBan + { + return $ip === null || self::isNeverBanned($ip) ? null : IpBan::query()->active()->where('ip', $ip)->first(); + } + + /** + * The ban that keeps this address off the whole site now, if any. Asked at every request of + * every visitor, so the list (address => id) comes from the cache; it is thrown away whenever + * a ban is saved or deleted (see IpBan). + */ + public function wholeSite(?string $ip): ?IpBan + { + if ($ip === null || self::isNeverBanned($ip)) { + return null; + } + + $banned = Cache::get(self::WHOLE_SITE); + + if (! is_array($banned)) { + // Not kept while the table is not there yet: the answer would outlive the migration. + if (! self::ready()) { + return null; + } + + $banned = IpBan::query()->where('whole_site', true)->pluck('id', 'ip')->all(); + Cache::forever(self::WHOLE_SITE, $banned); + } + + if (! isset($banned[$ip])) { + return null; + } + + // Only now the database: whether it still counts (a ban ends by itself). + return IpBan::query()->active()->where('whole_site', true)->where('ip', $ip)->first(); + } + + public static function forgetWholeSite(): void + { + Cache::forget(self::WHOLE_SITE); + } + + private static function ready(): bool + { + try { + return Schema::hasTable((new IpBan)->getTable()); + } catch (Throwable) { + return false; + } + } + + /** + * $minutes 0: until someone lifts it. Null for an address that is never banned. + */ + public function ban(string $ip, ?string $reason, int $minutes, ?Authenticatable $by, bool $automatic = false, bool $wholeSite = false): ?IpBan + { + if (self::isNeverBanned($ip)) { + return null; + } + + $name = $by === null ? null : data_get($by, 'name'); + + return IpBan::query()->updateOrCreate(['ip' => $ip], [ + 'reason' => $reason, + 'automatic' => $automatic, + 'whole_site' => $wholeSite, + 'user_id' => $by?->getAuthIdentifier(), + 'user_name' => is_string($name) ? $name : null, + 'hits' => 0, + 'last_hit_at' => null, + 'expires_at' => $minutes > 0 ? now()->addMinutes($minutes) : null, + 'created_at' => now(), + ]); + } + + public function lift(IpBan $ban): void + { + $ban->delete(); + } + + /** A banned address knocked: only counted, so a flood does not fill the log. */ + public function knocked(IpBan $ban): void + { + IpBan::query()->whereKey($ban->id)->update(['hits' => $ban->hits + 1, 'last_hit_at' => now()]); + } + + /** + * After a failed login: bans the address when it failed too often. What counts are the + * failures since the address last logged in or was last banned or let back in, so a ban that + * was lifted does not come back at the next typo. + */ + public function afterFailedLogin(?string $ip): ?IpBan + { + $rules = AuditSetting::current()->rules(); + + if ($ip === null || ! $rules['auto_ban'] || self::isNeverBanned($ip) || $this->for($ip) !== null) { + return null; + } + + // By id and not by time: a login in the same second as the failure before it still comes after it. + $reset = AuditLog::query() + ->where(fn (Builder $query) => $query + ->where(fn (Builder $q) => $q->where('event', AuditLog::LOGIN)->where('ip', $ip)) + ->orWhere(fn (Builder $q) => $q->where('subject_type', 'ip_ban')->where('subject_label', $ip))) + ->max('id'); + + $failures = AuditLog::query() + ->where('event', AuditLog::LOGIN_FAILED) + ->where('ip', $ip) + ->where('id', '>', is_numeric($reset) ? (int) $reset : 0) + ->where('created_at', '>=', now()->subMinutes($rules['window_minutes'])) + ->count(); + + if ($failures < $rules['max_failures']) { + return null; + } + + $ban = $this->ban($ip, sprintf('%d failed logins within %d minutes', $failures, $rules['window_minutes']), $rules['ban_minutes'], null, automatic: true); + + if ($ban === null) { + return null; + } + + $this->trail->record(AuditLog::BAN, __('The address was banned after too many failed logins'), subject: $ban, details: ['failures' => $failures]); + + return $ban; + } + + /** Bans that ended before $before are deleted; returns how many. */ + public function forgetExpiredBefore(Carbon $before): int + { + $ended = IpBan::query()->whereNotNull('expires_at')->where('expires_at', '<', $before); + $count = $ended->count(); + $ended->delete(); + + return $count; + } +} diff --git a/src/Modules/Audit/LiftBan.php b/src/Modules/Audit/LiftBan.php new file mode 100644 index 0000000..01d5e2e --- /dev/null +++ b/src/Modules/Audit/LiftBan.php @@ -0,0 +1,51 @@ +argument('ip'); + + if ($this->option('all')) { + $lifted = IpBan::query()->get()->each(fn (IpBan $ban) => $bans->lift($ban))->count(); + $this->line("{$lifted} ban(s) lifted."); + + return self::SUCCESS; + } + + if (! is_string($ip)) { + $rows = IpBan::query()->orderBy('ip')->get()->map(fn (IpBan $ban) => [ + $ban->ip, + $ban->isActive() ? ($ban->expires_at?->format('Y-m-d H:i') ?? 'until lifted') : 'ended', + $ban->reason ?? '', + ])->all(); + + $rows === [] ? $this->line('No address is banned.') : $this->table(['Address', 'Until', 'Reason'], $rows); + + return self::SUCCESS; + } + + $ban = IpBan::query()->where('ip', $ip)->first(); + + if ($ban === null) { + $this->error("{$ip} is not banned."); + + return self::FAILURE; + } + + $bans->lift($ban); + $this->line("The ban of {$ip} is lifted."); + + return self::SUCCESS; + } +} diff --git a/src/Modules/Audit/PruneAuditLog.php b/src/Modules/Audit/PruneAuditLog.php new file mode 100644 index 0000000..16b2c07 --- /dev/null +++ b/src/Modules/Audit/PruneAuditLog.php @@ -0,0 +1,27 @@ +subDays(AuditSetting::current()->rules()['keep_days']); + + $old = AuditLog::query()->where('created_at', '<', $before); + $lines = $old->count(); + $old->delete(); + + $this->line(sprintf('%d line(s) of the audit log and %d ended ban(s) deleted.', $lines, $bans->forgetExpiredBefore($before))); + + return self::SUCCESS; + } +} diff --git a/src/Modules/Audit/RecordActions.php b/src/Modules/Audit/RecordActions.php new file mode 100644 index 0000000..1b75c6c --- /dev/null +++ b/src/Modules/Audit/RecordActions.php @@ -0,0 +1,150 @@ +trail->reset(); + + $response = $next($request); + + if ($user !== null) { + $this->write($request, $response, $user, $this->trail->firstMade()); + } + + return $response; + } + + private function write(Request $request, Response $response, Authenticatable $user, ?Model $subject): void + { + $route = Str::after((string) $request->route()?->getName(), Names::routePrefix()); + $actions = $this->modules->actions(); + $views = $this->modules->views(); + $thrown = property_exists($response, 'exception') && $response->exception instanceof Throwable ? $response->exception : null; + $details = $this->details($request, $actions[$route][1] ?? []); + $name = $actions[$route][0] ?? ($views[$route] ?? ''); + $name = $name !== '' ? __($name) : __('Asked for :request', ['request' => $request->method().' /'.ltrim($request->path(), '/')]); + + if (in_array($route, self::SILENT, true)) { + return; + } + + if ($thrown !== null) { + // Only a refusal is worth a line; a form with a mistake or a page that is not there is not. + if ($thrown instanceof AuthorizationException || ($thrown instanceof HttpExceptionInterface && $thrown->getStatusCode() === 403)) { + $this->trail->record(AuditLog::REFUSED, __('Was not allowed: :what', ['what' => Str::lcfirst($name)]), $user, $subject, $details, $route); + } + + return; + } + + if ($response->getStatusCode() >= 400) { + return; + } + + $changes = ! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true); + + if (! $changes && ! isset($actions[$route])) { + $this->viewed($user, $route, __($views[$route] ?? ''), $subject, $details); + + return; + } + + $this->trail->record(AuditLog::ACTION, $name, $user, $subject, $details, $route); + } + + /** + * A page that was opened. Not twice in a row: filtering a list or loading a page again within + * a few minutes is the same look. A route with an empty name stays silent (what a page asks + * for in the background). + * + * @param array $details + */ + private function viewed(Authenticatable $user, string $route, string $summary, ?Model $subject, array $details): void + { + if ($summary === '') { + return; + } + + $last = AuditLog::query()->where('user_id', $user->getAuthIdentifier())->orderByDesc('id')->first(); + $about = $subject === null ? null : AuditTrail::describe($subject); + + if ($last !== null && $last->event === AuditLog::VIEWED && $last->action === $route + && $last->subject_id === ($about['id'] ?? null) && ($last->details ?? []) === $details + && $last->created_at->gt(now()->subMinutes(self::SAME_LOOK_MINUTES))) { + return; + } + + $this->trail->record(AuditLog::VIEWED, $summary, $user, $subject, $details, $route); + } + + /** + * What the address names (`/posts/5`) and the fields of the form a module said may be kept. + * + * @param list $kept + * @return array + */ + private function details(Request $request, array $kept): array + { + $input = []; + + foreach ($request->route()?->parameters() ?? [] as $name => $parameter) { + $value = $parameter instanceof BackedEnum ? $parameter->value : $parameter; + + if (is_scalar($value) && ! is_bool($value) && $name !== 'type') { + $input[$name] = Str::limit((string) $value, 100, '…'); + } + } + + foreach ($kept as $field) { + $value = $request->input($field); + + if (is_bool($value)) { + $value = $value ? 'yes' : 'no'; + } + + if (is_string($value) && $value !== '') { + $input[$field] = Str::limit($value, 100, '…'); + } + } + + return $input === [] ? [] : ['input' => $input]; + } +} diff --git a/src/Modules/Audit/RefuseBannedAddress.php b/src/Modules/Audit/RefuseBannedAddress.php new file mode 100644 index 0000000..0418a4c --- /dev/null +++ b/src/Modules/Audit/RefuseBannedAddress.php @@ -0,0 +1,56 @@ +bans->for($request->ip()); + + if ($ban === null) { + return $next($request); + } + + $this->bans->knocked($ban); + + return self::answer($request, $ban); + } + + /** The page (or JSON) a banned address gets, also for a ban on the whole site. */ + public static function answer(Request $request, IpBan $ban): Response + { + $where = $ban->whole_site ? __('this site') : __('the manager'); + $message = $ban->expires_at === null + ? __('This address is blocked from :where.', ['where' => $where]) + : __('This address is blocked from :where until :when.', ['where' => $where, 'when' => $ban->expires_at->format('j F Y, H:i')]); + + // A ban that followed too many attempts is "429 Too Many Requests" and says when to come + // back; one that was given by hand is a plain "403 Forbidden". + $status = $ban->automatic ? 429 : 403; + $headers = ['Cache-Control' => 'no-store']; + + if ($ban->automatic && $ban->expires_at !== null) { + $headers['Retry-After'] = (string) max(1, (int) now()->diffInSeconds($ban->expires_at, false)); + } + + return $request->expectsJson() + ? response()->json(['message' => $message], $status, $headers) + : response()->view('manager::banned', ['message' => $message, 'status' => $status], $status, $headers); + } +} diff --git a/src/Modules/Audit/RefuseBannedFromTheSite.php b/src/Modules/Audit/RefuseBannedFromTheSite.php new file mode 100644 index 0000000..a3306bd --- /dev/null +++ b/src/Modules/Audit/RefuseBannedFromTheSite.php @@ -0,0 +1,33 @@ +bans->wholeSite($request->ip()); + + if ($ban === null) { + return $next($request); + } + + $this->bans->knocked($ban); + + return RefuseBannedAddress::answer($request, $ban); + } +} diff --git a/src/Modules/Audit/migrations/2026_12_04_000003_create_manager_audit_tables.php b/src/Modules/Audit/migrations/2026_12_04_000003_create_manager_audit_tables.php new file mode 100644 index 0000000..fcaf5ef --- /dev/null +++ b/src/Modules/Audit/migrations/2026_12_04_000003_create_manager_audit_tables.php @@ -0,0 +1,82 @@ +id(); + $table->string('event', 40)->index(); + // The route that was called, for an action in the manager. + $table->string('action', 100)->nullable(); + $table->string('summary'); + $table->string('subject_type', 40)->nullable(); + $table->unsignedBigInteger('subject_id')->nullable(); + $table->string('subject_label')->nullable(); + $table->json('details')->nullable(); + $table->unsignedBigInteger('user_id')->nullable()->index(); + $table->string('user_name')->nullable(); + // The address that was typed at a login that failed. + $table->string('email')->nullable(); + $table->string('ip', 45)->nullable()->index(); + $table->string('user_agent', 500)->nullable(); + $table->dateTime('created_at')->index(); + }); + + // Addresses that are kept out of the manager, or off the whole site. + Tables::create(Names::table('ip_bans'), function (Blueprint $table) { + $table->id(); + $table->string('ip', 45)->unique(); + $table->string('reason')->nullable(); + $table->boolean('automatic')->default(false); + $table->boolean('whole_site')->default(false); + $table->unsignedBigInteger('user_id')->nullable(); + $table->string('user_name')->nullable(); + // How often the address knocked while it was banned. + $table->unsignedInteger('hits')->default(0); + $table->timestamp('last_hit_at')->nullable(); + // Null: until someone lifts it. + $table->timestamp('expires_at')->nullable(); + $table->dateTime('created_at'); + }); + + // One row (id 1) with the rules; without it the defaults of the model count. + Tables::create(Names::table('audit_settings'), function (Blueprint $table) { + $table->id(); + $table->boolean('auto_ban')->default(true); + $table->unsignedSmallInteger('max_failures')->default(10); + $table->unsignedSmallInteger('window_minutes')->default(30); + $table->unsignedInteger('ban_minutes')->default(1440); + $table->unsignedSmallInteger('keep_days')->default(90); + $table->timestamps(); + }); + + Tables::create(Names::table('ip_notes'), function (Blueprint $table) { + $table->id(); + $table->string('ip', 45)->unique(); + // Addresses that belong together carry the same name here; null: no group. + $table->string('group_name', 60)->nullable()->index(); + $table->text('note'); + $table->unsignedBigInteger('user_id')->nullable(); + $table->string('user_name')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + + foreach (['ip_notes', 'audit_settings', 'ip_bans', 'audit_logs'] as $table) { + Schema::dropIfExists(Names::table($table)); + } + } +}; diff --git a/src/Modules/Audit/routes.php b/src/Modules/Audit/routes.php new file mode 100644 index 0000000..1968f67 --- /dev/null +++ b/src/Modules/Audit/routes.php @@ -0,0 +1,15 @@ +name('audit.index')->middleware('can:audit.view'); + +Route::middleware('can:audit.manage')->group(function () { + Route::post('/audit/bans', [AuditController::class, 'ban'])->name('audit.bans.store'); + Route::delete('/audit/bans/{ban}', [AuditController::class, 'unban'])->name('audit.bans.destroy')->whereNumber('ban'); + Route::post('/audit/groups/ban', [AuditController::class, 'banGroup'])->name('audit.groups.ban'); + Route::post('/audit/groups/unban', [AuditController::class, 'unbanGroup'])->name('audit.groups.unban'); + Route::put('/audit/notes', [AuditController::class, 'note'])->name('audit.notes.update'); + Route::put('/audit/settings', [AuditController::class, 'settings'])->name('audit.settings'); +}); diff --git a/src/Modules/BaseModule.php b/src/Modules/BaseModule.php new file mode 100644 index 0000000..2228c74 --- /dev/null +++ b/src/Modules/BaseModule.php @@ -0,0 +1,98 @@ +path('routes.php'); + } + + public function publicRoutes(): ?string + { + return $this->path('public-routes.php'); + } + + public function commands(): array + { + return []; + } + + /** + * Tables (without the prefix) this module needs; `manager:doctor` checks that they exist. + * + * @return list + */ + public function tables(): array + { + 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 + */ + public function tutorial(): array + { + return []; + } + + public function actions(): array + { + return []; + } + + public function views(): array + { + return []; + } + + public function middleware(): array + { + return []; + } + + public function boot(): void {} + + public function migrations(): ?string + { + return $this->path('migrations'); + } + + private function path(string $name): ?string + { + $path = dirname((new \ReflectionClass($this))->getFileName()).'/'.$name; + + return file_exists($path) ? $path : null; + } +} diff --git a/src/Modules/Costs/CostsController.php b/src/Modules/Costs/CostsController.php new file mode 100644 index 0000000..3bba0f9 --- /dev/null +++ b/src/Modules/Costs/CostsController.php @@ -0,0 +1,93 @@ +items(); + $dates = []; + + foreach (Changelog::releases(limit: 200) as $release) { + $dates[$release['version']] = $release['date']; + } + + // A group per release, newest first as in the changelog, and before them the work that has no release yet. A row without a + // version belongs to the newest release when the site says so (on the live site everything that is deployed is released, and + // the row only has no version because the file is filled in afterwards). + $groups = []; + + foreach ($dates as $version => $date) { + $groups[$version] = ['version' => $version, 'date' => $date, 'items' => []]; + } + + $newest = config('manager.costs.assign_open_to_newest') ? array_key_first($groups) : null; + $open = ['version' => null, 'date' => null, 'items' => []]; + + foreach ($items as $item) { + if ($item['version'] === null && $newest !== null) { + $groups[$newest]['items'][] = $item; + } elseif ($item['version'] === null) { + $open['items'][] = $item; + } else { + // A row can name a release the changelog does not have (yet): it still gets its group. + $groups[$item['version']] ??= ['version' => $item['version'], 'date' => null, 'items' => []]; + $groups[$item['version']]['items'][] = $item; + } + } + + $all = array_values(array_filter([...($open['items'] !== [] ? [$open] : []), ...array_values($groups)], fn (array $group) => $group['items'] !== [])); + + $sum = fn (array $rows, string $key): float => (float) array_sum(array_map(fn (array $item) => $item[$key] ?? 0.0, $rows)); + $hosting = $ledger->hosting(); + $discount = $ledger->discount(); + $discounted = round(array_sum(array_map(fn (array $item) => $ledger->discountOn($item), $items)), 2); + $work = round($sum($items, 'work_eur'), 2); + $ai = round($sum($items, 'eur'), 2); + + return response()->json([ + 'groups' => array_map(fn (array $group) => $group + [ + 'eur' => round($sum($group['items'], 'eur'), 2), + 'tokens' => (int) $sum($group['items'], 'tokens'), + 'hours' => round($sum($group['items'], 'hours'), 2), + 'work_eur' => round($sum($group['items'], 'work_eur'), 2), + ], $all), + // Three costs, kept apart: the work (hours at the hourly rate), what the AI model cost in tokens, and hosting. + 'costs' => [ + 'hourly_rate' => $ledger->hourlyRate(), + 'hours' => round($sum($items, 'hours'), 2), + 'work_eur' => $work, + 'ai_eur' => $ai, + 'hosting' => $hosting, + 'total_eur' => round($work + $ai + $hosting['eur'], 2), + 'discount' => $discount !== null ? $discount + ['eur' => $discounted] : null, + // Never a cent below zero through rounding, and never "-0". + 'due_eur' => max(0.0, round($work + $ai + $hosting['eur'] - $discounted, 2)) + 0.0, + 'without_hours' => count(array_filter($items, fn (array $item) => $item['hours'] === null)), + ], + 'totals' => [ + 'tokens' => (int) $sum($items, 'tokens'), + 'steps' => (int) $sum($items, 'steps'), + 'unpriced' => count(array_filter($items, fn (array $item) => $item['eur'] === null)), + ], + // Where the amounts come from: a price source that was asked once and kept, the fixed rates of the config, or both. + 'source' => self::source($items), + ]); + } + + /** @param list $items */ + private static function source(array $items): string + { + $by = array_values(array_unique(array_filter(array_column($items, 'priced_by')))); + + return match (true) { + $by === ['service'] => 'service', + in_array('service', $by, true) => 'mixed', + default => 'config', + }; + } +} diff --git a/src/Modules/Costs/CostsModule.php b/src/Modules/Costs/CostsModule.php new file mode 100644 index 0000000..35690ce --- /dev/null +++ b/src/Modules/Costs/CostsModule.php @@ -0,0 +1,55 @@ + 'What it cost', 'route' => Names::route('costs.index'), 'permission' => 'costs.view', 'simple' => true, 'hint' => 'What was built, and what it cost']]; + } + + public function commands(): array + { + return [CostsPriceCommand::class]; + } + + public function views(): array + { + return ['costs.index' => 'Opened the costs']; + } +} diff --git a/src/Modules/Costs/migrations/2026_12_12_000001_create_manager_work_costs.php b/src/Modules/Costs/migrations/2026_12_12_000001_create_manager_work_costs.php new file mode 100644 index 0000000..ec53f29 --- /dev/null +++ b/src/Modules/Costs/migrations/2026_12_12_000001_create_manager_work_costs.php @@ -0,0 +1,33 @@ +id(); + // What makes a row the row it is: the day, the model and the tokens (see Support\Costs\Ledger). + $table->string('fingerprint', 64)->unique(); + $table->string('date', 10); + $table->string('name'); + $table->string('version', 40)->nullable(); + $table->string('model', 80); + $table->decimal('usd', 12, 4); + $table->decimal('eur', 12, 2); + $table->decimal('usd_per_eur', 10, 4); + $table->dateTime('priced_at'); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('work_costs')); + } +}; diff --git a/src/Modules/Costs/routes.php b/src/Modules/Costs/routes.php new file mode 100644 index 0000000..7a40f62 --- /dev/null +++ b/src/Modules/Costs/routes.php @@ -0,0 +1,6 @@ +name('costs.index')->middleware('can:costs.view'); diff --git a/src/Modules/Leads/LeadFormController.php b/src/Modules/Leads/LeadFormController.php new file mode 100644 index 0000000..e0b3fe9 --- /dev/null +++ b/src/Modules/Leads/LeadFormController.php @@ -0,0 +1,164 @@ +filled($honeypot)) { + return $this->thanks($request); + } + + $attributes = $this->validated($request, (array) ($definition['require'] ?? ['name'])); + + // After the fields are right, so the visitor fixes those first: a token works once. + if (config('manager.leads.form.turnstile', true) && Turnstile::configured() && ! Turnstile::passes($request->string('turnstile')->limit(2048, '')->toString(), (string) $request->ip())) { + throw ValidationException::withMessages(['turnstile' => __('Prove you are not a program, then send it again.')]); + } + + $intake->take( + [...$attributes, 'kind' => $kind, 'about' => $kind !== 'callback' && $request->string('about')->toString() === 'other' ? 'other' : 'job', 'page' => $this->pageOf($request), 'answers' => $this->answers($request, $kind)], + Intake::secondsOpen($request->string('form_token')->toString()), + (string) $request->ip(), + (string) $request->userAgent(), + ); + + return $this->thanks($request); + } + + /** A tap on the phone number or the WhatsApp button, counted for the page it was on. */ + public function tap(Request $request): JsonResponse + { + $data = $request->validate(['kind' => ['required', 'in:call,whatsapp'], 'path' => ['required', 'string', 'max:255']]); + Report::tap($data['kind'], parse_url($data['path'], PHP_URL_PATH) ?: '/'); + + return response()->json(['ok' => true], 201); + } + + /** A signed moment for a form that is built by script: sent back with the form, it tells how long the form was open. */ + public function token(): JsonResponse + { + return response()->json(['token' => Intake::formToken()])->header('Cache-Control', 'no-store'); + } + + private function thanks(Request $request): JsonResponse|RedirectResponse + { + if ($request->expectsJson()) { + return response()->json(['ok' => true], 201); + } + + $to = config('manager.leads.form.thanks'); + + return ($to ? redirect($to) : back())->with('manager_lead_sent', true); + } + + /** + * @param list $require `name`, `phone`, `email`, `contact` (one box: with an @ a mail address, else a phone number), `message`, `location`, `subject` + * @return array + */ + private function validated(Request $request, array $require): array + { + $needs = fn (string $field) => in_array($field, $require, true) ? ['required'] : ['nullable']; + + $request->validate([ + 'name' => ['required', 'string', 'max:120'], + 'contact' => [...$needs('contact'), 'string', 'max:255'], + 'phone' => [...$needs('phone'), 'string', 'max:40'], + 'email' => [...$needs('email'), 'email', 'max:255'], + 'message' => [...$needs('message'), 'string', 'max:5000'], + 'location' => [...$needs('location'), 'string', 'max:120'], + 'about' => ['nullable', 'in:job,other'], + 'prefers' => ['nullable', 'in:phone,whatsapp,email'], + 'subject' => [...$needs('subject'), 'string', 'max:255'], + 'subject_id' => ['nullable', 'integer'], + ]); + + $phone = $request->string('phone')->trim()->toString(); + $email = $request->string('email')->trim()->toString(); + $contact = $request->string('contact')->trim()->toString(); + + if ($contact !== '') { + if (str_contains($contact, '@')) { + filter_var($contact, FILTER_VALIDATE_EMAIL) !== false || throw ValidationException::withMessages(['contact' => __('This does not look like a mail address.')]); + $email = $contact; + } else { + $phone = $contact; + } + } + + if ($phone !== '' && Phone::international($phone) === null) { + throw ValidationException::withMessages([$contact !== '' ? 'contact' : 'phone' => __('This does not look like a phone number.')]); + } + + if ($phone === '' && $email === '') { + throw ValidationException::withMessages([in_array('contact', $require, true) ? 'contact' : 'phone' => __('Give a phone number or a mail address, so we can answer.')]); + } + + return [ + 'name' => $request->string('name')->trim()->toString(), + 'phone' => $phone !== '' ? $phone : null, + 'email' => $email !== '' ? $email : null, + 'prefers' => $request->filled('prefers') ? $request->string('prefers')->toString() : null, + 'message' => $request->filled('message') ? $request->string('message')->trim()->toString() : null, + 'location' => $request->filled('location') ? $request->string('location')->trim()->toString() : null, + 'subject' => $request->filled('subject') ? $request->string('subject')->trim()->toString() : null, + 'subject_id' => $request->filled('subject_id') ? $request->integer('subject_id') : null, + ]; + } + + /** + * What was tapped: only the questions and the moments the site itself offers. + * + * @return array + */ + private function answers(Request $request, string $kind): array + { + $answers = []; + $moment = $request->string('moment')->toString(); + $moments = (array) config('manager.leads.form.moments', []); + + if ($kind === 'callback' && in_array($moment, $moments, true)) { + $answers[__('When suits you?')] = $moment; + } + + foreach ((array) config('manager.leads.form.questions', []) as $key => $question) { + $answer = $request->string("answers.{$key}")->toString(); + + if ($answer !== '' && in_array($answer, (array) ($question['options'] ?? []), true)) { + $answers[(string) ($question['label'] ?? $key)] = $answer; + } + } + + return $answers; + } + + /** The page the form was on, as a path of this site. */ + private function pageOf(Request $request): ?string + { + $path = parse_url((string) $request->headers->get('referer'), PHP_URL_PATH); + + return is_string($path) && $path !== '' ? mb_substr($path, 0, 300) : null; + } +} diff --git a/src/Modules/Leads/LeadsController.php b/src/Modules/Leads/LeadsController.php new file mode 100644 index 0000000..abbf68a --- /dev/null +++ b/src/Modules/Leads/LeadsController.php @@ -0,0 +1,209 @@ +string('view')->toString(); + $view = in_array($view, $manages ? [...self::VIEWS, Lead::OTHER, Lead::SPAM] : self::VIEWS, true) ? $view : 'waiting'; + + $query = Lead::query()->latest('id'); + match ($view) { + 'waiting' => $query->waiting(), + 'handled' => $query->handled(), + default => $query->where('folder', $view), + }; + + return response()->json([ + 'view' => $view, + 'items' => $query->limit(200)->get()->map(fn (Lead $lead) => $this->present($lead, $manages))->values(), + 'counts' => [ + 'waiting' => Lead::query()->waiting()->count(), + 'handled' => Lead::query()->handled()->count(), + // How much was kept away; the folders themselves are only for who manages. + 'other' => Lead::query()->where('folder', Lead::OTHER)->count(), + 'spam' => Lead::query()->where('folder', Lead::SPAM)->count(), + ], + 'open' => $request->integer('open') ?: null, + 'blocks' => $manages ? LeadBlock::query()->latest('id')->get()->map(fn (LeadBlock $block) => [ + 'id' => $block->id, 'type' => $block->type, 'value' => $block->value, 'reason' => $block->reason, 'expires_at' => $block->expires_at?->toIso8601String(), + ])->values() : null, + // What the forms and the contact buttons brought in, the last 90 days. + 'report' => $manages ? $report->over(90) : null, + 'can' => ['handle' => Gate::allows('leads.handle'), 'manage' => $manages, 'delete' => Gate::allows('leads.delete')], + ]); + } + + /** The first time a request is opened: it is no longer new. */ + public function opened(int $lead): JsonResponse + { + $lead = Lead::findOrFail($lead); + $lead->opened_at ??= now(); + $lead->save(); + + return response()->json(['ok' => true]); + } + + /** "Handled", and back; with whether it became a job, when that is said. */ + public function handled(Request $request, int $lead): JsonResponse + { + $lead = Lead::findOrFail($lead); + $request->validate(['handled' => ['required', 'boolean'], 'outcome' => ['nullable', Rule::in([Lead::WON, Lead::LOST])]]); + + $handled = $request->boolean('handled'); + + $lead->update([ + 'handled_at' => $handled ? ($lead->handled_at ?? now()) : null, + 'outcome' => $handled && $request->filled('outcome') ? $request->string('outcome')->toString() : ($handled ? $lead->outcome : null), + 'opened_at' => $lead->opened_at ?? now(), + ]); + + return response()->json($this->present($lead->refresh(), Gate::allows('leads.manage'))); + } + + /** A note of the owner to themselves. */ + public function note(Request $request, int $lead): JsonResponse + { + $lead = Lead::findOrFail($lead); + $request->validate(['text' => ['required', 'string', 'max:2000']]); + + $lead->update(['notes' => [ + ...($lead->notes ?? []), + ['at' => now()->format('Y-m-d H:i:s'), 'by' => Auth::user()?->name, 'text' => $request->string('text')->trim()->toString()], + ]]); + + return response()->json($this->present($lead->refresh(), Gate::allows('leads.manage')), 201); + } + + /** Moves a request to another folder: the screening made the wrong call, or let something through. */ + public function folder(Request $request, Intake $intake, int $lead): JsonResponse + { + $lead = Lead::findOrFail($lead); + $request->validate(['folder' => ['required', Rule::in(Lead::FOLDERS)]]); + + $folder = $request->string('folder')->toString(); + $was = $lead->folder; + + $lead->update(['folder' => $folder, 'reasons' => [...($lead->reasons ?? []), 'Moved by hand from '.$was.' to '.$folder]]); + + // A real request after all: the owner hears about it like about any new one. + if ($folder === Lead::INBOX && $was !== Lead::INBOX && $lead->notified_at === null) { + $intake->tellTheOwner($lead); + } + + return response()->json($this->present($lead->refresh(), true)); + } + + /** Keeps a sender out: what they send from now on goes to the spam folder. */ + public function block(Request $request, int $lead): JsonResponse + { + $lead = Lead::findOrFail($lead); + $request->validate([ + 'type' => ['required', Rule::in(LeadBlock::TYPES)], + 'days' => ['nullable', 'integer', 'min:1', 'max:3650'], + 'reason' => ['nullable', 'string', 'max:255'], + ]); + + $type = $request->string('type')->toString(); + $email = mb_strtolower((string) $lead->email); + + $value = match ($type) { + LeadBlock::EMAIL => $email, + LeadBlock::DOMAIN => substr((string) strrchr($email, '@'), 1), + LeadBlock::PHONE => (string) Phone::international((string) $lead->phone), + default => (string) $lead->ip, + }; + + if ($value === '') { + return response()->json(['message' => __('This request has nothing of that kind to block.')], 422); + } + + // Half the country mails from these: blocking one would keep customers out. + if ($type === LeadBlock::DOMAIN && in_array($value, LeadBlock::SHARED_DOMAINS, true)) { + return response()->json(['message' => __('Everyone uses :domain: block the mail address instead of the whole domain.', ['domain' => $value])], 422); + } + + $block = LeadBlock::query()->updateOrCreate(['type' => $type, 'value' => $value], [ + 'reason' => $request->filled('reason') ? $request->string('reason')->toString() : null, + 'expires_at' => $request->filled('days') ? now()->addDays($request->integer('days')) : null, + 'user_id' => Auth::id(), + 'user_name' => Auth::user()?->name, + ]); + + return response()->json(['id' => $block->id, 'type' => $type, 'value' => $value], 201); + } + + public function unblock(int $block): JsonResponse + { + LeadBlock::findOrFail($block)->delete(); + + return response()->json(['ok' => true]); + } + + public function destroy(int $lead): JsonResponse + { + Lead::findOrFail($lead)->delete(); + + return response()->json(['ok' => true]); + } + + /** + * A request as the screen shows it. The reasons of the screening, the address it came from and where the visit came from are + * only for whoever manages the requests. + * + * @return array + */ + private function present(Lead $lead, bool $manages): array + { + $digits = $lead->phone ? Phone::international($lead->phone) : null; + + return [ + 'id' => $lead->id, + 'kind' => $lead->kindLabel(), + 'subject' => $lead->aboutLine(), + 'name' => $lead->name, + 'phone' => $lead->phone, + 'email' => $lead->email, + 'prefers' => $lead->prefers, + 'message' => $lead->message, + 'answers' => $lead->answers ?? [], + 'location' => $lead->location, + 'page' => $lead->page, + 'call_link' => $digits ? 'tel:+'.$digits : null, + 'whatsapp_link' => $digits ? 'https://wa.me/'.$digits : null, + 'mail_link' => $lead->email ? 'mailto:'.$lead->email : null, + 'is_new' => $lead->opened_at === null, + 'handled' => $lead->handled_at !== null, + 'outcome' => $lead->outcome, + 'notes' => $lead->notes ?? [], + 'created_at' => $lead->created_at?->toIso8601String(), + 'notify_failed' => $lead->notify_failed, + ...($manages ? [ + 'folder' => $lead->folder, + 'reasons' => $lead->reasons ?? [], + 'source' => trim(($lead->channel ?? '').($lead->source ? ': '.$lead->source : '')) ?: null, + 'ip' => $lead->ip, + ] : []), + ]; + } +} diff --git a/src/Modules/Leads/LeadsModule.php b/src/Modules/Leads/LeadsModule.php new file mode 100644 index 0000000..8b126d2 --- /dev/null +++ b/src/Modules/Leads/LeadsModule.php @@ -0,0 +1,92 @@ + 'Requests', 'route' => Names::route('leads.index'), 'permission' => 'leads.view', 'simple' => true, 'hint' => 'The messages and requests from your website']]; + } + + /** @return array> what the settings screen can change */ + public function settings(): array + { + return [ + 'manager.leads.notify' => ['label' => 'Mail new requests to', 'type' => 'text', 'group' => 'Requests', 'sensitive' => true, 'help' => 'The mail address that is told about every real request', 'env' => 'MANAGER_LEADS_NOTIFY'], + 'manager.leads.confirm' => ['label' => 'Mail the visitor a confirmation', 'type' => 'toggle', 'group' => 'Requests'], + 'manager.leads.keep_days' => ['label' => 'Days a request is kept', 'type' => 'number', 'group' => 'Requests'], + 'manager.leads.keep_spam_days' => ['label' => 'Days spam is kept', 'type' => 'number', 'group' => 'Requests'], + ]; + } + + public function boot(): void + { + // A form may be sent so many times an hour per address, and by everyone together. Over the limit the visitor is told to wait. + RateLimiter::for('manager-leads', fn (Request $request) => [ + Limit::perHour(max(1, (int) config('manager.leads.form.per_hour', 6)))->by('lead|'.$request->ip()), + Limit::perHour(max(1, (int) config('manager.leads.form.per_hour_all', 120)))->by('lead-all'), + ]); + RateLimiter::for('manager-leads-token', fn (Request $request) => Limit::perMinute(60)->by((string) $request->ip())); + } + + public function commands(): array + { + return [LeadsPruneCommand::class]; + } + + public function actions(): array + { + return [ + 'leads.handled' => ['Marked a request as handled or open'], + 'leads.note' => ['Added a note to a request'], + 'leads.folder' => ['Moved a request to another folder'], + 'leads.block' => ['Blocked a sender'], + 'leads.unblock' => ['Lifted the block of a sender'], + 'leads.destroy' => ['Deleted a request'], + ]; + } + + public function views(): array + { + return ['leads.index' => 'Opened the requests', 'leads.opened' => 'Opened a request']; + } +} diff --git a/src/Modules/Leads/migrations/2026_12_10_000001_create_manager_leads.php b/src/Modules/Leads/migrations/2026_12_10_000001_create_manager_leads.php new file mode 100644 index 0000000..1830181 --- /dev/null +++ b/src/Modules/Leads/migrations/2026_12_10_000001_create_manager_leads.php @@ -0,0 +1,74 @@ +id(); + $table->string('kind', 20)->index(); + // inbox (a real request), other (acquisition, something else) or spam. Set by the screening. + $table->string('folder', 20)->default('inbox')->index(); + // Why it is in that folder, for who looks after the screening. + $table->json('reasons')->nullable(); + $table->string('name'); + $table->string('phone', 40)->nullable(); + $table->string('email')->nullable(); + // How the visitor wants to be reached: phone, whatsapp or email. + $table->string('prefers', 20)->nullable(); + // What the visitor ticked: a job, or something else. + $table->string('about', 20)->default('job'); + $table->text('message')->nullable(); + // To see that the same text was sent before. + $table->string('message_hash', 64)->nullable()->index(); + // What was tapped in the steps of a form, and when a callback suits. + $table->json('answers')->nullable(); + $table->string('location', 120)->nullable(); + // What the request is about, as the site names it (a service, a product): a label and the id it points to. + $table->string('subject', 255)->nullable(); + $table->unsignedBigInteger('subject_id')->nullable(); + // The page the form was on, and where the visit came from. + $table->string('page', 300)->nullable(); + $table->string('channel', 20)->nullable(); + $table->string('source', 80)->nullable(); + // The address it was sent from, to be able to block a sender. Goes with the request. + $table->string('ip', 45)->nullable(); + $table->dateTime('opened_at')->nullable(); + $table->dateTime('handled_at')->nullable(); + // won or lost, when that was said. + $table->string('outcome', 20)->nullable(); + // Notes of the owner: a list of {at, by, text}. + $table->json('notes')->nullable(); + $table->dateTime('notified_at')->nullable(); + $table->boolean('notify_failed')->default(false); + $table->timestamps(); + }); + + // A sender that is kept out: what they send goes to the spam folder. + Tables::create(Names::table('lead_blocks'), function (Blueprint $table) { + $table->id(); + // email, domain, phone or ip. + $table->string('type', 20); + $table->string('value'); + $table->string('reason')->nullable(); + $table->dateTime('expires_at')->nullable(); + $table->unsignedBigInteger('user_id')->nullable(); + $table->string('user_name')->nullable(); + $table->timestamps(); + $table->unique(['type', 'value']); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('lead_blocks')); + Schema::dropIfExists(Names::table('leads')); + } +}; diff --git a/src/Modules/Leads/migrations/2026_12_10_000002_create_manager_lead_taps.php b/src/Modules/Leads/migrations/2026_12_10_000002_create_manager_lead_taps.php new file mode 100644 index 0000000..4962b83 --- /dev/null +++ b/src/Modules/Leads/migrations/2026_12_10_000002_create_manager_lead_taps.php @@ -0,0 +1,28 @@ +id(); + $table->string('day', 10); + // call or whatsapp. + $table->string('kind', 20); + $table->string('path', 255); + $table->unsignedInteger('taps')->default(0); + $table->unique(['day', 'kind', 'path']); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('lead_taps')); + } +}; diff --git a/src/Modules/Leads/migrations/2026_12_11_000001_add_subject_to_manager_leads.php b/src/Modules/Leads/migrations/2026_12_11_000001_add_subject_to_manager_leads.php new file mode 100644 index 0000000..5e3c825 --- /dev/null +++ b/src/Modules/Leads/migrations/2026_12_11_000001_add_subject_to_manager_leads.php @@ -0,0 +1,39 @@ + $blueprint->string('subject', 255)->nullable()); + Tables::addColumn($table, 'subject_id', fn (Blueprint $blueprint) => $blueprint->unsignedBigInteger('subject_id')->nullable()); + + if (! $hadSubjectId && Schema::hasColumn($table, 'service_id')) { + DB::table($table)->whereNotNull('service_id')->update(['subject_id' => DB::raw('service_id')]); + } + } + + public function down(): void + { + // The columns may have been there before the package: nothing to take away. + } +}; diff --git a/src/Modules/Leads/public-routes.php b/src/Modules/Leads/public-routes.php new file mode 100644 index 0000000..86465cc --- /dev/null +++ b/src/Modules/Leads/public-routes.php @@ -0,0 +1,13 @@ +middleware('throttle:manager-leads-token')->name(Names::route('leads.token')); +Route::post($path.'/tap', [LeadFormController::class, 'tap'])->middleware('throttle:manager-leads-token')->name(Names::route('leads.tap')); +Route::post($path.'/{form}', [LeadFormController::class, 'store'])->where('form', '[a-z0-9_-]+')->middleware(['web', 'throttle:manager-leads'])->name(Names::route('leads.store')); diff --git a/src/Modules/Leads/routes.php b/src/Modules/Leads/routes.php new file mode 100644 index 0000000..b59e467 --- /dev/null +++ b/src/Modules/Leads/routes.php @@ -0,0 +1,15 @@ +where(['lead' => '[0-9]+', 'block' => '[0-9]+'])->group(function () { + Route::get('/', [LeadsController::class, 'index'])->name('leads.index')->middleware('can:leads.view'); + Route::post('/{lead}/opened', [LeadsController::class, 'opened'])->name('leads.opened')->middleware('can:leads.view'); + Route::put('/{lead}/handled', [LeadsController::class, 'handled'])->name('leads.handled')->middleware('can:leads.handle'); + Route::post('/{lead}/notes', [LeadsController::class, 'note'])->name('leads.note')->middleware('can:leads.handle'); + Route::put('/{lead}/folder', [LeadsController::class, 'folder'])->name('leads.folder')->middleware('can:leads.manage'); + Route::post('/{lead}/block', [LeadsController::class, 'block'])->name('leads.block')->middleware('can:leads.manage'); + Route::delete('/blocks/{block}', [LeadsController::class, 'unblock'])->name('leads.unblock')->middleware('can:leads.manage'); + Route::delete('/{lead}', [LeadsController::class, 'destroy'])->name('leads.destroy')->middleware('can:leads.delete'); +}); diff --git a/src/Modules/Media/MediaController.php b/src/Modules/Media/MediaController.php new file mode 100644 index 0000000..2e00a43 --- /dev/null +++ b/src/Modules/Media/MediaController.php @@ -0,0 +1,152 @@ +json($this->limits()); + } + + public function items(): JsonResponse + { + $media = Media::query()->with('uploader')->latest()->latest('id')->get(); + $usage = $this->library->usageCounts($media); + + return response()->json([ + 'items' => $media->map(fn (Media $item) => $item->toLibraryItem($usage[$item->id] ?? 0))->values(), + ...$this->limits(), + ]); + } + + public function store(Request $request): JsonResponse + { + $request->validate([ + 'file' => ['required', 'file', 'mimes:'.implode(',', $this->extensions()), 'max:'.($this->maxMegabytes() * 1024)], + ...$this->focusRules(), + ]); + + $file = $request->file('file'); + abort_unless($file instanceof UploadedFile, 422); + + $room = $this->library->room(); + + if ($file->getSize() > $room['left']) { + $message = __('The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.'); + + return response()->json(['message' => $message, 'errors' => ['file' => [$message]], 'storage' => $room], 422); + } + + try { + $media = $this->library->store($file, $request->user()); + } catch (MediaStorageException $e) { + return $this->unavailable($e); + } + + if ($media->isImage()) { + $media->update($this->focus($request)); + } + + return response()->json(['item' => $media->load('uploader')->toLibraryItem(), 'storage' => $this->library->room()], 201); + } + + public function update(Request $request, string $media): JsonResponse + { + $media = Media::query()->findOrFail($media); + app(AuditTrail::class)->about($media); + + $request->validate([ + 'name' => ['required', 'string', 'max:250'], + 'alt' => ['nullable', 'string', 'max:500'], + ...$this->focusRules(), + ]); + + $alt = $request->string('alt')->trim()->toString(); + + $media->update([ + 'name' => $request->string('name')->trim()->toString(), + 'alt' => $alt !== '' ? $alt : null, + // Only when the request says something about it; renaming keeps the focus point. + ...($media->isImage() && $request->has('focus_x') ? $this->focus($request) : []), + ]); + + $usage = $this->library->usageCounts([$media]); + + return response()->json(['item' => $media->load('uploader')->toLibraryItem($usage[$media->id] ?? 0)]); + } + + public function destroy(string $media): JsonResponse + { + $media = Media::query()->findOrFail($media); + app(AuditTrail::class)->about($media); + + try { + $this->library->delete($media); + } catch (MediaStorageException $e) { + return $this->unavailable($e); + } + + return response()->json(['deleted' => true, 'storage' => $this->library->room()]); + } + + /** @return array> */ + private function focusRules(): array + { + return [ + 'focus_x' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_y'], + 'focus_y' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_x'], + ]; + } + + /** @return array{focus_x: float|null, focus_y: float|null} both null when none was sent */ + private function focus(Request $request): array + { + $x = $request->input('focus_x'); + $y = $request->input('focus_y'); + $set = is_numeric($x) && is_numeric($y); + + return ['focus_x' => $set ? round((float) $x, 4) : null, 'focus_y' => $set ? round((float) $y, 4) : null]; + } + + /** The reason goes to the log; the browser only hears that it did not work. */ + private function unavailable(MediaStorageException $e): JsonResponse + { + Log::warning('Media storage failed.', ['error' => $e->getMessage(), 'status' => $e->status]); + + return response()->json(['message' => __(self::UNAVAILABLE)], 502); + } + + /** @return array{max_file_mb: int, extensions: list, storage: array{used: int, limit: int, left: int}} */ + private function limits(): array + { + return ['max_file_mb' => $this->maxMegabytes(), 'extensions' => $this->extensions(), 'storage' => $this->library->room()]; + } + + private function maxMegabytes(): int + { + return max(1, config()->integer('manager.media.max_file_mb')); + } + + /** @return list */ + private function extensions(): array + { + return array_values(array_filter(config()->array('manager.media.extensions'), 'is_string')); + } +} diff --git a/src/Modules/Media/MediaFileController.php b/src/Modules/Media/MediaFileController.php new file mode 100644 index 0000000..1311fcd --- /dev/null +++ b/src/Modules/Media/MediaFileController.php @@ -0,0 +1,156 @@ +findOrFail((int) $media); + + $headers = $this->headers($media); + + // A media id never gets other content, so what the browser has is still right. + if (in_array($headers['ETag'], $request->getETags(), true)) { + return response('', 304, $headers); + } + + $range = $this->range($request, $media->size); + + if ($range === null) { + return response('', 416, ['Content-Range' => "bytes */{$media->size}"] + $headers); + } + + [$start, $end, $partial] = $range; + $length = $end - $start + 1; + + $headers['Content-Length'] = (string) $length; + + if ($partial) { + $headers['Content-Range'] = "bytes {$start}-{$end}/{$media->size}"; + } + + if ($request->isMethod('HEAD')) { + return response('', $partial ? 206 : 200, $headers); + } + + try { + $stream = $library->open($media); + } catch (MediaStorageException $e) { + if ($e->status === 404) { + abort(404); + } + + return response('This file is temporarily unavailable.', 503, ['Retry-After' => (string) ($e->retryAfter ?? 30), 'Cache-Control' => 'no-store']); + } + + return response()->stream(fn () => $this->send($stream, $start, $length), $partial ? 206 : 200, $headers); + } + + /** @return array */ + private function headers(Media $media): array + { + $inline = in_array($media->mime_type, self::INLINE_TYPES, true); + $name = str_replace(['"', '\\', "\r", "\n"], '', $media->filename); + + return [ + 'Content-Type' => $inline ? $media->mime_type : 'application/octet-stream', + 'Content-Disposition' => ($inline ? 'inline' : 'attachment').'; filename="'.$name.'"', + 'X-Content-Type-Options' => 'nosniff', + 'Accept-Ranges' => 'bytes', + 'Cache-Control' => 'public, max-age=31536000, immutable', + 'ETag' => '"'.($media->checksum ?? 'media-'.$media->id).'"', + ]; + } + + /** + * The part of the file the browser asks for: [first byte, last byte, is it a part]. + * Null when the request asks for bytes the file does not have. + * + * @return array{int, int, bool}|null + */ + private function range(Request $request, int $size): ?array + { + $header = $request->headers->get('Range'); + $whole = [0, max($size - 1, 0), false]; + + // No range, an empty file, or something other than one plain byte range: send it all. + if ($header === null || $size === 0 || preg_match('/^bytes=(\d*)-(\d*)$/', trim($header), $match) !== 1) { + return $whole; + } + + [, $first, $last] = $match; + + if ($first === '' && $last === '') { + return $whole; + } + + if ($first === '') { + // "bytes=-500": the last 500 bytes. + $start = max($size - (int) $last, 0); + $end = $size - 1; + } else { + $start = (int) $first; + $end = $last === '' ? $size - 1 : min((int) $last, $size - 1); + } + + if ($start >= $size || $start > $end) { + return null; + } + + return [$start, $end, true]; + } + + /** @param resource $stream */ + private function send($stream, int $start, int $length): void + { + try { + if ($start > 0 && stream_get_meta_data($stream)['seekable']) { + fseek($stream, $start); + } else { + $skip = $start; + + while ($skip > 0 && ! feof($stream)) { + $chunk = fread($stream, min(65536, $skip)); + + if ($chunk === false || $chunk === '') { + break; + } + + $skip -= strlen($chunk); + } + } + + while ($length > 0 && ! feof($stream)) { + $chunk = fread($stream, min(65536, $length)); + + if ($chunk === false || $chunk === '') { + break; + } + + echo $chunk; + flush(); + + $length -= strlen($chunk); + } + } finally { + fclose($stream); + } + } +} diff --git a/src/Modules/Media/MediaLibrary.php b/src/Modules/Media/MediaLibrary.php new file mode 100644 index 0000000..e06184e --- /dev/null +++ b/src/Modules/Media/MediaLibrary.php @@ -0,0 +1,172 @@ +getClientOriginalExtension()); + $baseName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME); + $filename = (Str::slug($baseName) ?: 'file').($extension !== '' ? '.'.$extension : ''); + $path = $file->getRealPath(); + + if ($path === false) { + throw new MediaStorageException('The uploaded file could not be read.'); + } + + $mimeType = $file->getMimeType() ?? 'application/octet-stream'; + $dimensions = str_starts_with($mimeType, 'image/') ? @getimagesize($path) : false; + $disk ??= config('manager.media.disk'); + + $location = $file->store('media/'.now()->format('Y/m'), $disk); + + if ($location === false) { + throw new MediaStorageException('The file could not be stored.'); + } + + return Media::create([ + 'disk' => $disk, + 'location' => $location, + 'name' => Str::limit(trim($baseName) !== '' ? trim($baseName) : 'File', 250, ''), + 'filename' => $filename, + 'mime_type' => $mimeType, + 'size' => (int) $file->getSize(), + 'checksum' => hash_file('sha256', $path) ?: null, + 'width' => $dimensions !== false ? $dimensions[0] : null, + 'height' => $dimensions !== false ? $dimensions[1] : null, + 'uploaded_by' => $uploader?->getAuthIdentifier(), + ]); + } + + /** + * Move a file to another disk: copy it (the same location on the new disk), check the size (and, with $verify, what comes + * back), only then point the row at the new disk and, when asked, delete the original. The address of the file does not + * change, because it holds the id of the row. A file that is already there is not copied again. + * + * @throws MediaStorageException with the file still where it was + */ + public function move(Media $media, string $disk, bool $deleteSource = false, bool $verify = false): void + { + $from = Storage::disk($media->disk); + $to = Storage::disk($disk); + + $wrote = false; + + if (! $to->exists($media->location)) { + $stream = $this->open($media); + + try { + $stored = $to->put($media->location, $stream); + } finally { + is_resource($stream) && fclose($stream); + } + + if ($stored === false) { + throw new MediaStorageException('The file could not be written to the new disk.'); + } + + $wrote = true; + } + + if ($to->size($media->location) !== (int) $media->size) { + $wrote && $to->delete($media->location); + + throw new MediaStorageException('The copy on the new disk is not the size of the original.'); + } + + if ($verify && $media->checksum !== null && hash('sha256', (string) $to->get($media->location)) !== $media->checksum) { + $wrote && $to->delete($media->location); + + throw new MediaStorageException('The copy on the new disk is not the same as the original.'); + } + + $source = $media->disk; + $media->update(['disk' => $disk]); + + if ($deleteSource && $source !== $disk) { + Storage::disk($source)->delete($media->location); + } + } + + /** + * How full the library is: what all files together take, how much it may hold + * (`manager.media.max_total_gb`) and what is left. In bytes. + * + * @return array{used: int, limit: int, left: int} + */ + public function room(): array + { + $configured = config('manager.media.max_total_gb'); + $limit = (int) round((is_numeric($configured) ? max(0.0, (float) $configured) : 15.0) * 1_000_000_000); + $used = (int) Media::query()->sum('size'); + + return ['used' => $used, 'limit' => $limit, 'left' => max(0, $limit - $used)]; + } + + /** + * Open a file's content as a stream. Read it and close it. + * + * @return resource + * + * @throws MediaStorageException with status 404 when the file is gone + */ + public function open(Media $media) + { + $stream = Storage::disk($media->disk)->readStream($media->location); + + if (! is_resource($stream)) { + throw new MediaStorageException('The file is no longer there.', 404); + } + + return $stream; + } + + /** Delete the file and then its row. When the storage refuses, the row stays. */ + public function delete(Media $media): void + { + $disk = Storage::disk($media->disk); + + if ($disk->exists($media->location) && ! $disk->delete($media->location)) { + throw new MediaStorageException('The file could not be deleted.'); + } + + $media->delete(); + } + + /** + * How often each media file is used, keyed by media id: how many of the registered sources + * (MediaUsage) hold its address. Nothing registered means 0. + * + * @param iterable $items + * @return array + */ + public function usageCounts(iterable $items): array + { + $haystacks = $this->usage->haystacks(); + $counts = []; + + foreach ($items as $media) { + $prefix = $media->urlPrefix(); + $counts[$media->id] = count(array_filter($haystacks, fn (string $text) => str_contains($text, $prefix))); + } + + return $counts; + } +} diff --git a/src/Modules/Media/MediaModule.php b/src/Modules/Media/MediaModule.php new file mode 100644 index 0000000..ccc4c48 --- /dev/null +++ b/src/Modules/Media/MediaModule.php @@ -0,0 +1,69 @@ + 'Media', 'route' => Names::route('media.index'), 'permission' => 'media.view', 'simple' => true, 'hint' => 'Your photos and files'], + ]; + } + + public function actions(): array + { + return [ + 'media.store' => ['Uploaded a file'], + 'media.update' => ['Changed a file'], + 'media.destroy' => ['Deleted a file'], + ]; + } + + public function views(): array + { + return ['media.index' => 'Opened the media library', 'media.items' => '']; + } + + public function boot(): void + { + RateLimiter::for('media-files', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.media.per_minute', 600)))->by((string) $request->ip())); + } +} diff --git a/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php new file mode 100644 index 0000000..378a89d --- /dev/null +++ b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php @@ -0,0 +1,41 @@ +getTable(); + + // The file itself is elsewhere: `disk` says where, `location` is its path there. + Tables::create(Names::table('media'), function (Blueprint $table) use ($users) { + $table->id(); + $table->string('disk', 40); + $table->string('location'); + $table->string('name'); + $table->string('filename'); + $table->string('mime_type', 100); + $table->unsignedBigInteger('size'); + $table->string('checksum', 64)->nullable(); + $table->unsignedInteger('width')->nullable(); + $table->unsignedInteger('height')->nullable(); + $table->string('alt', 500)->nullable(); + // The part of an image that must stay in view when it is cropped to fit: + // 0-1 from the left and from the top. + $table->decimal('focus_x', 5, 4)->nullable(); + $table->decimal('focus_y', 5, 4)->nullable(); + $table->foreignId('uploaded_by')->nullable()->constrained($users)->nullOnDelete(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('media')); + } +}; diff --git a/src/Modules/Media/migrations/2026_12_08_000002_create_manager_storage_files.php b/src/Modules/Media/migrations/2026_12_08_000002_create_manager_storage_files.php new file mode 100644 index 0000000..a4f9721 --- /dev/null +++ b/src/Modules/Media/migrations/2026_12_08_000002_create_manager_storage_files.php @@ -0,0 +1,25 @@ +id(); + $table->string('path')->unique(); + $table->string('remote_id', 100); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('storage_files')); + } +}; diff --git a/src/Modules/Media/public-routes.php b/src/Modules/Media/public-routes.php new file mode 100644 index 0000000..aa1433a --- /dev/null +++ b/src/Modules/Media/public-routes.php @@ -0,0 +1,13 @@ +whereNumber('media') + ->middleware('throttle:media-files') + ->name(Names::route('media.file')); diff --git a/src/Modules/Media/routes.php b/src/Modules/Media/routes.php new file mode 100644 index 0000000..2b81661 --- /dev/null +++ b/src/Modules/Media/routes.php @@ -0,0 +1,10 @@ +name('media.index')->middleware('can:media.view'); +Route::get('/media/items', [MediaController::class, 'items'])->name('media.items')->middleware('can:media.view'); +Route::post('/media', [MediaController::class, 'store'])->name('media.store')->middleware('can:media.upload'); +Route::put('/media/{media}', [MediaController::class, 'update'])->name('media.update')->middleware('can:media.edit')->whereNumber('media'); +Route::delete('/media/{media}', [MediaController::class, 'destroy'])->name('media.destroy')->middleware('can:media.delete')->whereNumber('media'); diff --git a/src/Modules/Numbers/NumbersController.php b/src/Modules/Numbers/NumbersController.php new file mode 100644 index 0000000..a0da9ee --- /dev/null +++ b/src/Modules/Numbers/NumbersController.php @@ -0,0 +1,15 @@ +json($numbers->over((string) $request->query('range', Numbers::DEFAULT_PERIOD), Gate::forUser($request->user())->allows('leads.view'))); + } +} diff --git a/src/Modules/Numbers/NumbersModule.php b/src/Modules/Numbers/NumbersModule.php new file mode 100644 index 0000000..8a975ac --- /dev/null +++ b/src/Modules/Numbers/NumbersModule.php @@ -0,0 +1,46 @@ + 'Numbers', 'route' => Names::route('numbers.index'), 'permission' => 'numbers.view', 'simple' => true, 'hint' => 'How your website is doing', 'icon' => 'chart']]; + } + + public function views(): array + { + return ['numbers.index' => 'Opened the numbers']; + } +} diff --git a/src/Modules/Numbers/routes.php b/src/Modules/Numbers/routes.php new file mode 100644 index 0000000..68cc32e --- /dev/null +++ b/src/Modules/Numbers/routes.php @@ -0,0 +1,6 @@ +name('numbers.index')->middleware('can:numbers.view'); diff --git a/src/Modules/Pages/PagesController.php b/src/Modules/Pages/PagesController.php new file mode 100644 index 0000000..5fe77ca --- /dev/null +++ b/src/Modules/Pages/PagesController.php @@ -0,0 +1,123 @@ +orderBy('title')->get()->keyBy('slug'); + $pages = []; + + foreach ($definitions as $slug => $definition) { + $pages[] = ['slug' => $slug, 'title' => $definition['title'], 'simple_title' => $definition['simple_title'], 'defined' => true, 'saved' => $stored->has($slug), 'updated_at' => $stored[$slug]->updated_at ?? null]; + } + + foreach ($stored as $slug => $page) { + if (! isset($definitions[$slug])) { + $pages[] = ['slug' => $slug, 'title' => $page->title, 'defined' => false, 'saved' => true, 'is_published' => $page->is_published, 'updated_at' => $page->updated_at]; + } + } + + return response()->json(['pages' => $pages]); + } + + public function show(string $slug): JsonResponse + { + return response()->json(['page' => $this->payload($slug)]); + } + + /** Makes a free page. A defined page is made by saving it. */ + public function store(Request $request): JsonResponse + { + $data = $request->validate([ + 'slug' => ['required', 'string', 'max:120', 'regex:/^'.self::SLUG.'$/', Rule::unique(Page::query()->getModel()->getTable(), 'slug'), Rule::notIn(array_keys(Page::definitions()))], + 'title' => ['required', 'string', 'max:255'], + ]); + + $page = Page::query()->create($data + ['is_published' => false]); + app(AuditTrail::class)->about($page); + + return response()->json(['page' => $this->payload($page->slug)], 201); + } + + public function update(Request $request, string $slug): JsonResponse + { + $definition = Page::definitions()[$slug] ?? null; + $page = Page::query()->where('slug', $slug)->first(); + abort_if($definition === null && $page === null, 404); + + $rules = [ + 'title' => ['required', 'string', 'max:255'], + 'meta_description' => ['nullable', 'string', 'max:255'], + ]; + + if ($definition !== null) { + $rules = [...$rules, 'content' => ['nullable', 'array'], ...Fields::rules($definition['fields'], 'content.')]; + } else { + $rules = [...$rules, 'body' => ['nullable', 'string', 'max:200000'], 'is_published' => ['boolean']]; + } + + $data = $request->validate($rules); + $values = ['title' => $data['title'], 'meta_description' => ($data['meta_description'] ?? '') ?: null]; + + if ($definition !== null) { + $values['content'] = Fields::clean($definition['fields'], (array) ($data['content'] ?? [])); + } else { + $values += ['body' => $data['body'] ?? null, 'is_published' => (bool) ($data['is_published'] ?? false)]; + } + + $page = $page ?? new Page(['slug' => $slug]); + $page->fill($values)->save(); + app(AuditTrail::class)->about($page); + + return response()->json(['page' => $this->payload($slug)]); + } + + /** Removes a free page; a defined page stays (its values go back to the defaults when it is emptied by saving). */ + public function destroy(string $slug): JsonResponse + { + abort_if(isset(Page::definitions()[$slug]), 422, __('A page with fields of its own cannot be removed.')); + + $page = Page::query()->where('slug', $slug)->firstOrFail(); + app(AuditTrail::class)->about($page); + $page->delete(); + + return response()->json(['deleted' => true]); + } + + /** @return array */ + private function payload(string $slug): array + { + $definition = Page::definitions()[$slug] ?? null; + $page = Page::query()->where('slug', $slug)->first(); + abort_if($definition === null && $page === null, 404); + + return [ + 'id' => $page?->id, + 'slug' => $slug, + 'title' => $page->title ?? $definition['title'], + 'simple_title' => $definition['simple_title'] ?? null, + 'meta_description' => $page->meta_description ?? '', + 'defined' => $definition !== null, + 'fields' => array_values($definition['fields'] ?? []), + 'content' => $definition !== null ? Fields::values($definition['fields'], is_array($page?->content) ? $page->content : []) : null, + 'body' => $definition === null ? (string) $page->body : null, + 'is_published' => $definition === null ? (bool) $page->is_published : null, + ]; + } +} diff --git a/src/Modules/Pages/PagesModule.php b/src/Modules/Pages/PagesModule.php new file mode 100644 index 0000000..5d4b826 --- /dev/null +++ b/src/Modules/Pages/PagesModule.php @@ -0,0 +1,66 @@ + 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit', 'simple' => true, 'hint' => 'Change the texts and photos of your pages'], + ]; + } + + /** Where the media library looks for the use of a file: the texts of the pages. */ + public function views(): array + { + return ['pages.index' => 'Opened the pages', 'pages.show' => 'Opened a page']; + } + + public function actions(): array + { + return [ + 'pages.store' => ['Created a page'], + 'pages.update' => ['Changed a page'], + 'pages.destroy' => ['Removed a page'], + ]; + } + + public function boot(): void + { + app(MediaUsage::class)->register(fn () => Page::query()->get(['body', 'content'])->flatMap(fn (Page $row) => [$row->body, ...array_values(array_filter((array) $row->content, 'is_string'))])); + } +} diff --git a/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php b/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php new file mode 100644 index 0000000..b85b8bb --- /dev/null +++ b/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php @@ -0,0 +1,27 @@ +id(); + $table->string('slug')->unique(); + $table->string('title'); + $table->longText('body')->nullable(); + $table->boolean('is_published')->default(false); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('pages')); + } +}; diff --git a/src/Modules/Pages/migrations/2026_12_06_000001_add_content_to_manager_pages.php b/src/Modules/Pages/migrations/2026_12_06_000001_add_content_to_manager_pages.php new file mode 100644 index 0000000..b732517 --- /dev/null +++ b/src/Modules/Pages/migrations/2026_12_06_000001_add_content_to_manager_pages.php @@ -0,0 +1,26 @@ + $table->string('meta_description', 255)->nullable()); + Tables::addColumn($pages, 'content', fn (Blueprint $table) => $table->json('content')->nullable()); + } + + public function down(): void + { + Schema::table(Names::table('pages'), function (Blueprint $table) { + $table->dropColumn(['meta_description', 'content']); + }); + } +}; diff --git a/src/Modules/Pages/routes.php b/src/Modules/Pages/routes.php new file mode 100644 index 0000000..f226379 --- /dev/null +++ b/src/Modules/Pages/routes.php @@ -0,0 +1,12 @@ +group(function () { + Route::get('/pages', [PagesController::class, 'index'])->name('pages.index'); + Route::post('/pages', [PagesController::class, 'store'])->name('pages.store'); + Route::get('/pages/{slug}', [PagesController::class, 'show'])->name('pages.show')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*'); + Route::put('/pages/{slug}', [PagesController::class, 'update'])->name('pages.update')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*'); + Route::delete('/pages/{slug}', [PagesController::class, 'destroy'])->name('pages.destroy')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*'); +}); diff --git a/src/Modules/Posts/LabelController.php b/src/Modules/Posts/LabelController.php new file mode 100644 index 0000000..c91db84 --- /dev/null +++ b/src/Modules/Posts/LabelController.php @@ -0,0 +1,80 @@ +json($this->labels->overview()); + } + + /** A category or tag that no post uses yet; the post form offers it from then on. */ + public function store(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => $this->nameRules($type)], $this->messages()); + + $name = $request->string('name')->trim()->toString(); + + if (! $this->labels->create($type, $name)) { + return response()->json(['message' => $already = __('The :type ":name" already exists.', ['type' => __($type), 'name' => $name]), 'errors' => ['name' => [$already]]], 422); + } + + return response()->json(['created' => $name], 201); + } + + public function update(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => ['required', 'string'], 'new_name' => $this->nameRules($type)], $this->messages()); + + $from = $request->string('name')->toString(); + $to = $request->string('new_name')->trim()->toString(); + + return response()->json(['posts' => $this->labels->rename($type, $from, $to)]); + } + + public function destroy(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => ['required', 'string']]); + + return response()->json(['posts' => $this->labels->remove($type, $request->string('name')->toString())]); + } + + /** + * The same limits as the post form. + * + * @return list + */ + private function nameRules(string $type): array + { + return ['required', 'string', 'max:'.($type === PostLabels::CATEGORY ? 60 : 40), ...($type === PostLabels::TAG ? ['not_regex:/,/'] : [])]; + } + + /** @return array */ + private function messages(): array + { + $comma = 'A tag cannot hold a comma: the post form separates tags with it.'; + + return ['name.not_regex' => $comma, 'new_name.not_regex' => $comma]; + } + + private function type(Request $request): string + { + $request->validate(['type' => ['required', Rule::in([PostLabels::CATEGORY, PostLabels::TAG])]]); + + return $request->string('type')->toString(); + } +} diff --git a/src/Modules/Posts/PostController.php b/src/Modules/Posts/PostController.php new file mode 100644 index 0000000..1746c97 --- /dev/null +++ b/src/Modules/Posts/PostController.php @@ -0,0 +1,194 @@ +orderByRaw('published_at is null desc') + ->latest('published_at') + ->latest('id') + ->get() + ->map(fn (Post $post) => [ + 'id' => $post->id, + 'title' => $post->title, + 'slug' => $post->slug, + 'category' => $post->category, + 'is_featured' => $post->is_featured, + 'status' => $post->status(), + 'published_at' => $post->published_at?->toIso8601String(), + 'can_change' => Gate::allows('posts.write') && $this->mayTouch($post), + 'can_delete' => Gate::allows('posts.delete') && $this->mayTouch($post), + ]) + ->values(); + + return response()->json(['posts' => $posts]); + } + + public function create(): JsonResponse + { + return response()->json([ + 'post' => null, + 'categories' => $this->labels->categories(), + 'known_tags' => $this->labels->names(PostLabels::TAG), + ]); + } + + public function store(Request $request): JsonResponse + { + $post = Post::create($this->validated($request)); + + return response()->json(['id' => $post->id], 201); + } + + public function edit(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + + return response()->json([ + 'post' => [ + 'id' => $post->id, + 'title' => $post->title, + 'slug' => $post->slug, + 'excerpt' => $post->excerpt, + 'body' => $post->body, + 'cover_image' => $post->cover_image, + 'category' => $post->category, + 'tags' => $post->tags ?? [], + 'is_featured' => $post->is_featured, + 'is_published' => $post->published_at !== null, + // datetime-local value, in the app timezone + 'published_at' => $post->published_at?->format('Y-m-d\TH:i'), + 'status' => $post->status(), + ], + 'categories' => $this->labels->categories(), + 'known_tags' => $this->labels->names(PostLabels::TAG), + ]); + } + + /** The post as a visitor will see it, also for drafts and scheduled posts. */ + public function preview(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + + return response()->json(['post' => [...$post->toCard(), 'body_html' => Markdown::toHtml($post->body)], 'preview' => true]); + } + + public function update(Request $request, string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + app(AuditTrail::class)->about($post); + + $post->update($this->validated($request, $post)); + + return response()->json(['saved' => true]); + } + + /** Puts a post on the site, or takes it off again (a draft) without opening it. */ + public function online(Request $request, string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + $request->validate(['online' => ['required', 'boolean']]); + app(AuditTrail::class)->about($post); + + $post->update(['published_at' => $request->boolean('online') ? ($post->published_at ?? now()) : null]); + + return response()->json(['status' => $post->status()]); + } + + public function destroy(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + app(AuditTrail::class)->about($post); + + $post->delete(); + + return response()->json(['deleted' => true]); + } + + /** + * Validates the post form and turns it into model attributes. + * + * @return array + */ + private function validated(Request $request, ?Post $post = null): array + { + $request->validate([ + 'title' => ['required', 'string', 'max:255'], + 'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(Names::table('posts'), 'slug')->ignore($post?->id)], + 'excerpt' => ['nullable', 'string', 'max:500'], + 'body' => ['required', 'string'], + 'cover_image' => ['nullable', 'string', 'max:2048'], + 'category' => ['nullable', 'string', 'max:60'], + 'tags' => ['array', 'max:20'], + 'tags.*' => ['nullable', 'string', 'max:40'], + 'is_featured' => ['boolean'], + 'is_published' => ['boolean'], + 'published_at' => ['nullable', 'date'], + ], [ + 'slug.regex' => 'Use only lowercase letters, numbers and dashes.', + ]); + + $title = $request->string('title')->trim()->toString(); + $slug = $request->string('slug')->trim()->toString(); + + // Publishing without a date means "now"; a date in the future schedules the post. + // Who may not publish only gets a draft, and a post that was live is not touched + // (mayTouch refused that before we got here). + $publishedAt = null; + if ($request->boolean('is_published') && Gate::allows('posts.publish')) { + $date = $request->string('published_at')->toString(); + $publishedAt = $date !== '' ? Carbon::parse($date) : ($post?->published_at ?? now()); + } + + return [ + 'title' => $title, + 'slug' => $slug !== '' ? $slug : Post::uniqueSlug($title, $post?->id), + 'excerpt' => $this->nullableString($request, 'excerpt'), + 'body' => $request->string('body')->toString(), + 'cover_image' => $this->nullableString($request, 'cover_image'), + 'category' => $this->nullableString($request, 'category'), + 'tags' => array_values(array_filter(array_map( + fn (mixed $tag) => is_string($tag) ? trim($tag) : '', + $request->array('tags'), + ))), + 'is_featured' => $request->boolean('is_featured'), + 'published_at' => $publishedAt, + ]; + } + + private function mayTouch(Post $post): bool + { + return $post->published_at === null || Gate::allows('posts.publish'); + } + + private function nullableString(Request $request, string $key): ?string + { + $value = $request->string($key)->trim()->toString(); + + return $value !== '' ? $value : null; + } +} diff --git a/src/Modules/Posts/PostLabels.php b/src/Modules/Posts/PostLabels.php new file mode 100644 index 0000000..bcd0f4a --- /dev/null +++ b/src/Modules/Posts/PostLabels.php @@ -0,0 +1,192 @@ +> */ + private array $suggestions = []; + + /** A site offers more categories in the post form, for instance the titles of its services. */ + public function suggestCategories(Closure $source): void + { + $this->suggestions[] = $source; + } + + /** + * What the post form offers as category: the suggestions of the site, the configured ones, + * and whatever is in use or was made by hand. + * + * @return list + */ + public function categories(): array + { + $suggested = []; + + foreach ($this->suggestions as $source) { + array_push($suggested, ...array_values([...$source()])); + } + + return array_values(array_unique([...$suggested, ...array_values((array) config('manager.posts.categories', [])), ...$this->names(self::CATEGORY)])); + } + + private function table(): string + { + return Names::table('post_labels'); + } + + /** + * Every category and tag, the ones made by hand included, with the number of posts (drafts + * included) that use it. + * + * @return array{categories: list, tags: list} + */ + public function overview(): array + { + $categories = []; + $tags = []; + + foreach (Post::query()->get(['id', 'category', 'tags']) as $post) { + if ($post->category !== null && $post->category !== '') { + $categories[$post->category] = ($categories[$post->category] ?? 0) + 1; + } + + foreach (array_unique($this->tagsOf($post)) as $tag) { + $tags[$tag] = ($tags[$tag] ?? 0) + 1; + } + } + + foreach (DB::table($this->table())->get(['type', 'name']) as $row) { + if (! is_string($row->name)) { + continue; + } + + if ($row->type === self::CATEGORY) { + $categories[$row->name] ??= 0; + } else { + $tags[$row->name] ??= 0; + } + } + + return ['categories' => $this->listed($categories), 'tags' => $this->listed($tags)]; + } + + /** + * The names of all categories or tags, to offer in the post form. + * + * @return list + */ + public function names(string $type): array + { + return array_column($this->overview()[$type === self::CATEGORY ? 'categories' : 'tags'], 'name'); + } + + /** Makes a category or tag that no post uses yet. False when the name is already there. */ + public function create(string $type, string $name): bool + { + if (in_array($name, $this->names($type), true)) { + return false; + } + + DB::table($this->table())->insert(['type' => $type, 'name' => $name, 'created_at' => now(), 'updated_at' => now()]); + + return true; + } + + /** Gives every post with the label the new name. Returns how many posts changed. */ + public function rename(string $type, string $from, string $to): int + { + if ($from === $to) { + return 0; + } + + // The name that was made by hand moves along, unless the new name is there already. + $made = DB::table($this->table())->where('type', $type); + if ((clone $made)->where('name', $to)->exists()) { + (clone $made)->where('name', $from)->delete(); + } else { + (clone $made)->where('name', $from)->update(['name' => $to, 'updated_at' => now()]); + } + + return $type === self::CATEGORY + ? Post::query()->where('category', $from)->update(['category' => $to]) + : $this->changeTags($from, $to); + } + + /** Takes the label off every post; the posts stay. Returns how many posts changed. */ + public function remove(string $type, string $name): int + { + DB::table($this->table())->where('type', $type)->where('name', $name)->delete(); + + return $type === self::CATEGORY + ? Post::query()->where('category', $name)->update(['category' => null]) + : $this->changeTags($name, null); + } + + /** Replaces a tag in every post that has it, or takes it out when $to is null. */ + private function changeTags(string $from, ?string $to): int + { + return DB::transaction(function () use ($from, $to) { + $changed = 0; + + foreach (Post::query()->whereNotNull('tags')->get() as $post) { + $tags = $this->tagsOf($post); + + if (! in_array($from, $tags, true)) { + continue; + } + + $new = []; + foreach ($tags as $tag) { + $tag = $tag === $from ? $to : $tag; + + // A post that had both names keeps the tag once. + if ($tag !== null && ! in_array($tag, $new, true)) { + $new[] = $tag; + } + } + + $post->update(['tags' => $new]); + $changed++; + } + + return $changed; + }); + } + + /** @return list */ + private function tagsOf(Post $post): array + { + return array_values(array_filter(is_array($post->tags) ? $post->tags : [], fn (mixed $tag) => is_string($tag) && $tag !== '')); + } + + /** + * @param array $counts + * @return list + */ + private function listed(array $counts): array + { + $names = array_map(fn (int|string $name) => (string) $name, array_keys($counts)); + natcasesort($names); + + return array_values(array_map(fn (string $name) => ['name' => $name, 'posts' => $counts[$name]], $names)); + } +} diff --git a/src/Modules/Posts/PostsModule.php b/src/Modules/Posts/PostsModule.php new file mode 100644 index 0000000..291b0f2 --- /dev/null +++ b/src/Modules/Posts/PostsModule.php @@ -0,0 +1,81 @@ + 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view', 'simple' => true, 'hint' => 'Write and put news on your website'], + ['label' => 'Categories and tags', 'route' => Names::route('labels.index'), 'permission' => 'posts.labels'], + ]; + } + + public function actions(): array + { + return [ + 'posts.store' => ['Created a post'], + 'posts.update' => ['Changed a post'], + 'posts.online' => ['Put a post on the site, or took it off', ['online']], + 'posts.destroy' => ['Deleted a post'], + 'labels.store' => ['Made a category or tag', ['type', 'name']], + 'labels.update' => ['Renamed a category or tag', ['type', 'name', 'new_name']], + 'labels.destroy' => ['Removed a category or tag', ['type', 'name']], + ]; + } + + public function views(): array + { + return [ + 'posts.index' => 'Opened the posts', + 'posts.create' => 'Opened the form for a new post', + 'posts.edit' => 'Opened a post', + 'posts.preview' => 'Opened the preview of a post', + 'labels.index' => 'Opened the categories and tags', + ]; + } + + /** Where the media library looks for the use of a file: the texts of the posts. */ + public function boot(): void + { + app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt', 'cover_image'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt', 'cover_image'])))); + } +} diff --git a/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php b/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php new file mode 100644 index 0000000..8cf6440 --- /dev/null +++ b/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php @@ -0,0 +1,47 @@ +id(); + $table->string('title'); + $table->string('slug')->unique(); + $table->string('excerpt', 500)->nullable(); + $table->longText('body'); + $table->string('cover_image', 2048)->nullable(); + $table->string('category', 60)->nullable(); + $table->json('tags')->nullable(); + $table->boolean('is_featured')->default(false); + // null = draft; a future date = scheduled + $table->timestamp('published_at')->nullable()->index(); + $table->timestamps(); + }); + + // Categories and tags that were made by hand, so one can exist before a post uses it. + // The ones a post uses are in the post itself; this only remembers names to offer. + Tables::create(Names::table('post_labels'), function (Blueprint $table) { + $table->id(); + $table->string('type', 10); + $table->string('name', 60); + $table->timestamps(); + + $table->unique(['type', 'name']); + }); + } + + public function down(): void + { + + Schema::dropIfExists(Names::table('post_labels')); + Schema::dropIfExists(Names::table('posts')); + } +}; diff --git a/src/Modules/Posts/routes.php b/src/Modules/Posts/routes.php new file mode 100644 index 0000000..623d3f6 --- /dev/null +++ b/src/Modules/Posts/routes.php @@ -0,0 +1,22 @@ +name('posts.index')->middleware('can:posts.view'); +Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create')->middleware('can:posts.write'); +Route::post('/posts', [PostController::class, 'store'])->name('posts.store')->middleware('can:posts.write'); +Route::get('/posts/{post}/edit', [PostController::class, 'edit'])->name('posts.edit')->middleware('can:posts.write')->whereNumber('post'); +Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('posts.preview')->middleware('can:posts.view')->whereNumber('post'); +Route::put('/posts/{post}', [PostController::class, 'update'])->name('posts.update')->middleware('can:posts.write')->whereNumber('post'); +Route::put('/posts/{post}/online', [PostController::class, 'online'])->name('posts.online')->middleware('can:posts.publish')->whereNumber('post'); +Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy')->middleware('can:posts.delete')->whereNumber('post'); + +// The name of a label travels in the body, not the address: it can hold anything. +Route::middleware('can:posts.labels')->group(function () { + Route::get('/labels', [LabelController::class, 'index'])->name('labels.index'); + Route::post('/labels', [LabelController::class, 'store'])->name('labels.store'); + Route::put('/labels', [LabelController::class, 'update'])->name('labels.update'); + Route::delete('/labels', [LabelController::class, 'destroy'])->name('labels.destroy'); +}); diff --git a/src/Modules/Resources/ResourceController.php b/src/Modules/Resources/ResourceController.php new file mode 100644 index 0000000..8660093 --- /dev/null +++ b/src/Modules/Resources/ResourceController.php @@ -0,0 +1,108 @@ +resource($resource, 'view'); + $page = Resources::query($def)->paginate($def['per_page']); + + return response()->json([ + 'resource' => $this->describe($def), + 'rows' => $page->getCollection()->map(fn (Model $model) => Resources::row($def, $model))->values(), + 'current_page' => $page->currentPage(), + 'last_page' => $page->lastPage(), + ]); + } + + public function create(string $resource): JsonResponse + { + $def = $this->resource($resource, 'manage'); + + return response()->json(['resource' => $this->describe($def), 'record' => ['id' => null, 'values' => Fields::values($def['fields'], [])]]); + } + + public function edit(string $resource, string $id): JsonResponse + { + $def = $this->resource($resource, 'manage'); + + return response()->json(['resource' => $this->describe($def), 'record' => Resources::row($def, $this->record($def, $id))]); + } + + public function store(Request $request, string $resource): JsonResponse + { + $def = $this->resource($resource, 'manage'); + $model = Resources::save($def, null, $this->values($request, $def)); + app(AuditTrail::class)->about($model); + + return response()->json(['record' => Resources::row($def, $model)], 201); + } + + public function update(Request $request, string $resource, string $id): JsonResponse + { + $def = $this->resource($resource, 'manage'); + $model = Resources::save($def, $this->record($def, $id), $this->values($request, $def)); + app(AuditTrail::class)->about($model); + + return response()->json(['record' => Resources::row($def, $model)]); + } + + public function destroy(string $resource, string $id): JsonResponse + { + $def = $this->resource($resource, 'manage'); + $model = $this->record($def, $id); + app(AuditTrail::class)->about($model); + $model->delete(); + + return response()->json(['deleted' => true]); + } + + /** @return array */ + private function resource(string $key, string $ability): array + { + $def = Resources::find($key); + abort_if($def === null, 404); + Gate::authorize($key.'.'.$ability); + + return $def; + } + + /** @param array $def */ + private function record(array $def, string $id): Model + { + return Resources::record($def, $id) ?? abort(404); + } + + /** + * @param array $def + * @return array + */ + private function values(Request $request, array $def): array + { + $data = $request->validate(Fields::rules($def['fields'])); + + return Fields::clean($def['fields'], $data); + } + + /** + * @param array $def + * @return array + */ + private function describe(array $def): array + { + return [ + 'key' => $def['key'], 'label' => $def['label'], 'singular' => $def['singular'], 'simple_label' => $def['simple_label'], 'simple_singular' => $def['simple_singular'], 'columns' => $def['columns'], + 'fields' => Fields::described($def['fields']), 'can_manage' => Gate::allows($def['key'].'.manage'), + ]; + } +} diff --git a/src/Modules/Resources/ResourcesModule.php b/src/Modules/Resources/ResourcesModule.php new file mode 100644 index 0000000..449a43c --- /dev/null +++ b/src/Modules/Resources/ResourcesModule.php @@ -0,0 +1,69 @@ + $resource) { + $permissions[] = new Permission($key.'.view', __('See :label', ['label' => $resource['label']]), $resource['label']); + $permissions[] = new Permission($key.'.manage', __('Add, change and delete :label', ['label' => $resource['label']]), $resource['label'], needs: [$key.'.view']); + } + + return $permissions; + } + + public function navigation(): array + { + return array_values(array_map( + fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'simple_label' => $resource['simple_label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view', 'simple' => true, 'hint' => $resource['hint']], + Resources::all(), + )); + } + + public function actions(): array + { + return [ + 'records.store' => ['Added a record'], + 'records.update' => ['Changed a record'], + 'records.destroy' => ['Removed a record'], + ]; + } + + public function views(): array + { + return ['records.index' => 'Opened a list', 'records.create' => 'Opened the form for a new record', 'records.edit' => 'Opened a record']; + } +} diff --git a/src/Modules/Resources/migrations/2026_12_06_000001_create_manager_records.php b/src/Modules/Resources/migrations/2026_12_06_000001_create_manager_records.php new file mode 100644 index 0000000..3ce8c76 --- /dev/null +++ b/src/Modules/Resources/migrations/2026_12_06_000001_create_manager_records.php @@ -0,0 +1,25 @@ +id(); + $table->string('resource', 40)->index(); + $table->json('data')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('records')); + } +}; diff --git a/src/Modules/Resources/routes.php b/src/Modules/Resources/routes.php new file mode 100644 index 0000000..3069e52 --- /dev/null +++ b/src/Modules/Resources/routes.php @@ -0,0 +1,14 @@ +.view` and `.manage`. +Route::prefix('/records/{resource}')->where(['resource' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+'])->group(function () { + Route::get('/', [ResourceController::class, 'index'])->name('records.index'); + Route::get('/create', [ResourceController::class, 'create'])->name('records.create'); + Route::post('/', [ResourceController::class, 'store'])->name('records.store'); + Route::get('/{id}/edit', [ResourceController::class, 'edit'])->name('records.edit'); + Route::put('/{id}', [ResourceController::class, 'update'])->name('records.update'); + Route::delete('/{id}', [ResourceController::class, 'destroy'])->name('records.destroy'); +}); diff --git a/src/Modules/Reviews/ReviewsController.php b/src/Modules/Reviews/ReviewsController.php new file mode 100644 index 0000000..d74ed8f --- /dev/null +++ b/src/Modules/Reviews/ReviewsController.php @@ -0,0 +1,14 @@ +json(Review::query()->latest()->paginate(25)); + } +} diff --git a/src/Modules/Reviews/ReviewsModule.php b/src/Modules/Reviews/ReviewsModule.php new file mode 100644 index 0000000..0bc86e4 --- /dev/null +++ b/src/Modules/Reviews/ReviewsModule.php @@ -0,0 +1,49 @@ + 'Reviews', 'route' => Names::route('reviews.index'), 'permission' => 'reviews.manage'], + ]; + } + + public function views(): array + { + return ['reviews.index' => 'Opened the reviews']; + } +} diff --git a/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php b/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php new file mode 100644 index 0000000..3129e1e --- /dev/null +++ b/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php @@ -0,0 +1,28 @@ +id(); + $table->string('author'); + $table->string('place')->nullable(); + $table->unsignedTinyInteger('rating')->nullable(); + $table->text('body'); + $table->boolean('is_visible')->default(true); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('reviews')); + } +}; diff --git a/src/Modules/Reviews/routes.php b/src/Modules/Reviews/routes.php new file mode 100644 index 0000000..bbbd424 --- /dev/null +++ b/src/Modules/Reviews/routes.php @@ -0,0 +1,6 @@ +name('reviews.index')->middleware('can:reviews.manage'); diff --git a/src/Modules/Revisions/RevisionController.php b/src/Modules/Revisions/RevisionController.php new file mode 100644 index 0000000..7727f39 --- /dev/null +++ b/src/Modules/Revisions/RevisionController.php @@ -0,0 +1,65 @@ +find($type, $id, 'view'); + + $revisions = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->orderByDesc('id')->limit(100)->get(); + + return response()->json([ + 'revisions' => $revisions->map(fn (Revision $revision, int $position) => [ + 'id' => $revision->id, + 'created_at' => $revision->created_at, + 'user' => $revision->user_name, + 'changed' => $revision->changed ?? [], + 'current' => $position === 0, + // What the changed attributes were then, shortened: enough to see what an old version said. + 'values' => collect($revision->changed ?? [])->mapWithKeys(fn (string $key) => [$key => $this->shorten($revision->data[$key] ?? null)])->all(), + ])->values(), + 'can_restore' => Gate::allows('revisions.restore') && Gate::allows($config['restore']), + ]); + } + + public function restore(string $type, string $id, string $revision): JsonResponse + { + [$config, $model] = $this->find($type, $id, 'restore'); + $revision = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->whereKey($revision)->firstOrFail(); + + // A post that is on the site is only changed by someone who may publish. + abort_if($model instanceof Post && $model->isPublished() && Gate::denies('posts.publish'), 403); + + app(AuditTrail::class)->about($model); + Revisions::restore($model, $revision, $config); + + return response()->json(['restored' => true]); + } + + /** @return array{0: array{model: class-string, view: string, restore: string, except: list}, 1: Model} */ + private function find(string $type, string $id, string $ability): array + { + $config = Revisions::types()[$type] ?? null; + abort_if($config === null, 404); + Gate::authorize($config[$ability]); + + return [$config, $config['model']::query()->findOrFail($id)]; + } + + private function shorten(mixed $value): mixed + { + $text = is_scalar($value) || $value === null ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + return mb_strlen($text) > 300 ? mb_substr($text, 0, 300).'…' : $text; + } +} diff --git a/src/Modules/Revisions/RevisionsModule.php b/src/Modules/Revisions/RevisionsModule.php new file mode 100644 index 0000000..ef5820b --- /dev/null +++ b/src/Modules/Revisions/RevisionsModule.php @@ -0,0 +1,54 @@ + ['Put an earlier version back']]; + } + + public function views(): array + { + return ['revisions.index' => 'Opened the history of a text']; + } + + public function boot(): void + { + Revisions::listen(); + } +} diff --git a/src/Modules/Revisions/migrations/2026_12_06_000001_create_manager_revisions.php b/src/Modules/Revisions/migrations/2026_12_06_000001_create_manager_revisions.php new file mode 100644 index 0000000..7609f04 --- /dev/null +++ b/src/Modules/Revisions/migrations/2026_12_06_000001_create_manager_revisions.php @@ -0,0 +1,32 @@ +id(); + $table->string('type', 40); + $table->unsignedBigInteger('subject_id'); + // Who saved it: no foreign key, so the history stays when an account is removed. + $table->unsignedBigInteger('user_id')->nullable(); + $table->string('user_name')->nullable(); + $table->json('data'); + $table->json('changed')->nullable(); + $table->dateTime('created_at'); + + $table->index(['type', 'subject_id', 'id']); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('revisions')); + } +}; diff --git a/src/Modules/Revisions/routes.php b/src/Modules/Revisions/routes.php new file mode 100644 index 0000000..d141f2f --- /dev/null +++ b/src/Modules/Revisions/routes.php @@ -0,0 +1,10 @@ +prefix('/revisions/{type}/{id}')->where(['type' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+', 'revision' => '[0-9]+'])->group(function () { + Route::get('/', [RevisionController::class, 'index'])->name('revisions.index'); + Route::post('/{revision}/restore', [RevisionController::class, 'restore'])->name('revisions.restore')->middleware('can:revisions.restore'); +}); diff --git a/src/Modules/Settings/SettingsController.php b/src/Modules/Settings/SettingsController.php new file mode 100644 index 0000000..65d1bd4 --- /dev/null +++ b/src/Modules/Settings/SettingsController.php @@ -0,0 +1,199 @@ +onlyFull($request); + + $groups = []; + $origin = []; + + foreach ($this->definitions->all() as $key => $definition) { + if (! $this->mayChange($request, $definition)) { + continue; + } + + $value = config($key); + + $origin[__($definition['group'])] = $definition['group']; + $groups[__($definition['group'])][] = [ + 'key' => $key, + 'label' => __($definition['label']), + 'type' => $definition['type'], + 'help' => $definition['help'] === null ? null : __($definition['help']), + 'options' => $definition['options'], + 'sensitive' => $definition['sensitive'], + // A secret says only whether it is set. + 'value' => $definition['type'] === 'secret' ? null : $value, + 'set' => $definition['type'] === 'secret' ? filled($value) : null, + 'saved' => $this->store->has($key), + ]; + } + + $mayTry = Gate::forUser($request->user())->allows('settings.secrets'); + + return response()->json([ + 'groups' => collect($groups)->map(fn (array $items, string $name) => ['name' => $name, 'items' => $items, 'check' => $mayTry && $this->checks->has($origin[$name])])->values(), + 'write_env' => (bool) config('manager.settings.write_env'), + 'env_writable' => $this->env->writable(), + 'config_cached' => app()->configurationIsCached(), + ]); + } + + public function update(Request $request): JsonResponse + { + $this->onlyFull($request); + $request->validate(['values' => ['present', 'array'], 'reset' => ['nullable', 'array'], 'reset.*' => ['string'], 'password' => ['nullable', 'string', 'max:200']]); + + $changes = []; + $sensitive = false; + + foreach ($request->array('values') as $key => $raw) { + $definition = $this->definitions->find((string) $key); + + if ($definition === null || ! $this->mayChange($request, $definition)) { + throw ValidationException::withMessages(['values' => __('This setting does not exist or you may not change it.')]); + } + + // A secret that is left empty is left alone (the browser sends an empty field as null): clearing one is `reset`. + if ($definition['type'] === 'secret' && ($raw === '' || $raw === null)) { + continue; + } + + try { + $value = $raw === null ? null : $this->definitions->cast($definition, $raw); + } catch (\InvalidArgumentException) { + throw ValidationException::withMessages(['values.'.$key => __('This value is not valid.')]); + } + + if ($value !== null && $value === config($key) && ! $this->store->has($key)) { + continue; + } + + $changes[$key] = $value; + $sensitive = $sensitive || $definition['sensitive']; + } + + // `reset`: back to what the config (and .env) says. + foreach ($request->array('reset') as $key) { + $definition = $this->definitions->find((string) $key); + + if ($definition === null || ! $this->mayChange($request, $definition)) { + throw ValidationException::withMessages(['reset' => __('This setting does not exist or you may not change it.')]); + } + + $changes[$key] = null; + $sensitive = $sensitive || $definition['sensitive']; + } + + if ($sensitive && ! Hash::check((string) $request->input('password'), (string) $request->user()->getAuthPassword())) { + throw ValidationException::withMessages(['password' => __('Type your own password to change this.')]); + } + + $result = $this->writer->apply($changes, $request->user()->getAuthIdentifier()); + + return response()->json([ + 'saved' => true, + 'changed' => count($changes), + ...$result, + 'migrate' => $this->pendingMigrations(array_keys($changes)), + ]); + } + + /** Writes the compiled file again and empties what caches the old values. */ + public function refresh(Request $request): JsonResponse + { + $this->onlyFull($request); + + $written = $this->writer->refresh(); + + return response()->json(['refreshed' => true, 'file_written' => $written]); + } + + /** Tries the connection of one group of settings with what is saved. Needs `settings.secrets`: it uses the keys. */ + public function check(Request $request): JsonResponse + { + $this->onlyFull($request); + abort_unless(Gate::forUser($request->user())->allows('settings.secrets'), 403); + + $group = (string) $request->validate(['group' => ['required', 'string', 'max:100']])['group']; + // The name that comes in is the translated one, as the screen shows it; the checks are keyed by the untranslated one. + $key = collect($this->definitions->all())->pluck('group')->unique()->first(fn (string $name) => __($name) === $group); + + abort_unless($key !== null && $this->checks->has($key), 404); + + return response()->json($this->checks->run($key)); + } + + private function onlyFull(Request $request): void + { + abort_if($this->menu->view($request->user()) === Menu::SIMPLE, 403); + } + + /** @param array $definition */ + private function mayChange(Request $request, array $definition): bool + { + $user = $request->user(); + + return (! $definition['sensitive'] || Gate::forUser($user)->allows('settings.secrets')) + && ($definition['permission'] === null || Gate::forUser($user)->allows($definition['permission'])); + } + + /** + * The parts that were switched on and miss a table: the screen tells to run `php artisan migrate`. + * + * @param list $keys + * @return list + */ + private function pendingMigrations(array $keys): array + { + $labels = []; + + foreach ($keys as $key) { + if (! str_starts_with($key, 'manager.modules.') || ! config($key)) { + continue; + } + + foreach ($this->modules->all() as $module) { + if ('manager.modules.'.$module->key() === $key && collect($module->tables())->contains(fn (string $table) => ! Schema::hasTable(Names::table($table)))) { + $labels[] = $module->label(); + } + } + } + + return $labels; + } +} diff --git a/src/Modules/Settings/SettingsModule.php b/src/Modules/Settings/SettingsModule.php new file mode 100644 index 0000000..40b5d31 --- /dev/null +++ b/src/Modules/Settings/SettingsModule.php @@ -0,0 +1,58 @@ + 'Settings', 'route' => Names::route('settings.index'), 'permission' => 'settings.manage', 'icon' => 'cog', 'simple' => false]]; + } + + public function actions(): array + { + return ['settings.update' => ['Changed the settings'], 'settings.refresh' => ['Refreshed the settings'], 'settings.check' => ['Tried a connection of the settings']]; + } + + public function views(): array + { + return ['settings.index' => 'Opened the settings']; + } +} diff --git a/src/Modules/Settings/migrations/2026_12_09_000001_create_manager_settings.php b/src/Modules/Settings/migrations/2026_12_09_000001_create_manager_settings.php new file mode 100644 index 0000000..f091475 --- /dev/null +++ b/src/Modules/Settings/migrations/2026_12_09_000001_create_manager_settings.php @@ -0,0 +1,29 @@ +id(); + $table->string('key', 150)->unique(); + // JSON; a secret is encrypted. + $table->text('value')->nullable(); + $table->boolean('is_secret')->default(false); + $table->unsignedBigInteger('updated_by')->nullable(); + $table->dateTime('created_at')->nullable(); + $table->dateTime('updated_at')->nullable(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('settings')); + } +}; diff --git a/src/Modules/Settings/routes.php b/src/Modules/Settings/routes.php new file mode 100644 index 0000000..1b331b1 --- /dev/null +++ b/src/Modules/Settings/routes.php @@ -0,0 +1,11 @@ +group(function () { + Route::get('/settings', [SettingsController::class, 'index'])->name('settings.index'); + Route::put('/settings', [SettingsController::class, 'update'])->name('settings.update'); + Route::post('/settings/check', [SettingsController::class, 'check'])->name('settings.check'); + Route::post('/settings/refresh', [SettingsController::class, 'refresh'])->name('settings.refresh'); +}); diff --git a/src/Modules/Sharing/LinkedInSharer.php b/src/Modules/Sharing/LinkedInSharer.php new file mode 100644 index 0000000..aaba8b9 --- /dev/null +++ b/src/Modules/Sharing/LinkedInSharer.php @@ -0,0 +1,203 @@ +setting('client_id') !== '' && $this->setting('client_secret') !== ''; + } + + public function missing(): string + { + return __('LinkedIn: client id and client secret'); + } + + public function connection(): ?SocialConnection + { + return SocialConnection::query()->find(self::NAME); + } + + public function accountName(): ?string + { + return $this->connection()?->account_name; + } + + public function authorizationUrl(string $state, string $redirectUri, string $verifier = ''): string + { + return $this->setting('auth_url').'/authorization?'.http_build_query([ + 'response_type' => 'code', + 'client_id' => $this->setting('client_id'), + 'redirect_uri' => $redirectUri, + 'state' => $state, + 'scope' => self::SCOPE, + ]); + } + + public function connect(string $code, string $redirectUri, string $verifier = ''): SocialConnection + { + if (! $this->canConnect()) { + throw new SharingException(__('The LinkedIn app is not set up: fill in its client id and client secret.')); + } + + $response = $this->send(fn () => Http::asForm()->acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20) + ->post($this->setting('auth_url').'/accessToken', [ + 'grant_type' => 'authorization_code', + 'code' => $code, + 'redirect_uri' => $redirectUri, + 'client_id' => $this->setting('client_id'), + 'client_secret' => $this->setting('client_secret'), + ])); + + $token = $response->json('access_token'); + + if ($response->failed() || ! is_string($token) || $token === '') { + throw new SharingException(__('LinkedIn did not give a token').$this->reason($response)); + } + + // Who the site will post as. + $me = $this->send(fn () => $this->api($token)->get($this->setting('userinfo_url'))); + $id = $me->json('sub'); + + if ($me->failed() || ! is_string($id) || $id === '') { + throw new SharingException(__('LinkedIn did not say whose account this is').$this->reason($me).' '.__('Check that the app has the product "Sign In with LinkedIn using OpenID Connect".')); + } + + $name = $me->json('name'); + $expiresIn = $response->json('expires_in'); + $refreshToken = $response->json('refresh_token'); + $refreshExpiresIn = $response->json('refresh_token_expires_in'); + + return SocialConnection::query()->updateOrCreate(['name' => self::NAME], [ + 'access_token' => $token, + 'expires_at' => is_numeric($expiresIn) ? now()->addSeconds((int) $expiresIn) : null, + 'refresh_token' => is_string($refreshToken) && $refreshToken !== '' ? $refreshToken : null, + 'refresh_token_expires_at' => is_numeric($refreshExpiresIn) ? now()->addSeconds((int) $refreshExpiresIn) : null, + 'account_id' => 'urn:li:person:'.$id, + 'account_name' => is_string($name) && $name !== '' ? mb_substr($name, 0, 200) : null, + ]); + } + + public function disconnect(): void + { + SocialConnection::query()->whereKey(self::NAME)->delete(); + } + + public function publish(ShareContent $content): SharedPost + { + $connection = $this->connection(); + + if (! $connection instanceof SocialConnection || ! is_string($connection->account_id)) { + throw new SharingException(__('LinkedIn is not connected.')); + } + + if ($connection->expires_at !== null && $connection->expires_at->isPast()) { + throw new SharingException(__('The connection with LinkedIn has expired. Connect again under Sharing.')); + } + + $token = $connection->access_token; + + $response = $this->send(fn () => $this->api($token)->post($this->setting('base_url').'/posts', [ + 'author' => $connection->account_id, + 'commentary' => self::escape($content->text), + 'visibility' => 'PUBLIC', + 'distribution' => ['feedDistribution' => 'MAIN_FEED', 'targetEntities' => [], 'thirdPartyDistributionChannels' => []], + 'content' => ['article' => ['source' => $content->url, 'title' => $content->title, 'description' => $content->description]], + 'lifecycleState' => 'PUBLISHED', + 'isReshareDisabledByAuthor' => false, + ])); + + if ($response->failed()) { + throw new SharingException(match ($response->status()) { + 401 => __('LinkedIn refused the connection. Connect again under Sharing.'), + 403 => __('LinkedIn does not allow this app to post. Check that it has the product "Share on LinkedIn".'), + 429 => __('LinkedIn says there were too many posts. Try again later.'), + default => __('LinkedIn did not accept the post').$this->reason($response), + }); + } + + $id = $response->header('x-restli-id'); + $id = $id !== '' ? $id : $response->json('id'); + + if (! is_string($id) || $id === '') { + // Posted, but LinkedIn did not say under which id: there is nothing to link to. + return new SharedPost('unknown'); + } + + return new SharedPost($id, 'https://www.linkedin.com/feed/update/'.rawurlencode($id).'/'); + } + + private function api(string $token): PendingRequest + { + return Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(30)->withToken($token)->withHeaders([ + 'LinkedIn-Version' => $this->setting('version'), + 'X-Restli-Protocol-Version' => '2.0.0', + ]); + } + + /** + * @param callable(): Response $request + */ + private function send(callable $request): Response + { + try { + return $request(); + } catch (ConnectionException) { + throw new SharingException(__('LinkedIn could not be reached.')); + } + } + + /** LinkedIn's own words about what went wrong, as the end of a sentence. Never holds a token. */ + private function reason(Response $response): string + { + $reason = $response->json('error_description') ?? $response->json('message'); + + return is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : " (HTTP {$response->status()})."; + } + + /** + * LinkedIn reads the text of a post as its "little text format", where these characters mean something (mentions, hashtags, + * templates). Escaped, they are shown as typed. + */ + public static function escape(string $text): string + { + return (string) preg_replace('/[\\\\|{}@\[\]()<>#*_~]/', '\\\\$0', $text); + } + + private function setting(string $key): string + { + $value = config("manager.sharing.linkedin.{$key}"); + + return is_string($value) ? trim($value) : ''; + } +} diff --git a/src/Modules/Sharing/SharingController.php b/src/Modules/Sharing/SharingController.php new file mode 100644 index 0000000..509462b --- /dev/null +++ b/src/Modules/Sharing/SharingController.php @@ -0,0 +1,157 @@ +names() as $name) { + $sharer = $sharers->for($name); + $connection = $sharer->connection(); + + $platforms[] = [ + 'platform' => $name, + 'label' => $sharer->label(), + 'can_connect' => $sharer->canConnect(), + 'missing' => $sharer->canConnect() ? null : $sharer->missing(), + 'connected' => $connection !== null, + 'account' => $sharer->accountName(), + 'expires_at' => $connection?->expires_at?->toIso8601String(), + 'callback_url' => route(Names::route('sharing.callback'), $name), + ]; + } + + $notice = (string) $request->query('notice'); + + return response()->json([ + 'live' => PostSharing::isLive(), + 'platforms' => $platforms, + 'notice' => in_array($notice, self::NOTICES, true) ? $notice : null, + 'shares' => PostShare::query()->with('post')->where('status', '!=', PostShare::PENDING)->latest('id')->limit(30)->get() + ->map(fn (PostShare $share) => [ + 'id' => $share->id, + 'post_id' => $share->post_id, + 'post_title' => $share->post?->title, + 'platform' => $share->platform, + 'status' => $share->status, + 'dry_run' => (bool) $share->dry_run, + 'url' => $share->external_url, + 'error' => $share->error, + 'at' => ($share->shared_at ?? $share->updated_at)?->toIso8601String(), + ])->values(), + ]); + } + + /** Sends the owner to the platform to give permission. */ + public function connect(Request $request, Sharers $sharers, string $platform): RedirectResponse + { + $sharer = $sharers->for($platform); + + if (! $sharer->canConnect()) { + return $this->back('failed'); + } + + // The platform sends this value back; it proves the answer belongs to this login session. + $state = Str::random(40); + // A second secret that never leaves this site until the code is traded in (PKCE). + $verifier = Str::random(64); + $request->session()->put(self::STATE_KEY.$platform, $state); + $request->session()->put(self::VERIFIER_KEY.$platform, $verifier); + + return redirect()->away($sharer->authorizationUrl($state, route(Names::route('sharing.callback'), $platform), $verifier)); + } + + /** Where the platform sends the owner back to, with a code or with an error. */ + public function callback(Request $request, Sharers $sharers, string $platform): RedirectResponse + { + $sharer = $sharers->for($platform); + $expected = $request->session()->pull(self::STATE_KEY.$platform); + $verifier = $request->session()->pull(self::VERIFIER_KEY.$platform); + $state = $request->query('state'); + + if (! is_string($expected) || ! is_string($state) || ! hash_equals($expected, $state)) { + return $this->back('state'); + } + + if ($request->query('error') !== null) { + return $this->back('denied'); + } + + $code = $request->query('code'); + + if (! is_string($code) || $code === '') { + return $this->back('failed'); + } + + try { + $sharer->connect($code, route(Names::route('sharing.callback'), $platform), is_string($verifier) ? $verifier : ''); + } catch (SharingException) { + return $this->back('failed'); + } + + return $this->back('connected'); + } + + public function disconnect(Sharers $sharers, string $platform): JsonResponse + { + $sharers->for($platform)->disconnect(); + + return response()->json(['ok' => true]); + } + + /** How a post stands on every platform, for the panel on its screen. */ + public function post(Post $post, PostSharing $sharing): JsonResponse + { + return response()->json(['live' => PostSharing::isLive(), 'platforms' => $sharing->overview($post)]); + } + + public function share(Request $request, Post $post, Sharers $sharers, PostSharing $sharing): JsonResponse + { + $request->validate(['platform' => ['required', 'string', 'max:20']]); + $platform = $request->string('platform')->toString(); + + abort_unless($sharers->has($platform), 422, __('This platform is not known.')); + + try { + $share = $sharing->shareNow($post, $platform); + } catch (SharingException $e) { + return response()->json(['message' => $e->getMessage()], 422); + } + + if ($share->status === PostShare::FAILED) { + return response()->json(['message' => (string) $share->error], 422); + } + + return response()->json(['ok' => true, 'dry_run' => (bool) $share->dry_run, 'url' => $share->external_url], 201); + } + + private function back(string $notice): RedirectResponse + { + return redirect(route(Names::route('sharing.index'), ['notice' => $notice])); + } +} diff --git a/src/Modules/Sharing/SharingModule.php b/src/Modules/Sharing/SharingModule.php new file mode 100644 index 0000000..8dd7d04 --- /dev/null +++ b/src/Modules/Sharing/SharingModule.php @@ -0,0 +1,80 @@ + 'Sharing', 'route' => Names::route('sharing.index'), 'permission' => 'sharing.view']]; + } + + /** @return array> what the settings screen can change */ + public function settings(): array + { + return [ + 'manager.sharing.live' => ['label' => 'Post for real', 'type' => 'toggle', 'group' => 'Sharing', 'help' => 'Off: a share is written down as a dry run and nothing is sent. Keep it off on a test site.', 'env' => 'MANAGER_SHARING_LIVE'], + 'manager.sharing.post_url' => ['label' => 'Address of a post', 'type' => 'url', 'group' => 'Sharing', 'sensitive' => true, 'help' => 'Where a post lives on the site, with {slug} for its address, for example https://example.test/blog/{slug}', 'env' => 'MANAGER_SHARING_POST_URL'], + 'manager.sharing.linkedin.client_id' => ['label' => 'LinkedIn: client id', 'type' => 'text', 'group' => 'Sharing', 'sensitive' => true, 'env' => 'MANAGER_LINKEDIN_CLIENT_ID'], + 'manager.sharing.linkedin.client_secret' => ['label' => 'LinkedIn: client secret', 'type' => 'secret', 'group' => 'Sharing', 'env' => 'MANAGER_LINKEDIN_CLIENT_SECRET'], + ]; + } + + public function actions(): array + { + return [ + 'sharing.connect' => ['Went to a social network to connect an account'], + 'sharing.callback' => ['Connected an account of a social network'], + 'sharing.disconnect' => ['Disconnected an account of a social network'], + 'sharing.share' => ['Shared a post on a social network'], + ]; + } + + public function views(): array + { + return ['sharing.index' => 'Opened the sharing screen', 'sharing.post' => 'Opened how a post is shared']; + } +} diff --git a/src/Modules/Sharing/migrations/2026_12_12_000001_create_manager_sharing_tables.php b/src/Modules/Sharing/migrations/2026_12_12_000001_create_manager_sharing_tables.php new file mode 100644 index 0000000..b1759ef --- /dev/null +++ b/src/Modules/Sharing/migrations/2026_12_12_000001_create_manager_sharing_tables.php @@ -0,0 +1,49 @@ +string('name', 20)->primary(); + $table->text('access_token'); + $table->dateTime('expires_at')->nullable(); + $table->text('refresh_token')->nullable(); + $table->dateTime('refresh_token_expires_at')->nullable(); + $table->string('account_id')->nullable(); + $table->string('account_name')->nullable(); + $table->json('details')->nullable(); + $table->timestamps(); + }); + + Tables::create(Names::table('post_shares'), function (Blueprint $table) { + $table->id(); + $table->unsignedBigInteger('post_id')->index(); + $table->string('platform', 20); + // pending, sharing, shared or failed + $table->string('status', 10)->default('pending'); + $table->text('text')->nullable(); + $table->string('external_id')->nullable(); + $table->string('external_url', 2048)->nullable(); + $table->string('error', 500)->nullable(); + // Written down as done, but nothing was sent (the site does not post for real). + $table->boolean('dry_run')->default(false); + $table->dateTime('shared_at')->nullable(); + $table->timestamps(); + + $table->index(['status', 'post_id']); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('post_shares')); + Schema::dropIfExists(Names::table('social_connections')); + } +}; diff --git a/src/Modules/Sharing/routes.php b/src/Modules/Sharing/routes.php new file mode 100644 index 0000000..f0d0f8e --- /dev/null +++ b/src/Modules/Sharing/routes.php @@ -0,0 +1,14 @@ +where(['platform' => '[a-z][a-z0-9_]{0,19}'])->group(function () { + Route::get('/', [SharingController::class, 'index'])->name('sharing.index')->middleware('can:sharing.view'); + Route::get('/{platform}/connect', [SharingController::class, 'connect'])->name('sharing.connect')->middleware('can:sharing.manage'); + Route::get('/{platform}/callback', [SharingController::class, 'callback'])->name('sharing.callback')->middleware('can:sharing.manage'); + Route::delete('/{platform}', [SharingController::class, 'disconnect'])->name('sharing.disconnect')->middleware('can:sharing.manage'); +}); + +Route::get('/posts/{post}/sharing', [SharingController::class, 'post'])->whereNumber('post')->name('sharing.post')->middleware('can:sharing.publish'); +Route::post('/posts/{post}/share', [SharingController::class, 'share'])->whereNumber('post')->name('sharing.share')->middleware('can:sharing.publish'); diff --git a/src/Modules/Statistics/BotRecorder.php b/src/Modules/Statistics/BotRecorder.php new file mode 100644 index 0000000..b1bb119 --- /dev/null +++ b/src/Modules/Statistics/BotRecorder.php @@ -0,0 +1,66 @@ +bot(); + + if ($bot === null) { + return; + } + + $day = now()->toDateString(); + $name = $bot['name'] ?? self::OTHER; + + if ($bot['kind'] === 'other' && $name !== self::OTHER && $this->isOneTooMany($table, $day, $name)) { + $name = self::OTHER; + } + + // One statement, so two requests at the same moment both count. + DB::table($table)->upsert( + [['day' => $day, 'bot' => $name, 'kind' => $bot['kind'], 'path' => Str::limit('/'.trim(Str::before($path, '?'), '/'), 255, ''), 'hits' => 1]], + ['day', 'bot', 'path'], + ['hits' => DB::raw($table.'.hits + 1')], + ); + } + + private function isOneTooMany(string $table, string $day, string $name): bool + { + $unknown = DB::table($table)->where('day', $day)->where('kind', 'other'); + + if ((clone $unknown)->where('bot', $name)->exists()) { + return false; + } + + return $unknown->distinct()->count('bot') >= self::UNKNOWN_NAMES_A_DAY; + } +} diff --git a/src/Modules/Statistics/CountBots.php b/src/Modules/Statistics/CountBots.php new file mode 100644 index 0000000..ae251fd --- /dev/null +++ b/src/Modules/Statistics/CountBots.php @@ -0,0 +1,51 @@ +counts($request, $response)) { + try { + $this->recorder->hit((string) $request->userAgent(), $request->getPathInfo()); + } catch (Throwable $e) { + // Counting must never be the reason a page is not served. + report($e); + } + } + + return $response; + } + + private function counts(Request $request, Response $response): bool + { + $name = $request->route()?->getName(); + + return $request->isMethod('GET') + && $response->getStatusCode() === 200 + && is_string($name) + && ! str_starts_with($name, Names::routePrefix()) + // The same promise as for visitors: who asks not to be followed is not counted at all. + && $request->header('Sec-GPC') !== '1' + && $request->header('DNT') !== '1'; + } +} diff --git a/src/Modules/Statistics/CountedPages.php b/src/Modules/Statistics/CountedPages.php new file mode 100644 index 0000000..c546a50 --- /dev/null +++ b/src/Modules/Statistics/CountedPages.php @@ -0,0 +1,59 @@ + */ + private array $resolvers = []; + + /** + * @param Closure(string): (array{path: string, post_id: int|null}|null) $resolver gets a path like `/about`, returns the page or null + */ + public function register(Closure $resolver): void + { + $this->resolvers[] = $resolver; + } + + /** @return array{path: string, post_id: int|null}|null */ + public function resolve(string $path): ?array + { + $pages = array_map(fn (string $page) => '/'.trim($page, '/'), (array) config('manager.statistics.pages', ['/'])); + + if (in_array($path, $pages, true)) { + return ['path' => $path, 'post_id' => null]; + } + + $postsPath = config('manager.statistics.posts_path'); + + if (is_string($postsPath) && $postsPath !== '' && Manager::enabled('posts')) { + $prefix = '/'.trim($postsPath, '/').'/'; + + if (str_starts_with($path, $prefix)) { + $post = Post::query()->published()->where('slug', substr($path, strlen($prefix)))->first(); + + return $post instanceof Post ? ['path' => $path, 'post_id' => $post->id] : null; + } + } + + foreach ($this->resolvers as $resolver) { + $page = $resolver($path); + + if ($page !== null) { + return $page; + } + } + + return null; + } +} diff --git a/src/Modules/Statistics/ForgetVisitorKeys.php b/src/Modules/Statistics/ForgetVisitorKeys.php new file mode 100644 index 0000000..a68a275 --- /dev/null +++ b/src/Modules/Statistics/ForgetVisitorKeys.php @@ -0,0 +1,20 @@ +line(sprintf('%d key(s) of past days deleted.', VisitorSalt::forgetOld())); + + return self::SUCCESS; + } +} diff --git a/src/Modules/Statistics/PulseController.php b/src/Modules/Statistics/PulseController.php new file mode 100644 index 0000000..d92ea17 --- /dev/null +++ b/src/Modules/Statistics/PulseController.php @@ -0,0 +1,58 @@ +` puts it in the page). */ + public function script(): BinaryFileResponse + { + return response()->file(__DIR__.'/../../../resources/js/pulse.js', [ + 'Content-Type' => 'application/javascript', + 'Cache-Control' => 'public, max-age=3600', + 'X-Content-Type-Options' => 'nosniff', + ]); + } + + public function view(Request $request, VisitRecorder $recorder): JsonResponse + { + // A browser that says its user does not want to be followed is not counted at all. + if ($request->header('Sec-GPC') === '1' || $request->header('DNT') === '1') { + return response()->json(['token' => null])->header('Cache-Control', 'no-store'); + } + + $countryHeader = config('manager.statistics.country_header'); + + $token = $recorder->view( + (string) $request->ip(), + (string) $request->userAgent(), + $request->string('path')->limit(300, '')->toString(), + [ + 'via' => $request->string('via')->limit(40, '')->toString(), + 'campaign' => $request->string('campaign')->limit(80, '')->toString(), + 'referrer' => $request->string('referrer')->limit(2000, '')->toString(), + // Only the country code is kept, and only when the site names the header that has it (Cloudflare: CF-IPCountry). + 'country' => is_string($countryHeader) && $countryHeader !== '' ? (string) $request->header($countryHeader, '') : '', + 'host' => $request->getHost(), + ], + ); + + return response()->json(['token' => $token])->header('Cache-Control', 'no-store'); + } + + public function leave(Request $request, VisitRecorder $recorder): Response + { + $recorder->leave($request->string('token')->limit(40, '')->toString(), $request->integer('seconds')); + + return response()->noContent()->header('Cache-Control', 'no-store'); + } +} diff --git a/src/Modules/Statistics/Source.php b/src/Modules/Statistics/Source.php new file mode 100644 index 0000000..b860bb7 --- /dev/null +++ b/src/Modules/Statistics/Source.php @@ -0,0 +1,122 @@ +, which + * is what tells a click on my own post apart from someone else's link. + */ +final class Source +{ + /** The platforms the site shares posts to; the values of ?via=. */ + public const PLATFORMS = ['linkedin', 'x', 'facebook', 'instagram']; + + /** Host (or the end of one) => platform. */ + private const SOCIAL = [ + 'linkedin.com' => 'linkedin', 'lnkd.in' => 'linkedin', 'com.linkedin.android' => 'linkedin', + 't.co' => 'x', 'x.com' => 'x', 'twitter.com' => 'x', 'com.twitter.android' => 'x', + 'facebook.com' => 'facebook', 'fb.com' => 'facebook', 'fb.me' => 'facebook', 'com.facebook.katana' => 'facebook', + 'instagram.com' => 'instagram', 'com.instagram.android' => 'instagram', + 'threads.net' => 'threads', 'threads.com' => 'threads', 'bsky.app' => 'bluesky', 'reddit.com' => 'reddit', + 'youtube.com' => 'youtube', 'youtu.be' => 'youtube', 'news.ycombinator.com' => 'hackernews', + 'tweakers.net' => 'tweakers', + ]; + + /** Host (or the end of one) => search engine. */ + private const SEARCH = [ + 'bing.com' => 'bing', 'duckduckgo.com' => 'duckduckgo', 'ecosia.org' => 'ecosia', + 'startpage.com' => 'startpage', 'search.brave.com' => 'brave', 'yandex.com' => 'yandex', 'yandex.ru' => 'yandex', + 'baidu.com' => 'baidu', 'kagi.com' => 'kagi', 'qwant.com' => 'qwant', 'search.yahoo.com' => 'yahoo', + 'com.google.android.googlequicksearchbox' => 'google', + ]; + + private function __construct( + public readonly string $channel, + public readonly ?string $source, + public readonly ?string $referrerHost, + ) {} + + /** + * @param string $via the ?via= of the address the visitor arrived on + * @param string $campaign its ?utm_source= + * @param string $referrer the address of the page that linked here + * @param string $ownHost this site's own host: a link from the site itself is no source + */ + public static function of(string $via, string $campaign, string $referrer, string $ownHost): self + { + $host = self::host($referrer); + if ($host === self::bare($ownHost)) { + $host = null; + } + + $via = strtolower(trim($via)); + if (in_array($via, self::PLATFORMS, true)) { + return new self('share', $via, $host); + } + + $campaign = strtolower(trim($campaign)); + if ($campaign !== '' && preg_match('/^[a-z0-9._-]{1,80}$/', $campaign) === 1) { + $platform = self::SOCIAL[$campaign.'.com'] ?? ($campaign === 'twitter' ? 'x' : null); + + return $platform !== null ? new self('social', $platform, $host) : new self('campaign', $campaign, $host); + } + + if ($host === null) { + return new self('direct', null, null); + } + + if (($platform = self::match($host, self::SOCIAL)) !== null) { + return new self('social', $platform, $host); + } + + // google.com, google.nl, google.co.uk ... + if (preg_match('/(^|\.)google\.[a-z.]{2,6}$/', $host) === 1) { + return new self('search', 'google', $host); + } + + if (($engine = self::match($host, self::SEARCH)) !== null) { + return new self('search', $engine, $host); + } + + return new self('referral', $host, $host); + } + + /** The host of an address, lower case and without "www."; null when there is none. */ + private static function host(string $address): ?string + { + $address = trim($address); + if ($address === '') { + return null; + } + + $host = parse_url($address, PHP_URL_HOST); + if (! is_string($host) || $host === '' || strlen($host) > 255) { + return null; + } + + return self::bare($host); + } + + private static function bare(string $host): string + { + $host = strtolower($host); + + return str_starts_with($host, 'www.') ? substr($host, 4) : $host; + } + + /** @param array $known */ + private static function match(string $host, array $known): ?string + { + foreach ($known as $end => $name) { + if ($host === $end || str_ends_with($host, '.'.$end)) { + return $name; + } + } + + return null; + } +} diff --git a/src/Modules/Statistics/Statistics.php b/src/Modules/Statistics/Statistics.php new file mode 100644 index 0000000..9ce0f16 --- /dev/null +++ b/src/Modules/Statistics/Statistics.php @@ -0,0 +1,746 @@ + 'Today', 'week' => 'This week', '7d' => 'Last 7 days', 'month' => 'This month', '30d' => 'Last 30 days', + '12m' => 'Last 12 months', 'all' => 'All time', + ]; + + /** A period between two dates of one's own choosing (`from` and `to`). */ + public const CUSTOM = 'custom'; + + /** What a period can be put next to: the one before it, the same days a year earlier, days of one's own choosing, or nothing. */ + public const COMPARISONS = ['previous' => 'The period before', 'year' => 'A year earlier', 'custom' => 'Another period', 'none' => 'Nothing']; + + /** What can be downloaded as a CSV file. */ + public const EXPORTS = ['days' => 'Per day', 'pages' => 'Pages', 'sources' => 'Sources', 'bots' => 'Bots']; + + public const DEFAULT_RANGE = '30d'; + + private const WEEKDAYS = [1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat', 7 => 'Sun']; + + /** + * Everything the statistics page shows for one period. + * + * @param array $choice `from` and `to` for a period of one's own, `compare` (see COMPARISONS) and `compare_from` + * @return array + */ + public function report(string $range, array $choice = []): array + { + $period = $this->period($range, $choice); + $from = $period['from']; + $to = $period['to']; + $compares = $period['previous_from'] !== null && $period['previous_to'] !== null; + + return [ + 'range' => [ + 'key' => $period['key'], + 'label' => $period['label'], + 'from' => $from, + 'to' => $to, + 'bucket' => $period['bucket'], + 'compare' => $period['compare'], + 'compared_to' => $period['compared_to'], + 'previous_from' => $period['previous_from'], + 'previous_to' => $period['previous_to'], + ], + 'ranges' => $this->ranges(), + 'comparisons' => self::COMPARISONS, + 'exports' => self::EXPORTS, + 'totals' => $this->totals($from, $to), + 'previous' => $compares ? $this->totals((string) $period['previous_from'], (string) $period['previous_to'], $period['previous_until_hour']) : null, + 'series' => $this->series($from, $to, $period['bucket']), + // The other period, step by step: the first step of it next to the first step of this one. + 'previous_series' => $compares ? $this->series((string) $period['previous_from'], (string) $period['previous_to'], $period['bucket']) : null, + 'pages' => $this->pages($from, $to), + 'posts' => $this->posts($from, $to), + 'channels' => $this->grouped($from, $to, 'channel', 10), + 'platforms' => $this->platforms($from, $to), + 'sources' => $this->sources($from, $to), + 'heatmap' => $this->heatmap($from, $to), + 'countries' => $this->grouped($from, $to, 'country', 8), + 'devices' => $this->grouped($from, $to, 'device', 5), + 'browsers' => $this->grouped($from, $to, 'browser', 6), + 'systems' => $this->grouped($from, $to, 'os', 6), + // Programs have no hour, so "today until now" has nothing fair to stand next to. + 'bots' => $this->bots($from, $to, $compares && $period['previous_until_hour'] === null ? [(string) $period['previous_from'], (string) $period['previous_to']] : null), + ]; + } + + /** + * The few numbers of a period that the screen of the owner shows (`OwnerNumbers`): the + * totals next to the period before, the visitors step by step, and the pages, articles + * and ways in that were used most. + * + * @return array{from: string, to: string, bucket: string, totals: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}, previous: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}|null, series: list, pages: list, posts: list, channels: list} + */ + public function brief(string $range): array + { + $period = $this->period($range); + $from = $period['from']; + $to = $period['to']; + + return [ + 'from' => $from, + 'to' => $to, + 'bucket' => $period['bucket'], + 'totals' => $this->totals($from, $to), + 'previous' => $period['previous_from'] !== null && $period['previous_to'] !== null + ? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour']) + : null, + 'series' => $this->series($from, $to, $period['bucket']), + 'pages' => $this->pages($from, $to, 6), + 'posts' => $this->posts($from, $to), + 'channels' => $this->grouped($from, $to, 'channel', 6), + ]; + } + + /** + * One list of the period as rows for a CSV file. An unknown list gives the days. + * + * @param array $choice + * @return array{filename: string, header: list, rows: list>} + */ + public function export(string $sheet, string $range, array $choice = []): array + { + $period = $this->period($range, $choice); + $from = $period['from']; + $to = $period['to']; + $sheet = array_key_exists($sheet, self::EXPORTS) ? $sheet : 'days'; + + [$header, $rows] = match ($sheet) { + 'pages' => [['Page', 'Title', 'Views', 'Average seconds on the page'], array_map( + fn (array $page) => [$page['path'], $page['title'] ?? '', $page['views'], $page['average_seconds']], + $this->pages($from, $to, null), + )], + 'sources' => [['Source', 'Channel', 'Visits'], array_map( + fn (array $source) => [$source['name'], $source['channel'], $source['visits']], + $this->sources($from, $to, null), + )], + 'bots' => [['Program', 'Kind', 'Page', 'Requests'], $this->botRows($from, $to)], + default => [['Day', 'Visitors', 'Visits', 'Page views', 'Requests by programs'], array_map( + fn (array $day) => [$day['key'], $day['visitors'], $day['visits'], $day['page_views'], $day['bot_hits']], + $this->series($from, $to, 'day'), + )], + }; + + return ['filename' => "statistics-{$sheet}-{$from}-to-{$to}.csv", 'header' => $header, 'rows' => $rows]; + } + + /** + * The short version for the dashboard: today, the last 7 and the last 30 days, + * each next to the period before it, and the visitors per day of the last 30 days. + * + * @return array{periods: list, days: list} + */ + public function summary(): array + { + $periods = []; + + foreach (['today', '7d', '30d'] as $range) { + $period = $this->period($range); + $now = $this->totals($period['from'], $period['to']); + $before = $period['previous_from'] !== null && $period['previous_to'] !== null + ? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour']) + : null; + + $periods[] = [ + 'key' => $range, + 'label' => $period['label'], + 'visitors' => $now['visitors'], + 'page_views' => $now['page_views'], + 'previous_visitors' => $before['visitors'] ?? 0, + ]; + } + + $month = $this->period('30d'); + + return ['periods' => $periods, 'days' => $this->series($month['from'], $month['to'], 'day')]; + } + + /** + * A period as dates, with the period it is compared with. An unknown key + * gives the default period. + * + * @param array $choice + * @return array{key: string, label: string, from: string, to: string, bucket: string, compare: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null} + */ + private function period(string $range, array $choice = []): array + { + $period = $this->dates($range, $choice); + $compare = $choice['compare'] ?? 'previous'; + $nothing = ['compare' => 'none', 'compared_to' => null, 'previous_from' => null, 'previous_to' => null, 'previous_until_hour' => null]; + + // All time has nothing before it. + if ($period['previous_from'] === null || $compare === 'none') { + return $nothing + $period; + } + + $from = CarbonImmutable::parse($period['from']); + $to = CarbonImmutable::parse($period['to']); + + if ($compare === 'year') { + return [ + 'compare' => 'year', 'compared_to' => 'the same days a year earlier', + 'previous_from' => $from->subYearNoOverflow()->toDateString(), 'previous_to' => $to->subYearNoOverflow()->toDateString(), + ] + $period; + } + + $start = $compare === 'custom' ? self::date($choice['compare_from'] ?? '') : null; + + if ($start !== null) { + // As many days as the period itself, from the chosen day on. + $end = $start->addDays((int) $from->diffInDays($to)); + + return [ + 'compare' => 'custom', 'compared_to' => self::span($start, $end), + 'previous_from' => $start->toDateString(), 'previous_to' => $end->toDateString(), + ] + $period; + } + + return ['compare' => 'previous'] + $period; + } + + /** + * The dates of a period, and of the period before it. + * + * @param array $choice + * @return array{key: string, label: string, from: string, to: string, bucket: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null} + */ + private function dates(string $range, array $choice): array + { + $today = CarbonImmutable::now()->startOfDay(); + $day = fn (CarbonImmutable $date): string => $date->toDateString(); + + if (preg_match('/^\d{4}$/', $range) === 1 && in_array((int) $range, $this->years(), true)) { + $start = $today->setDate((int) $range, 1, 1); + + return [ + 'key' => $range, 'label' => $range, 'from' => $day($start), 'to' => $day($start->endOfYear()), 'bucket' => 'month', + 'compared_to' => (string) ((int) $range - 1), + 'previous_from' => $day($start->subYear()), 'previous_to' => $day($start->subDay()), 'previous_until_hour' => null, + ]; + } + + $from = self::date($choice['from'] ?? ''); + $to = self::date($choice['to'] ?? ''); + + if ($range === self::CUSTOM && $from !== null && $to !== null) { + // The wrong way round, or into the future: still a period. + [$from, $to] = $from <= $to ? [$from, $to] : [$to, $from]; + $to = $to->min($today); + $from = $from->min($to); + $days = (int) $from->diffInDays($to) + 1; + + return [ + 'key' => self::CUSTOM, 'label' => self::span($from, $to), 'from' => $day($from), 'to' => $day($to), + 'bucket' => match (true) { + $days === 1 => 'hour', + $days <= 92 => 'day', + $days <= 1100 => 'month', + default => 'year', + }, + 'compared_to' => $days === 1 ? 'the day before' : "the {$days} days before", + 'previous_from' => $day($from->subDays($days)), 'previous_to' => $day($from->subDay()), 'previous_until_hour' => null, + ]; + } + + if (! array_key_exists($range, self::RANGES)) { + $range = self::DEFAULT_RANGE; + } + + $period = ['key' => $range, 'label' => self::RANGES[$range], 'to' => $day($today), 'previous_until_hour' => null]; + $monday = $today->startOfWeek(CarbonImmutable::MONDAY); + $lastMonth = $today->startOfMonth()->subMonthNoOverflow(); + + return match ($range) { + // Today so far, next to yesterday up to the same hour: a fair comparison at any time of day. + 'today' => ['previous_until_hour' => CarbonImmutable::now()->hour] + $period + [ + 'from' => $day($today), 'bucket' => 'hour', 'compared_to' => 'yesterday at this time', + 'previous_from' => $day($today->subDay()), 'previous_to' => $day($today->subDay()), + ], + // A week and a month that are still running stand next to as many days of the one before. + 'week' => $period + [ + 'from' => $day($monday), 'bucket' => 'day', 'compared_to' => 'last week up to the same day', + 'previous_from' => $day($monday->subWeek()), 'previous_to' => $day($today->subWeek()), + ], + 'month' => $period + [ + 'from' => $day($today->startOfMonth()), 'bucket' => 'day', 'compared_to' => 'last month up to the same day', + 'previous_from' => $day($lastMonth), 'previous_to' => $day($lastMonth->setDay(min($today->day, $lastMonth->daysInMonth))), + ], + '7d' => $period + [ + 'from' => $day($today->subDays(6)), 'bucket' => 'day', 'compared_to' => 'the 7 days before', + 'previous_from' => $day($today->subDays(13)), 'previous_to' => $day($today->subDays(7)), + ], + '12m' => $period + [ + 'from' => $day($today->startOfMonth()->subMonthsNoOverflow(11)), 'bucket' => 'month', 'compared_to' => 'the 12 months before', + 'previous_from' => $day($today->startOfMonth()->subMonthsNoOverflow(23)), + 'previous_to' => $day($today->startOfMonth()->subMonthsNoOverflow(11)->subDay()), + ], + 'all' => $period + [ + 'from' => $this->firstDay() ?? $day($today), + // Months while that still fits on the screen, years after that. + 'bucket' => CarbonImmutable::parse($this->firstDay() ?? $day($today))->diffInMonths($today) > 24 ? 'year' : 'month', + 'compared_to' => null, 'previous_from' => null, 'previous_to' => null, + ], + default => $period + [ + 'from' => $day($today->subDays(29)), 'bucket' => 'day', 'compared_to' => 'the 30 days before', + 'previous_from' => $day($today->subDays(59)), 'previous_to' => $day($today->subDays(30)), + ], + }; + } + + /** A date as 'Y-m-d' from the address bar, or null when it is not one. */ + private static function date(string $value): ?CarbonImmutable + { + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + + $date = CarbonImmutable::createFromFormat('!Y-m-d', $value); + + // "2026-02-31" is read as the 3rd of March: not what was typed, so not a date. + return $date instanceof CarbonImmutable && $date->toDateString() === $value && $date->year >= 2000 ? $date : null; + } + + /** "1 Oct – 31 Oct 2026" */ + private static function span(CarbonImmutable $from, CarbonImmutable $to): string + { + if ($from->equalTo($to)) { + return $from->format('j M Y'); + } + + return $from->format($from->year === $to->year ? 'j M' : 'j M Y').' – '.$to->format('j M Y'); + } + + /** + * The periods to choose from: the fixed ones and every year there are visits of. + * + * @return list + */ + private function ranges(): array + { + $ranges = []; + foreach (self::RANGES as $key => $label) { + $ranges[] = ['key' => $key, 'label' => $label]; + } + foreach (array_reverse($this->years()) as $year) { + $ranges[] = ['key' => (string) $year, 'label' => (string) $year]; + } + + return $ranges; + } + + /** @return list every year from the first visit until now */ + private function years(): array + { + $first = $this->firstDay(); + + return $first === null ? [] : range((int) substr($first, 0, 4), CarbonImmutable::now()->year); + } + + private function firstDay(): ?string + { + $first = DB::table($this->table('visits'))->min('day'); + + return is_string($first) ? substr($first, 0, 10) : null; + } + + /** + * @param int|null $untilHour only count visits that started in or before this hour of the day + * @return array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int} + */ + private function totals(string $from, string $to, ?int $untilHour = null): array + { + $row = $this->visits($from, $to) + ->when($untilHour !== null, fn (Builder $query) => $query->where('hour', '<=', $untilHour)) + ->selectRaw('count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views') + ->selectRaw('sum(seconds) as seconds, sum(case when page_views <= 1 then 1 else 0 end) as bounces') + ->first(); + + $visits = self::number($row->visits ?? 0); + + return [ + 'visitors' => self::number($row->visitors ?? 0), + 'visits' => $visits, + 'page_views' => self::number($row->page_views ?? 0), + 'average_seconds' => $visits > 0 ? (int) round(self::number($row->seconds ?? 0) / $visits) : 0, + // Visits that ended after a single page, as a percentage. + 'bounce_rate' => $visits > 0 ? (int) round(100 * self::number($row->bounces ?? 0) / $visits) : 0, + ]; + } + + /** + * Visitors, visits and page views through time, one entry per hour, day, month + * or year. Every step of the period is there, also the ones without visits. + * + * `bot_hits` are the requests by programs; those have no hour, so per hour it stays 0. + * + * @return list + */ + private function series(string $from, string $to, string $bucket): array + { + $column = $bucket === 'hour' ? 'hour' : 'day'; + $rows = $this->visits($from, $to) + ->selectRaw("{$column} as step, count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views") + ->groupBy($column) + ->get(); + + $steps = []; + $start = CarbonImmutable::parse($from); + $end = CarbonImmutable::parse($to); + + if ($bucket === 'hour') { + foreach (range(0, 23) as $hour) { + $steps[(string) $hour] = sprintf('%02d:00', $hour); + } + } elseif ($bucket === 'day') { + for ($date = $start; $date <= $end; $date = $date->addDay()) { + $steps[$date->toDateString()] = $date->format('j M'); + } + } elseif ($bucket === 'month') { + for ($date = $start->startOfMonth(); $date <= $end; $date = $date->addMonth()) { + $steps[$date->format('Y-m')] = $date->format('M Y'); + } + } else { + foreach (range($start->year, $end->year) as $year) { + $steps[(string) $year] = (string) $year; + } + } + + $series = []; + foreach ($steps as $key => $label) { + $series[(string) $key] = ['key' => (string) $key, 'label' => $label, 'visitors' => 0, 'visits' => 0, 'page_views' => 0, 'bot_hits' => 0]; + } + + $keyOf = fn (mixed $step): string => match ($bucket) { + 'hour' => (string) (int) (is_scalar($step) ? $step : 0), + 'day' => substr(is_scalar($step) ? (string) $step : '', 0, 10), + 'month' => substr(is_scalar($step) ? (string) $step : '', 0, 7), + default => substr(is_scalar($step) ? (string) $step : '', 0, 4), + }; + + foreach ($rows as $row) { + $key = $keyOf($row->step); + + if (isset($series[$key])) { + $series[$key]['visitors'] += self::number($row->visitors); + $series[$key]['visits'] += self::number($row->visits); + $series[$key]['page_views'] += self::number($row->page_views); + } + } + + if ($bucket !== 'hour') { + foreach ($this->botHits($from, $to)->selectRaw('day as step, sum(hits) as hits')->groupBy('day')->get() as $row) { + $key = $keyOf($row->step); + + if (isset($series[$key])) { + $series[$key]['bot_hits'] += self::number($row->hits); + } + } + } + + return array_values($series); + } + + /** + * The pages that were looked at most, with the average time on the page. + * + * @return list + */ + private function pages(string $from, string $to, ?int $limit = 10): array + { + $rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to]) + ->selectRaw('path, max(post_id) as post_id, count(*) as views, sum(seconds) as seconds') + ->groupBy('path')->orderByDesc('views')->orderBy('path') + ->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get(); + + $titles = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->filter()->all())->pluck('title', 'id') : collect(); + + $pages = []; + foreach ($rows as $row) { + $views = self::number($row->views); + $title = $titles->get(self::number($row->post_id)); + + $pages[] = [ + 'path' => is_string($row->path) ? $row->path : '', + 'title' => is_string($title) ? $title : null, + 'views' => $views, + 'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0, + ]; + } + + return $pages; + } + + /** + * The posts that were read most. + * + * @return list + */ + private function posts(string $from, string $to): array + { + $rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to])->whereNotNull('post_id') + ->selectRaw('post_id, count(*) as views, sum(seconds) as seconds') + ->groupBy('post_id')->orderByDesc('views')->limit(10)->get(); + + $found = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->all())->get()->keyBy('id') : collect(); + + $posts = []; + foreach ($rows as $row) { + $post = $found->get(self::number($row->post_id)); + $views = self::number($row->views); + + if ($post instanceof Post) { + $posts[] = [ + 'title' => $post->title, + 'slug' => $post->slug, + 'views' => $views, + 'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0, + ]; + } + } + + return $posts; + } + + /** + * Visits counted by one column of `visits`, most first. + * + * @return list + */ + private function grouped(string $from, string $to, string $column, int $limit): array + { + $rows = $this->visits($from, $to)->whereNotNull($column) + ->select("{$column} as name")->selectRaw('count(*) as visits') + ->groupBy($column)->orderByDesc('visits')->orderBy($column)->limit($limit)->get(); + + $result = []; + foreach ($rows as $row) { + $result[] = ['name' => is_scalar($row->name) ? (string) $row->name : '', 'visits' => self::number($row->visits)]; + } + + return $result; + } + + /** + * The four platforms the site shares posts to: how many visits came from each, + * and how many of those through a link the site posted itself. + * + * @return list + */ + private function platforms(string $from, string $to): array + { + $rows = $this->visits($from, $to)->whereIn('source', Source::PLATFORMS)->whereIn('channel', ['share', 'social']) + ->selectRaw('source, channel, count(*) as visits')->groupBy('source', 'channel')->get(); + + $platforms = []; + foreach (Source::PLATFORMS as $platform) { + $platforms[$platform] = ['name' => $platform, 'visits' => 0, 'shared' => 0]; + } + + foreach ($rows as $row) { + $name = is_string($row->source) ? $row->source : ''; + if (isset($platforms[$name])) { + $platforms[$name]['visits'] += self::number($row->visits); + $platforms[$name]['shared'] += $row->channel === 'share' ? self::number($row->visits) : 0; + } + } + + return array_values($platforms); + } + + /** + * The sites, search engines and platforms that sent visitors, most first. + * + * @return list + */ + private function sources(string $from, string $to, ?int $limit = 12): array + { + $rows = $this->visits($from, $to)->whereNotNull('source') + ->selectRaw('source, channel, count(*) as visits') + ->groupBy('source', 'channel')->orderByDesc('visits')->orderBy('source') + ->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get(); + + $sources = []; + foreach ($rows as $row) { + $sources[] = [ + 'name' => is_string($row->source) ? $row->source : '', + 'channel' => is_string($row->channel) ? $row->channel : '', + 'visits' => self::number($row->visits), + ]; + } + + return $sources; + } + + /** + * The busy moments: visits per weekday and hour of the day. + * + * @return list}> + */ + private function heatmap(string $from, string $to): array + { + $rows = $this->visits($from, $to)->selectRaw('weekday, hour, count(*) as visits')->groupBy('weekday', 'hour')->get(); + + $grid = []; + foreach (self::WEEKDAYS as $number => $name) { + $grid[$number] = ['day' => $name, 'hours' => array_fill(0, 24, 0)]; + } + + foreach ($rows as $row) { + $weekday = self::number($row->weekday); + $hour = self::number($row->hour); + if (isset($grid[$weekday]) && $hour >= 0 && $hour <= 23) { + $grid[$weekday]['hours'][$hour] = self::number($row->visits); + } + } + + return array_values($grid); + } + + /** + * The programs that fetched pages (search engines, AI crawlers, link previews, + * scripts ...): how often in all, which ones, what kind, and which pages. + * They are counted on the server (BotRecorder) and are never part of the + * visitors above. + * + * @param array{0: string, 1: string}|null $before the period to compare the total with + * @return array{total: int, previous: int|null, names: list, kinds: list, pages: list} + */ + private function bots(string $from, string $to, ?array $before): array + { + $names = []; + foreach ($this->botHits($from, $to)->selectRaw('bot, kind, sum(hits) as hits') + ->groupBy('bot', 'kind')->orderByDesc('hits')->orderBy('bot')->limit(15)->get() as $row) { + $names[] = ['name' => is_string($row->bot) ? $row->bot : '', 'kind' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)]; + } + + $kinds = []; + foreach ($this->botHits($from, $to)->selectRaw('kind, sum(hits) as hits') + ->groupBy('kind')->orderByDesc('hits')->orderBy('kind')->get() as $row) { + $kinds[] = ['name' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)]; + } + + $pages = []; + foreach ($this->botHits($from, $to)->selectRaw('path, sum(hits) as hits') + ->groupBy('path')->orderByDesc('hits')->orderBy('path')->limit(10)->get() as $row) { + $pages[] = ['path' => is_string($row->path) ? $row->path : '', 'hits' => self::number($row->hits)]; + } + + return [ + 'total' => self::number($this->botHits($from, $to)->sum('hits')), + 'previous' => $before === null ? null : self::number($this->botHits($before[0], $before[1])->sum('hits')), + 'names' => $names, + 'kinds' => $kinds, + 'pages' => $pages, + ]; + } + + /** + * Every program and page of the period, for the export. + * + * @return list> + */ + private function botRows(string $from, string $to): array + { + $rows = []; + foreach ($this->botHits($from, $to)->selectRaw('bot, kind, path, sum(hits) as hits') + ->groupBy('bot', 'kind', 'path')->orderByDesc('hits')->orderBy('bot')->orderBy('path')->get() as $row) { + $rows[] = [is_string($row->bot) ? $row->bot : '', is_string($row->kind) ? $row->kind : '', is_string($row->path) ? $row->path : '', self::number($row->hits)]; + } + + return $rows; + } + + /** + * How often each post was opened, since the beginning, and how those readers + * got to it. Someone who landed on the post is counted under the way they + * arrived (a shared post on LinkedIn, Google, direct ...); someone who was on + * another page of the site first and clicked through is counted as "internal". + * + * @param int|null $postId only this post + * @return array}> by post id + */ + public function readers(?int $postId = null): array + { + $views = $this->table('page_views'); + $visits = $this->table('visits'); + $rows = DB::table($views) + ->join($visits, "{$visits}.id", '=', "{$views}.visit_id") + ->whereNotNull("{$views}.post_id") + ->when($postId !== null, fn (Builder $query) => $query->where("{$views}.post_id", $postId)) + ->selectRaw("{$views}.post_id as post, case when {$visits}.entry_path = {$views}.path then {$visits}.channel else 'internal' end as arrived_by") + ->selectRaw("case when {$visits}.entry_path = {$views}.path then {$visits}.source else null end as arrived_from") + ->selectRaw("count(*) as views, sum({$views}.seconds) as seconds") + ->groupBy('post', 'arrived_by', 'arrived_from') + ->orderByDesc('views')->orderBy('arrived_by')->orderBy('arrived_from') + ->get(); + + $posts = []; + $seconds = []; + + foreach ($rows as $row) { + $id = self::number($row->post); + $views = self::number($row->views); + + $posts[$id] ??= ['views' => 0, 'average_seconds' => 0, 'sources' => []]; + $posts[$id]['views'] += $views; + $posts[$id]['sources'][] = [ + 'channel' => is_string($row->arrived_by) ? $row->arrived_by : '', + 'name' => is_string($row->arrived_from) ? $row->arrived_from : null, + 'views' => $views, + ]; + $seconds[$id] = ($seconds[$id] ?? 0) + self::number($row->seconds); + } + + foreach ($posts as $id => $post) { + $posts[$id]['average_seconds'] = $post['views'] > 0 ? (int) round(($seconds[$id] ?? 0) / $post['views']) : 0; + } + + return $posts; + } + + private function visits(string $from, string $to): Builder + { + return DB::table($this->table('visits'))->whereBetween('day', [$from, $to]); + } + + private function botHits(string $from, string $to): Builder + { + return DB::table($this->table('bot_hits'))->whereBetween('day', [$from, $to]); + } + + /** A count or sum as the database gives it (int, numeric string or null). */ + private function table(string $name): string + { + return Names::table($name); + } + + private static function number(mixed $value): int + { + return is_numeric($value) ? (int) $value : 0; + } +} diff --git a/src/Modules/Statistics/StatisticsController.php b/src/Modules/Statistics/StatisticsController.php new file mode 100644 index 0000000..c5dbdb1 --- /dev/null +++ b/src/Modules/Statistics/StatisticsController.php @@ -0,0 +1,71 @@ +json($statistics->report($this->range($request), $this->choice($request))); + } + + /** One list of the period that is on the screen, as a CSV file. */ + public function export(Request $request, Statistics $statistics): StreamedResponse + { + $export = $statistics->export($request->string('sheet')->toString(), $this->range($request), $this->choice($request)); + + return response()->streamDownload(function () use ($export) { + $out = fopen('php://output', 'w'); + + if ($out === false) { + return; + } + + // The mark that tells a spreadsheet the file is UTF-8. + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, $export['header'], ',', '"', ''); + + foreach ($export['rows'] as $row) { + fputcsv($out, array_map(self::cell(...), $row), ',', '"', ''); + } + + fclose($out); + }, $export['filename'], ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store']); + } + + /** + * A page address, a referring site and the name of a program come from visitors. A spreadsheet + * runs a cell that starts like a formula, so such a cell gets a quote in front and is shown as + * the text it is. + */ + private static function cell(string|int $value): string|int + { + return is_string($value) && preg_match('/^[=+\-@\t\r]/', $value) === 1 ? "'".$value : $value; + } + + private function range(Request $request): string + { + return $request->string('range', Statistics::DEFAULT_RANGE)->toString(); + } + + /** @return array */ + private function choice(Request $request): array + { + $choice = []; + + foreach (['from', 'to', 'compare', 'compare_from'] as $key) { + $choice[$key] = $request->string($key)->limit(20, '')->toString(); + } + + // Nothing chosen is the period before, not "nothing". + if ($choice['compare'] === '') { + unset($choice['compare']); + } + + return $choice; + } +} diff --git a/src/Modules/Statistics/StatisticsModule.php b/src/Modules/Statistics/StatisticsModule.php new file mode 100644 index 0000000..cb610d4 --- /dev/null +++ b/src/Modules/Statistics/StatisticsModule.php @@ -0,0 +1,85 @@ + 'Statistics', 'route' => Names::route('statistics.index'), 'permission' => 'statistics.view']]; + } + + public function commands(): array + { + return [ForgetVisitorKeys::class]; + } + + public function actions(): array + { + return ['statistics.export' => ['Exported the statistics', ['sheet']]]; + } + + public function views(): array + { + return ['statistics.index' => 'Opened the statistics']; + } + + public function boot(): void + { + app()->singleton(CountedPages::class); + + // A person opens a few pages a minute; this only stops someone from flooding the statistics. + RateLimiter::for('manager-pulse', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.statistics.per_minute', 120)))->by((string) $request->ip())); + + // Programs never run the script that reports a view, so the server counts the pages it serves them. + // Through the kernel: it copies its own groups to the router when a request starts. + if (config('manager.statistics.count_bots') && method_exists($kernel = app(Kernel::class), 'appendMiddlewareToGroup')) { + $kernel->appendMiddlewareToGroup('web', CountBots::class); + } + + // Without yesterday's key, yesterday's visitor codes can no longer be traced back. + if (app()->runningInConsole()) { + app()->afterResolving(Schedule::class, fn (Schedule $schedule) => $schedule->command(ForgetVisitorKeys::class)->dailyAt('00:05')); + } + } +} diff --git a/src/Modules/Statistics/VisitRecorder.php b/src/Modules/Statistics/VisitRecorder.php new file mode 100644 index 0000000..1017a5e --- /dev/null +++ b/src/Modules/Statistics/VisitRecorder.php @@ -0,0 +1,168 @@ +page($path); + + if ($agent->isBot() || $page === null) { + return null; + } + + $now = now(); + $hash = hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent); + + $visit = Visit::query() + ->where('visitor_hash', $hash) + ->where('last_seen_at', '>=', $now->copy()->subMinutes(self::VISIT_GAP_MINUTES)) + ->latest('id') + ->first(); + + if (! $visit instanceof Visit) { + $source = Source::of($arrival['via'] ?? '', $arrival['campaign'] ?? '', $arrival['referrer'] ?? '', $arrival['host'] ?? ''); + $country = strtoupper(trim($arrival['country'] ?? '')); + + $visit = Visit::query()->create([ + 'visitor_hash' => $hash, + 'started_at' => $now, + 'last_seen_at' => $now, + 'day' => $now->toDateString(), + 'hour' => $now->hour, + 'weekday' => $now->dayOfWeekIso, + 'entry_path' => $page['path'], + 'exit_path' => $page['path'], + 'channel' => $source->channel, + 'source' => $source->source, + 'referrer_host' => $source->referrerHost, + // Cloudflare says XX for unknown and T1 for Tor: neither is a country. + 'country' => preg_match('/^[A-Z]{2}$/', $country) === 1 && ! in_array($country, ['XX', 'T1'], true) ? $country : null, + 'device' => $agent->device(), + 'browser' => $agent->browser(), + 'os' => $agent->os(), + ]); + } + + $token = Str::random(40); + + PageView::query()->create([ + 'token' => $token, + 'visit_id' => $visit->id, + 'path' => $page['path'], + 'post_id' => $page['post_id'], + 'viewed_at' => $now, + 'day' => $now->toDateString(), + 'hour' => $now->hour, + ]); + + $visit->update([ + 'last_seen_at' => $now, + 'exit_path' => $page['path'], + 'page_views' => $visit->page_views + 1, + ]); + + return $token; + } + + /** + * Where the visit of this visitor came from (channel and source), for a request + * that is sent during it. Empty when the visit was not counted. + * + * @return array{channel?: string|null, source?: string|null} + */ + public function sourceOf(string $ip, string $userAgent): array + { + $visit = Visit::query() + ->where('visitor_hash', hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent)) + ->latest('id') + ->first(); + + return $visit instanceof Visit ? ['channel' => $visit->channel, 'source' => $visit->source] : []; + } + + /** + * The time a visitor had a page in view, reported when they leave it. The + * browser may report more than once (a tab that is hidden and shown again), + * each time with the total so far. + */ + public function leave(string $token, int $seconds): void + { + $view = PageView::query()->where('token', $token)->first(); + + if (! $view instanceof PageView || $seconds < 1) { + return; + } + + // Never longer than the time that really passed since the page was opened. + $passed = (int) abs(now()->diffInSeconds($view->viewed_at)) + 5; + $seconds = min($seconds, $passed, self::MAX_SECONDS_ON_A_PAGE); + + if ($seconds <= $view->seconds) { + return; + } + + $view->update(['seconds' => $seconds]); + + Visit::query()->whereKey($view->visit_id)->update([ + 'seconds' => (int) PageView::query()->where('visit_id', $view->visit_id)->sum('seconds'), + 'last_seen_at' => now(), + ]); + } + + /** The address as the statistics know it, or null when it is no public page of this site. */ + public function pathOf(string $path): ?string + { + return $this->page($path)['path'] ?? null; + } + + /** + * The page behind an address, or null when the address is not a public page + * of this site: that keeps made-up addresses out of the statistics. + * + * @return array{path: string, post_id: int|null}|null + */ + private function page(string $path): ?array + { + if (! str_starts_with($path, '/')) { + return null; + } + + $path = '/'.trim(Str::before($path, '?'), '/'); + + if (strlen($path) > 255) { + return null; + } + + return app(CountedPages::class)->resolve($path); + } +} diff --git a/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php b/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php new file mode 100644 index 0000000..b5b4945 --- /dev/null +++ b/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php @@ -0,0 +1,97 @@ +date('day')->primary(); + $table->string('salt', 64); + }); + + // One visit: the pages someone looks at with less than half an hour between them. + Tables::create(Names::table('visits'), function (Blueprint $table) { + $table->id(); + $table->string('visitor_hash', 64); + $table->dateTime('started_at'); + $table->dateTime('last_seen_at'); + $table->date('day'); + $table->unsignedTinyInteger('hour'); + // 1 = Monday ... 7 = Sunday. + $table->unsignedTinyInteger('weekday'); + $table->string('entry_path'); + $table->string('exit_path'); + // direct, search, social, referral, share or campaign. + $table->string('channel', 20); + // The platform or site behind the channel: "linkedin", "google", "example.com". + $table->string('source', 80)->nullable(); + $table->string('referrer_host')->nullable(); + $table->string('country', 2)->nullable(); + $table->string('device', 10); + $table->string('browser', 30); + $table->string('os', 20); + $table->unsignedInteger('page_views')->default(0); + $table->unsignedInteger('seconds')->default(0); + + $table->index('day'); + $table->index(['visitor_hash', 'last_seen_at']); + }); + + Tables::create(Names::table('page_views'), function (Blueprint $table) { + $table->id(); + // What the browser sends back when the visitor leaves the page, to report the time spent. + $table->string('token', 40)->unique(); + $table->foreignId('visit_id')->constrained(Names::table('visits'))->cascadeOnDelete(); + $table->string('path'); + // The post behind the page, when the posts module is on. No foreign key: posts may be off. + $table->unsignedBigInteger('post_id')->nullable(); + $table->dateTime('viewed_at'); + $table->date('day'); + $table->unsignedTinyInteger('hour'); + $table->unsignedInteger('seconds')->default(0); + + $table->index('day'); + $table->index('path'); + }); + + // How often each program (search engine, AI crawler, link preview, ...) fetched each page, per + // day. A counter, not a log: no address, no browser line. + Tables::create(Names::table('bot_hits'), function (Blueprint $table) { + $table->id(); + $table->date('day'); + $table->string('bot', 60); + // search, ai, seo, social, monitor, feed, archive, scanner, script or other. + $table->string('kind', 20); + $table->string('path'); + $table->unsignedInteger('hits')->default(0); + + $table->unique(['day', 'bot', 'path']); + }); + } + + public function down(): void + { + + foreach (['bot_hits', 'page_views', 'visits', 'visitor_salts'] as $table) { + Schema::dropIfExists(Names::table($table)); + } + } +}; diff --git a/src/Modules/Statistics/public-routes.php b/src/Modules/Statistics/public-routes.php new file mode 100644 index 0000000..da80677 --- /dev/null +++ b/src/Modules/Statistics/public-routes.php @@ -0,0 +1,14 @@ +. +Route::get(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/').'/pulse.js', [PulseController::class, 'script'])->name(Names::route('pulse.script')); + +Route::prefix(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/'))->middleware('throttle:manager-pulse')->group(function () { + Route::post('/view', [PulseController::class, 'view'])->name(Names::route('pulse.view')); + Route::post('/leave', [PulseController::class, 'leave'])->name(Names::route('pulse.leave')); +}); diff --git a/src/Modules/Statistics/routes.php b/src/Modules/Statistics/routes.php new file mode 100644 index 0000000..6086467 --- /dev/null +++ b/src/Modules/Statistics/routes.php @@ -0,0 +1,7 @@ +name('statistics.index')->middleware('can:statistics.view'); +Route::get('/statistics/export', [StatisticsController::class, 'export'])->name('statistics.export')->middleware('can:statistics.view'); diff --git a/src/Modules/Updates/UpdatesController.php b/src/Modules/Updates/UpdatesController.php new file mode 100644 index 0000000..c483b4e --- /dev/null +++ b/src/Modules/Updates/UpdatesController.php @@ -0,0 +1,13 @@ +json(['releases' => Changelog::releases(limit: (int) config('manager.updates.limit', 20))]); + } +} diff --git a/src/Modules/Updates/UpdatesModule.php b/src/Modules/Updates/UpdatesModule.php new file mode 100644 index 0000000..7692bd2 --- /dev/null +++ b/src/Modules/Updates/UpdatesModule.php @@ -0,0 +1,41 @@ + 'Updates', 'route' => Names::route('updates.index'), 'permission' => 'updates.view', 'simple' => true, 'hint' => 'What changed on your website']]; + } + + public function views(): array + { + return ['updates.index' => 'Opened the updates']; + } +} diff --git a/src/Modules/Updates/routes.php b/src/Modules/Updates/routes.php new file mode 100644 index 0000000..6340be8 --- /dev/null +++ b/src/Modules/Updates/routes.php @@ -0,0 +1,6 @@ +name('updates.index')->middleware('can:updates.view'); diff --git a/src/Modules/Users/AccountController.php b/src/Modules/Users/AccountController.php new file mode 100644 index 0000000..dbbe5eb --- /dev/null +++ b/src/Modules/Users/AccountController.php @@ -0,0 +1,218 @@ +user(); + $model = $this->model(); + + return response()->json([ + 'accounts' => $model::query()->with('managerGroups')->orderBy('name')->orderBy('id')->get() + ->map(fn ($user) => [ + 'id' => $user->getKey(), + 'name' => $user->name, + '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, 'primary' => (bool) $group->pivot->is_primary])->values(), + 'can_change' => $me->managerOutranks($user), + 'can_delete' => $me->managerOutranks($user) && ! $user->is($me), + ])->values(), + 'groups' => Group::query()->orderBy('name')->get() + ->map(fn (Group $group) => [ + 'id' => $group->id, + 'name' => $group->name, + 'description' => $group->description, + 'can_give' => $me->managerMayGive($group), + ])->values(), + ]); + } + + public function store(Request $request): JsonResponse + { + $request->validate([...$this->rules(), 'password' => ['required', 'string', 'min:12', 'max:200']]); + + // Everything is checked before anything is stored: a refused group leaves no account behind. + $details = $this->details($request, null); + $groups = $this->groups($request); + + $model = $this->model(); + $user = new $model; + $user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save(); + $user->managerGroups()->sync($this->withPrimary($groups, $request)); + $this->settings($request, $user); + + return response()->json(['id' => $user->getKey()], 201); + } + + public function update(Request $request, string $account): JsonResponse + { + $me = $request->user(); + $user = $this->find($account); + abort_unless($me->managerOutranks($user), 403); + app(AuditTrail::class)->about($user); + + $request->validate([...$this->rules(), 'password' => ['nullable', 'string', 'min:12', 'max:200']]); + $details = $this->details($request, $user); + + // Groups mean nothing for a super admin, and nobody changes their own. + $groups = $user->isManagerSuperAdmin() || $user->is($me) ? null : $this->groups($request); + + $user->forceFill($details); + + // Empty: the password stays as it is. + if ($request->filled('password')) { + $user->forceFill(['password' => Hash::make($request->string('password')->toString())]); + } + + $user->save(); + + if ($groups !== null) { + $user->managerGroups()->sync($this->withPrimary($groups, $request)); + } + + $this->settings($request, $user); + + return response()->json(['saved' => true]); + } + + public function destroy(Request $request, string $account): JsonResponse + { + $me = $request->user(); + $user = $this->find($account); + abort_unless($me->managerOutranks($user), 403); + app(AuditTrail::class)->about($user); + + if ($user->is($me)) { + return response()->json(['message' => __('You cannot delete your own account.')], 422); + } + + $user->managerGroups()->detach(); + $user->delete(); + + 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 */ + private function model(): string + { + return config('manager.user_model'); + } + + private function find(string $id) + { + return $this->model()::query()->findOrFail($id); + } + + /** @return array> */ + private function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'email', 'max:255'], + 'groups' => ['array'], + 'groups.*' => ['integer'], + 'primary_group' => ['nullable', 'integer'], + 'view' => ['nullable', Rule::in([Menu::FULL, Menu::SIMPLE])], + 'tutorial' => ['nullable', 'boolean'], + ]; + } + + /** + * Name and email address, the address in lower case and not in use by another account. + * + * @return array{name: string, email: string} + */ + private function details(Request $request, $user): array + { + $email = $request->string('email')->trim()->lower()->toString(); + + if ($this->model()::query()->where('email', $email)->when($user !== null, fn ($query) => $query->whereKeyNot($user->getKey()))->exists()) { + throw ValidationException::withMessages(['email' => __('Another account already uses this email address.')]); + } + + return ['name' => $request->string('name')->trim()->toString(), 'email' => $email]; + } + + /** + * The ticked groups as a sync map: exactly one of them is the primary one (the one that was asked for, else the first), + * and none when there are no groups. + * + * @param list $ids + * @return array + */ + private function withPrimary(array $ids, Request $request): array + { + $asked = $request->integer('primary_group'); + $primary = in_array($asked, $ids, true) ? $asked : ($ids[0] ?? null); + + return collect($ids)->mapWithKeys(fn (int $id) => [$id => ['is_primary' => $id === $primary]])->all(); + } + + /** + * The ids of the groups that were ticked. One that does not exist, or that gives more than + * the account that is logged in has, is refused. + * + * @return list + */ + private function groups(Request $request): array + { + $me = $request->user(); + $ids = array_values(array_unique(array_map(fn (mixed $id) => is_numeric($id) ? (int) $id : 0, $request->array('groups')))); + $groups = Group::query()->whereKey($ids)->get(); + + if ($groups->count() !== count($ids) || $groups->contains(fn (Group $group) => ! $me->managerMayGive($group))) { + throw ValidationException::withMessages(['groups' => __('You can only choose groups that allow nothing more than your own account.')]); + } + + return $ids; + } +} diff --git a/src/Modules/Users/CreateManagerUser.php b/src/Modules/Users/CreateManagerUser.php new file mode 100644 index 0000000..89163eb --- /dev/null +++ b/src/Modules/Users/CreateManagerUser.php @@ -0,0 +1,78 @@ +value('name', 'Name'); + $email = strtolower($this->value('email', 'Email')); + $password = $this->value('password', 'Password (min 12 characters)', secret: true); + $model = config('manager.user_model'); + + if ($name === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) { + $this->error('A name and a valid email address are required.'); + + return self::FAILURE; + } + + if ($model::query()->where('email', $email)->exists()) { + $this->error("A user with email {$email} already exists."); + + return self::FAILURE; + } + + if (mb_strlen($password) < 12) { + $this->error('Password must be at least 12 characters.'); + + return self::FAILURE; + } + + // Direct assignment: a super admin is never mass-assignable. + $user = new $model; + $user->forceFill(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]); + $user->is_super_admin = true; + $user->save(); + + $this->info("Super admin account for {$name} <{$email}> created."); + + return self::SUCCESS; + } + + /** The option when it was given, otherwise the answer to a question. */ + private function value(string $option, string $question, bool $secret = false): string + { + $given = $this->option($option); + + if (is_string($given) && trim($given) !== '') { + return $secret ? $given : trim($given); + } + + $answer = $secret ? $this->secret($question) : $this->ask($question); + + if (! is_string($answer)) { + return ''; + } + + return $secret ? $answer : trim($answer); + } +} diff --git a/src/Modules/Users/GroupController.php b/src/Modules/Users/GroupController.php new file mode 100644 index 0000000..6774869 --- /dev/null +++ b/src/Modules/Users/GroupController.php @@ -0,0 +1,83 @@ +json([ + 'groups' => Group::query()->withCount('users')->orderBy('name')->get() + ->map(fn (Group $group) => [ + 'id' => $group->id, + 'name' => $group->name, + 'description' => $group->description, + 'start' => $group->start, + 'permissions' => $group->allowed(), + 'accounts' => $group->users_count, + ])->values(), + 'catalogue' => $this->modules->catalogue(), + ]); + } + + public function store(Request $request): JsonResponse + { + $group = Group::create($this->validated($request)); + + return response()->json(['id' => $group->id], 201); + } + + public function update(Request $request, string $group): JsonResponse + { + $group = Group::query()->findOrFail($group); + app(AuditTrail::class)->about($group); + $group->update($this->validated($request, $group)); + + return response()->json(['saved' => true]); + } + + /** The accounts in it stay; they lose what only this group allowed. */ + public function destroy(string $group): JsonResponse + { + $group = Group::query()->findOrFail($group); + app(AuditTrail::class)->about($group); + $group->users()->detach(); + $group->delete(); + + return response()->json(['deleted' => true]); + } + + /** @return array{name: string, description: string|null, start: string|null, permissions: list} */ + private function validated(Request $request, ?Group $group = null): array + { + $table = Names::table('groups'); + + $request->validate([ + 'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)], + 'description' => ['nullable', 'string', 'max:500'], + 'start' => ['nullable', 'string', 'max:200', 'regex:#^/[A-Za-z0-9/_.-]*$#'], + 'permissions' => ['array'], + 'permissions.*' => ['string', Rule::in($this->modules->permissionValues())], + ]); + + $description = $request->string('description')->trim()->toString(); + + return [ + 'name' => $request->string('name')->trim()->toString(), + 'description' => $description !== '' ? $description : null, + 'start' => $request->filled('start') ? $request->string('start')->toString() : null, + 'permissions' => $this->modules->complete($request->array('permissions')), + ]; + } +} diff --git a/src/Modules/Users/UsersModule.php b/src/Modules/Users/UsersModule.php new file mode 100644 index 0000000..2f62b8f --- /dev/null +++ b/src/Modules/Users/UsersModule.php @@ -0,0 +1,67 @@ + 'Accounts', 'route' => Names::route('accounts.index'), 'permission' => 'accounts.manage'], + ['label' => 'Groups', 'route' => Names::route('groups.index'), 'permission' => 'groups.manage'], + ]; + } + + public function actions(): array + { + return [ + 'accounts.store' => ['Created an account'], + 'accounts.update' => ['Changed an account'], + 'accounts.destroy' => ['Deleted an account'], + 'groups.store' => ['Created a group'], + 'groups.update' => ['Changed a group'], + 'groups.destroy' => ['Deleted a group'], + ]; + } + + public function views(): array + { + return ['accounts.index' => 'Opened the accounts', 'groups.index' => 'Opened the groups']; + } + + public function commands(): array + { + return [CreateManagerUser::class]; + } +} diff --git a/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php new file mode 100644 index 0000000..4515d71 --- /dev/null +++ b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php @@ -0,0 +1,44 @@ +getTable(); + + // New accounts are never super admins; an existing one is not promoted here. + // `manager:create-user` is the way to make a super admin. + if (! Schema::hasColumn($users, 'is_super_admin')) { + Schema::table($users, fn (Blueprint $table) => $table->boolean('is_super_admin')->default(false)); + } + + Tables::create(Names::table('groups'), function (Blueprint $table) { + $table->id(); + $table->string('name')->unique(); + $table->string('description', 500)->nullable(); + $table->json('permissions')->nullable(); + $table->timestamps(); + }); + + Tables::create(Names::table('group_user'), function (Blueprint $table) use ($users) { + $table->foreignId('group_id')->constrained(Names::table('groups'))->cascadeOnDelete(); + $table->foreignId('user_id')->constrained($users)->cascadeOnDelete(); + $table->primary(['group_id', 'user_id']); + }); + } + + public function down(): void + { + $users = (new (config('manager.user_model')))->getTable(); + + Schema::dropIfExists(Names::table('group_user')); + Schema::dropIfExists(Names::table('groups')); + Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin')); + } +}; diff --git a/src/Modules/Users/migrations/2026_12_08_000001_add_primary_group_and_start.php b/src/Modules/Users/migrations/2026_12_08_000001_add_primary_group_and_start.php new file mode 100644 index 0000000..66cf4db --- /dev/null +++ b/src/Modules/Users/migrations/2026_12_08_000001_add_primary_group_and_start.php @@ -0,0 +1,31 @@ + $table->boolean('is_primary')->default(false)); + Tables::addColumn(Names::table('groups'), 'start', fn (Blueprint $table) => $table->string('start', 200)->nullable()); + + // An account that is in groups already gets the first of them as its primary one. + $pivot = Names::table('group_user'); + + $hasPrimary = DB::table($pivot)->where('is_primary', true)->exists(); + foreach ($hasPrimary ? [] : DB::table($pivot)->select('user_id', DB::raw('min(group_id) as first'))->groupBy('user_id')->get() as $row) { + DB::table($pivot)->where('user_id', $row->user_id)->where('group_id', $row->first)->update(['is_primary' => true]); + } + } + + public function down(): void + { + Schema::table(Names::table('groups'), fn (Blueprint $table) => $table->dropColumn('start')); + Schema::table(Names::table('group_user'), fn (Blueprint $table) => $table->dropColumn('is_primary')); + } +}; diff --git a/src/Modules/Users/routes.php b/src/Modules/Users/routes.php new file mode 100644 index 0000000..c87db22 --- /dev/null +++ b/src/Modules/Users/routes.php @@ -0,0 +1,21 @@ +group(function () { + Route::get('/accounts', [AccountController::class, 'index'])->name('accounts.index'); + Route::post('/accounts', [AccountController::class, 'store'])->name('accounts.store'); + Route::put('/accounts/{account}', [AccountController::class, 'update'])->name('accounts.update')->whereNumber('account'); + Route::delete('/accounts/{account}', [AccountController::class, 'destroy'])->name('accounts.destroy')->whereNumber('account'); +}); + +Route::middleware('can:groups.manage')->group(function () { + Route::get('/groups', [GroupController::class, 'index'])->name('groups.index'); + Route::post('/groups', [GroupController::class, 'store'])->name('groups.store'); + Route::put('/groups/{group}', [GroupController::class, 'update'])->name('groups.update')->whereNumber('group'); + Route::delete('/groups/{group}', [GroupController::class, 'destroy'])->name('groups.destroy')->whereNumber('group'); +}); diff --git a/src/Support/AuditTrail.php b/src/Support/AuditTrail.php new file mode 100644 index 0000000..5e3cb55 --- /dev/null +++ b/src/Support/AuditTrail.php @@ -0,0 +1,112 @@ +made = null; + $this->settled = false; + } + + public function made(Model $model): void + { + if (! $this->settled && $this->made === null && ! $model instanceof AuditLog) { + $this->made = $model; + } + } + + /** + * For a controller whose request is about something it did not make (an address that was + * banned before, an account that was changed), or about no single thing (null). + */ + public function about(?Model $model): void + { + $this->made = $model; + $this->settled = true; + } + + public function firstMade(): ?Model + { + return $this->made; + } + + /** + * @param array $details + */ + public function record( + string $event, + string $summary, + ?Authenticatable $user = null, + ?Model $subject = null, + array $details = [], + ?string $action = null, + ?string $email = null, + ): AuditLog { + // A command has no visitor: no address and no browser. + $request = app()->runningInConsole() && ! app()->runningUnitTests() ? null : request(); + $about = $subject === null ? null : self::describe($subject); + $agent = $request?->userAgent(); + $name = $user === null ? null : data_get($user, 'name'); + + return AuditLog::query()->create([ + 'event' => $event, + 'action' => $action, + 'summary' => Str::limit($summary, 250, '…'), + 'subject_type' => $about['type'] ?? null, + 'subject_id' => $about['id'] ?? null, + 'subject_label' => $about['label'] ?? null, + 'details' => $details === [] ? null : $details, + 'user_id' => $user?->getAuthIdentifier(), + 'user_name' => is_string($name) ? $name : null, + 'email' => $email === null ? null : Str::limit($email, 250, '…'), + 'ip' => $request?->ip(), + 'user_agent' => is_string($agent) ? Str::limit($agent, 490, '…') : null, + 'created_at' => now(), + ]); + } + + /** + * What a model is called in the log: its kind ('post', 'ip_ban'), its id and a name. + * + * @return array{type: string, id: int|null, label: string} + */ + public static function describe(Model $model): array + { + $id = $model->getKey(); + $id = is_int($id) ? $id : null; + $label = '#'.($id ?? '?'); + + foreach (['title', 'name', 'label', 'ip', 'slug'] as $attribute) { + $value = $model->getAttribute($attribute); + + if (is_string($value) && trim($value) !== '') { + $label = Str::limit(trim($value), 200, '…'); + break; + } + } + + return ['type' => Str::snake(class_basename($model)), 'id' => $id, 'label' => $label]; + } +} diff --git a/src/Support/Changelog.php b/src/Support/Changelog.php new file mode 100644 index 0000000..b57d555 --- /dev/null +++ b/src/Support/Changelog.php @@ -0,0 +1,69 @@ +}>}> + */ + public static function releases(?string $path = null, int $limit = 20): array + { + $path ??= (string) (config('manager.updates.changelog') ?: base_path('CHANGELOG.md')); + + if (! is_file($path)) { + return []; + } + + $releases = []; + + foreach (preg_split('/\R/', (string) file_get_contents($path)) ?: [] as $line) { + $line = rtrim($line); + + if (preg_match('/^##\s+\[?(v?\d+\.\d+\.\d+[^\s\]]*)\]?(?:\s+-\s+(\d{4}-\d{2}-\d{2}))?/', $line, $match) === 1) { + $releases[] = ['version' => $match[1], 'date' => $match[2] ?? null, 'sections' => []]; + + continue; + } + + if ($releases === []) { + continue; + } + + $last = count($releases) - 1; + + if (preg_match('/^###\s+(.+)$/', $line, $match) === 1) { + $releases[$last]['sections'][] = ['title' => trim($match[1]), 'items' => []]; + + continue; + } + + if (preg_match('/^[*-]\s+(.+)$/', $line, $match) === 1) { + // A line directly under the release, without a heading of its own kind, goes in a section without a title. + if ($releases[$last]['sections'] === []) { + $releases[$last]['sections'][] = ['title' => '', 'items' => []]; + } + + $section = count($releases[$last]['sections']) - 1; + $releases[$last]['sections'][$section]['items'][] = self::plain($match[1]); + } + } + + return array_slice($releases, 0, max(1, $limit)); + } + + /** A line without its Markdown and without the commit it came from: "(1a2b3c4)" at the end. */ + private static function plain(string $line): string + { + $line = (string) preg_replace('/\s*\(\[?[0-9a-f]{7,40}\]?(?:\([^)]*\))?\)\s*$/', '', $line); + $line = (string) preg_replace('/\[([^\]]+)\]\([^)]*\)/', '$1', $line); + + return trim(str_replace(['**', '`'], '', $line)); + } +} diff --git a/src/Support/Costs/Ledger.php b/src/Support/Costs/Ledger.php new file mode 100644 index 0000000..4dc9298 --- /dev/null +++ b/src/Support/Costs/Ledger.php @@ -0,0 +1,350 @@ + + */ + public function items(): array + { + $items = $this->rows(); + $costs = $this->kept($items); + + foreach ($items as $index => $item) { + $cost = $costs['row-'.$index] ?? null; + + if ($cost !== null) { + $items[$index] = ['usd' => round($cost['usd'], 4), 'eur' => round($cost['eur'], 2), 'priced_by' => 'service', 'usd_to_eur' => round(1 / $cost['usd_per_eur'], 4)] + $item; + } + } + + return $items; + } + + /** The rows of the file, priced with the fixed rates. */ + private function rows(): array + { + $path = config('manager.costs.ledger') ?: base_path('TOKENS.md'); + + if (! is_string($path) || ! is_file($path)) { + return []; + } + + $items = []; + $inTable = false; + + foreach (preg_split('/\R/', (string) file_get_contents($path)) ?: [] as $line) { + $line = trim($line); + + if (! str_starts_with($line, '|')) { + $inTable = false; + + continue; + } + + $cells = array_map(trim(...), explode('|', trim($line, '|'))); + + // Nine cells, or ten with the hours that were worked as the last one. + if (in_array(count($cells), [9, 10], true) && strcasecmp($cells[0], 'Datum') === 0) { + $inTable = true; + + continue; + } + + // A row of this table starts with a date; the line of dashes under the header does not. + if (! $inTable || ! in_array(count($cells), [9, 10], true) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $cells[0]) !== 1) { + continue; + } + + $item = [ + 'date' => $cells[0], + 'name' => $cells[1], + 'version' => $cells[2] !== '' ? $cells[2] : null, + 'model' => $cells[3], + 'steps' => self::number($cells[4]), + 'output' => self::number($cells[5]), + 'input' => self::number($cells[6]), + 'cache_write' => self::number($cells[7]), + 'cache_read' => self::number($cells[8]), + ]; + $item['tokens'] = $item['output'] + $item['input'] + $item['cache_write'] + $item['cache_read']; + // A row of work without the model (hours only) costs nothing in tokens. + $item['usd'] = $item['tokens'] === 0 ? 0.0 : $this->usd($item); + $item['eur'] = $item['usd'] !== null && $this->rate() > 0 ? round($item['usd'] * $this->rate(), 2) : null; + $item['priced_by'] = $item['eur'] !== null ? 'config' : null; + $item['usd_to_eur'] = $item['eur'] !== null ? $this->rate() : null; + $item['hours'] = self::hours($cells[9] ?? ''); + $item['work_eur'] = $item['hours'] !== null ? round($item['hours'] * $this->hourlyRate(), 2) : null; + + $items[] = $item; + } + + return $items; + } + + /** + * What the tokens of the rows cost, by the place of the row in the list ("row-0"), from the table of kept prices and, for the + * rows that are not in it, from the pricer of the site or the API. Only rows without a kept price are asked, all in one request; + * a visit to the screen of a site whose rows are all priced asks nothing. When nobody can say, that is remembered for ten minutes, + * so a server that is down is not asked again by every visit. + * + * @param list> $items + * @return array + */ + private function kept(array $items): array + { + $prints = []; + + foreach ($items as $index => $item) { + // A row without tokens costs nothing and needs no price. + if ($item['tokens'] > 0) { + $prints[$index] = self::fingerprint($item); + } + } + + if ($prints === []) { + return []; + } + + $costs = []; + $stored = WorkCost::query()->whereIn('fingerprint', array_values($prints))->get()->keyBy('fingerprint'); + + foreach ($prints as $index => $print) { + $kept = $stored->get($print); + + if ($kept instanceof WorkCost) { + $costs['row-'.$index] = ['usd' => (float) $kept->usd, 'eur' => (float) $kept->eur, 'usd_per_eur' => (float) $kept->usd_per_eur]; + } + } + + $missing = array_filter($prints, fn (string $print) => ! $stored->has($print)); + + if ($missing === []) { + return $costs; + } + + $ask = []; + + foreach ($missing as $index => $print) { + $ask[] = [ + 'reference' => 'row-'.$index, + 'model' => $items[$index]['model'], + 'date' => $items[$index]['date'], + // The sessions that wrote the table used the one-hour cache. + 'tokens' => ['output' => $items[$index]['output'], 'input' => $items[$index]['input'], 'cache_write_1h' => $items[$index]['cache_write'], 'cache_read' => $items[$index]['cache_read']], + ]; + } + + $failed = 'manager.costs.failed:'.hash('sha256', (string) json_encode($ask)); + + if (Cache::has($failed)) { + return $costs; + } + + $answer = $this->ask($ask); + + if ($answer === null) { + Cache::put($failed, true, now()->addMinutes(10)); + + return $costs; + } + + foreach ($missing as $index => $print) { + $cost = $answer['row-'.$index] ?? null; + + if ($cost === null) { + continue; + } + + WorkCost::query()->updateOrCreate(['fingerprint' => $print], [ + 'date' => $items[$index]['date'], + 'name' => mb_substr($items[$index]['name'], 0, 255), + 'version' => $items[$index]['version'], + 'model' => $items[$index]['model'], + 'usd' => $cost['usd'], + 'eur' => $cost['eur'], + 'usd_per_eur' => $cost['usd_per_eur'], + 'priced_at' => now(), + ]); + $costs['row-'.$index] = $cost; + } + + // What nobody had a price for (a model it does not know) is not asked again for six hours. + $left = array_values(array_filter($ask, fn (array $row) => ! isset($answer[$row['reference']]))); + + if ($left !== []) { + Cache::put('manager.costs.failed:'.hash('sha256', (string) json_encode($left)), true, now()->addHours(6)); + } + + return $costs; + } + + /** + * @param list> $ask + * @return array|null + */ + private function ask(array $ask): ?array + { + $pricer = config('manager.costs.pricer'); + + if (is_string($pricer) && $pricer !== '' && (class_exists($pricer) || app()->bound($pricer))) { + $answer = app($pricer)($ask); + + return is_array($answer) ? $answer : null; + } + + if (! config('manager.costs.use_api', true)) { + return null; + } + + $client = new Client((array) config('manager.media.iriksit', [])); + + return $client->isConfigured() ? $client->tokenCosts($ask) : null; + } + + /** + * What makes a row the row it is, for its price: the day, the model and the tokens. + * + * @param array $item + */ + private static function fingerprint(array $item): string + { + return hash('sha256', implode('|', [$item['date'], $item['model'], $item['output'], $item['input'], $item['cache_write'], $item['cache_read']])); + } + + /** Euros for an hour of work: a cost of its own, apart from what the AI model costs. */ + public function hourlyRate(): float + { + $rate = config('manager.costs.hourly_rate'); + + return is_numeric($rate) ? (float) $rate : 0.0; + } + + /** + * What hosting has cost until a day: the yearly amount once for every year that has begun since its first day, and nothing before. + * + * @return array{per_year: float, from: string|null, years: int, eur: float} + */ + public function hosting(?CarbonImmutable $on = null): array + { + $perYear = config('manager.costs.hosting.per_year'); + $from = config('manager.costs.hosting.from'); + $perYear = is_numeric($perYear) ? (float) $perYear : 0.0; + $on ??= CarbonImmutable::today(); + + if (! is_string($from) || $from === '') { + return ['per_year' => $perYear, 'from' => null, 'years' => 0, 'eur' => 0.0]; + } + + $start = CarbonImmutable::parse($from)->startOfDay(); + $years = $on->lt($start) ? 0 : (int) floor($start->diffInYears($on)) + 1; + + return ['per_year' => $perYear, 'from' => $start->toDateString(), 'years' => $years, 'eur' => round($years * $perYear, 2)]; + } + + /** + * The discount on the work and the AI costs: which share, and until which day (rows dated on or after that day get none). + * Null when there is no discount. Hosting is not part of it. + * + * @return array{percent: float, until: string}|null + */ + public function discount(): ?array + { + $percent = config('manager.costs.discount.percent'); + $until = config('manager.costs.discount.until'); + + if (! is_numeric($percent) || (float) $percent <= 0 || ! is_string($until) || $until === '') { + return null; + } + + return ['percent' => min(100.0, (float) $percent), 'until' => CarbonImmutable::parse($until)->toDateString()]; + } + + /** + * What of a row is not charged: the discount on its work and its AI costs. + * + * @param array $item + */ + public function discountOn(array $item): float + { + $discount = $this->discount(); + + if ($discount === null || $item['date'] >= $discount['until']) { + return 0.0; + } + + return round((($item['work_eur'] ?? 0.0) + ($item['eur'] ?? 0.0)) * $discount['percent'] / 100, 2); + } + + /** Euros for one US dollar, for the rows that are priced with the fixed rates; 0 when the site gave none. */ + public function rate(): float + { + $rate = config('manager.costs.usd_to_eur'); + + return is_numeric($rate) ? (float) $rate : 0.0; + } + + /** + * What a row costs at the fixed price list, or null when the model has no prices there. + * + * @param array $item + */ + private function usd(array $item): ?float + { + $rates = config('manager.costs.rates.'.$item['model']); + + if (! is_array($rates)) { + return null; + } + + $usd = 0.0; + + foreach (['output', 'input', 'cache_write', 'cache_read'] as $kind) { + $price = $rates[$kind] ?? null; + + if (! is_numeric($price)) { + return null; + } + + $usd += $item[$kind] * (float) $price / 1_000_000; + } + + return round($usd, 4); + } + + /** "1,25" or "1.25" hours as it is written in the file; an empty cell is not known. */ + private static function hours(string $cell): ?float + { + $cell = str_replace(',', '.', trim($cell)); + + return is_numeric($cell) && (float) $cell >= 0 ? round((float) $cell, 2) : null; + } + + /** "1.234.567" as it is written in the file. */ + private static function number(string $cell): int + { + return (int) preg_replace('/\D/', '', $cell); + } +} diff --git a/src/Support/Features.php b/src/Support/Features.php new file mode 100644 index 0000000..73260f2 --- /dev/null +++ b/src/Support/Features.php @@ -0,0 +1,56 @@ + ['services' => ['label' => 'Services', 'enabled' => true, 'env' => 'SITE_SERVICES', 'hint' => 'The page with what you offer']] + * + * - the manager: a `resources` entry with `'feature' => 'services'` is left out when it is off (menu, permissions, screens, routes), + * - the public site: `Features::on('services')`, the route middleware `manager.feature:services` (a 404 when off), the Blade + * condition `@feature('services') … @endfeature`, and `Features::flags()` for what a page needs to know (links, sitemap). + * + * Off hides, it does not delete: the data stays where it is and comes back when the switch goes on again. The value lives at + * `manager.features..enabled`, which is also the path the settings screen changes. + */ +final class Features +{ + /** @return array */ + public static function all(): array + { + $out = []; + + foreach ((array) config('manager.features', []) as $key => $definition) { + if (! is_string($key) || preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) !== 1) { + continue; + } + + $definition = is_array($definition) ? $definition : ['enabled' => (bool) $definition]; + $env = $definition['env'] ?? null; + + $out[$key] = [ + 'key' => $key, + 'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))), + 'hint' => isset($definition['hint']) ? (string) $definition['hint'] : null, + 'enabled' => filter_var($definition['enabled'] ?? false, FILTER_VALIDATE_BOOLEAN), + 'env' => is_string($env) && preg_match('/^[A-Z][A-Z0-9_]*$/', $env) === 1 ? $env : null, + ]; + } + + return $out; + } + + /** Whether a feature is on. A name that is not a feature is off: nothing shows up that nobody declared. */ + public static function on(string $key): bool + { + return (self::all()[$key]['enabled'] ?? false) === true; + } + + /** @return array every feature and whether it is on, to hand to a page */ + public static function flags(): array + { + return array_map(fn (array $feature) => $feature['enabled'], self::all()); + } +} diff --git a/src/Support/Fields.php b/src/Support/Fields.php new file mode 100644 index 0000000..0ed88ce --- /dev/null +++ b/src/Support/Fields.php @@ -0,0 +1,295 @@ + ['label' => 'Title on the photo', 'type' => 'text', 'help' => 'One line.', 'max' => 120] + * + * 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, or `source`: `['model' => Service::class, 'label' => 'title', 'value' => 'id']` + * for the rows of a table of the site). More: `slug` (an address part; `from` names the field it is made of when it is left empty), `list` (a list of short texts, + * one per line), `media_list` (a list of pictures from the media library, a gallery) and `repeater` (a list of items that each have the fields of `items`, for example + * questions and answers). The last three are stored as arrays. `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). `simple` gives the simple face its own words, + * for someone who is not a webmaster: `'simple' => ['label' => 'Your phone number', 'help' => 'As you want it to be read.']`; a part + * left out falls back to `label` / `help`. + */ +final class Fields +{ + public const TYPES = ['text', 'textarea', 'markdown', 'lines', 'media', 'url', 'number', 'date', 'toggle', 'select', 'slug', 'list', 'media_list', 'repeater']; + + /** What a repeater item may be made of. */ + private const ITEM_TYPES = ['text', 'textarea', 'url', 'media']; + + private const LENGTHS = ['text' => 255, 'textarea' => 20000, 'markdown' => 100000, 'lines' => 10000, 'media' => 2048, 'url' => 2048, 'date' => 40, 'select' => 255, 'slug' => 120]; + + /** + * The definitions in one shape, with a key, a label and a known type; what is wrong is dropped. + * + * @param array $fields key => definition + * @return array, source: ?array{model: class-string, label: string, value: string}, from: ?string, items: array>, max: ?int, rules: list}> + */ + public static function normalize(array $fields): array + { + $out = []; + + foreach ($fields as $key => $field) { + if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,59}$/', $key) || ! is_array($field)) { + continue; + } + + $type = in_array($field['type'] ?? 'text', self::TYPES, true) ? ($field['type'] ?? 'text') : 'text'; + $options = []; + + $given = (array) ($field['options'] ?? []); + + foreach ($given as $value => $label) { + $options[(string) (array_is_list($given) ? $label : $value)] = (string) $label; + } + + $source = self::source($field['source'] ?? null); + + if ($type === 'select' && $options === [] && $source === null) { + continue; + } + + $items = $type === 'repeater' ? self::normalizeItems((array) ($field['items'] ?? [])) : []; + + if ($type === 'repeater' && $items === []) { + continue; + } + + $out[$key] = [ + 'key' => $key, + 'label' => (string) ($field['label'] ?? ucfirst(str_replace('_', ' ', $key))), + 'type' => $type, + 'help' => isset($field['help']) ? (string) $field['help'] : null, + 'simple_label' => self::simpleText($field, 'label'), + 'simple_help' => self::simpleText($field, 'help'), + 'advanced' => (bool) ($field['advanced'] ?? false), + 'required' => (bool) ($field['required'] ?? false), + 'default' => $field['default'] ?? self::empty($type), + 'options' => $options, + 'source' => $source, + 'from' => $type === 'slug' && isset($field['from']) ? (string) $field['from'] : null, + 'items' => $items, + 'max' => isset($field['max']) ? max(1, (int) $field['max']) : null, + 'rules' => array_values((array) ($field['rules'] ?? [])), + ]; + } + + return $out; + } + + /** + * The Laravel rules for the values, keyed ``. + * + * @param array> $fields normalized + * @return array> + */ + public static function rules(array $fields, string $prefix = ''): array + { + $rules = []; + + foreach ($fields as $key => $field) { + $type = $field['type']; + $max = $field['max'] ?? self::LENGTHS[$type] ?? null; + $presence = $field['required'] ? 'required' : 'nullable'; + + $rules[$prefix.$key] = [$presence, ...match ($type) { + 'toggle' => ['boolean'], + 'number' => ['numeric'], + 'date' => ['date'], + 'select' => $field['source'] === null ? ['string', Rule::in(array_keys($field['options']))] : [Rule::in(array_keys(self::optionsOf($field)))], + 'media', 'url' => ['string', 'max:'.$max, 'regex:'.self::ADDRESS], + 'slug' => ['string', 'max:'.$max, 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/'], + 'list' => ['array', 'max:100'], + 'media_list' => ['array', 'max:50'], + 'repeater' => ['array', 'max:50'], + default => ['string', 'max:'.$max], + }, ...$field['rules']]; + + if ($type === 'list') { + $rules[$prefix.$key.'.*'] = ['nullable', 'string', 'max:500']; + } elseif ($type === 'media_list') { + $rules[$prefix.$key.'.*'] = ['nullable', 'string', 'max:2048', 'regex:'.self::ADDRESS]; + } elseif ($type === 'repeater') { + foreach (self::rules($field['items']) as $sub => $subRules) { + $rules[$prefix.$key.'.*.'.$sub] = $subRules; + } + } + } + + return $rules; + } + + /** A web address or a path of the site. Never `javascript:` and its kin. */ + public const ADDRESS = '#^(/(?!/)|https?://)[^\s<>"\']*$#i'; + + /** + * What is stored: only the known keys, in the type of the field, the default where nothing is given. + * + * @param array> $fields normalized + * @param array $input + * @return array + */ + public static function clean(array $fields, array $input): array + { + $out = []; + + foreach ($fields as $key => $field) { + $value = array_key_exists($key, $input) ? $input[$key] : $field['default']; + + $out[$key] = match ($field['type']) { + 'toggle' => filter_var($value, FILTER_VALIDATE_BOOLEAN), + 'number' => $value === null || $value === '' ? null : $value + 0, + 'select' => $field['source'] !== null && ($value === null || $value === '') ? null : (is_scalar($value) ? trim((string) $value) : ''), + 'list', 'media_list' => self::strings($value), + 'repeater' => self::cleanItems($field['items'], $value), + default => $value === null ? '' : (is_scalar($value) ? trim((string) $value) : ''), + }; + } + + // An address part that was left empty is made of the field it follows. + foreach ($fields as $key => $field) { + if ($field['type'] === 'slug' && $out[$key] === '' && $field['from'] !== null && is_string($out[$field['from']] ?? null)) { + $out[$key] = Str::slug($out[$field['from']]); + } + } + + return $out; + } + + /** + * The stored values over the defaults, for the screens and for the public site. + * + * @param array> $fields normalized + * @param array $stored + * @return array + */ + public static function values(array $fields, array $stored): array + { + $out = []; + + foreach ($fields as $key => $field) { + $out[$key] = array_key_exists($key, $stored) ? $stored[$key] : $field['default']; + } + + return $out; + } + + /** + * The options of a select: the fixed ones, or the rows of the table of the site it is made from (value => label). + * + * @param array $field normalized + * @return array + */ + public static function optionsOf(array $field): array + { + $source = $field['source'] ?? null; + + if ($source === null) { + return $field['options']; + } + + return $source['model']::query()->orderBy($source['label'])->pluck($source['label'], $source['value'])->mapWithKeys(fn ($label, $value) => [(string) $value => (string) $label])->all(); + } + + /** + * The fields with the options of a table of the site filled in, as the screens need them. + * + * @param array> $fields normalized + * @return list> + */ + public static function described(array $fields): array + { + return array_values(array_map(fn (array $field) => $field['source'] === null ? $field : [...$field, 'options' => self::optionsOf($field)], $fields)); + } + + /** @return ?array{model: class-string, label: string, value: string} */ + private static function source(mixed $source): ?array + { + if (! is_array($source) || ! is_string($source['model'] ?? null) || ! is_subclass_of($source['model'], Eloquent::class)) { + return null; + } + + $label = (string) ($source['label'] ?? 'name'); + $value = (string) ($source['value'] ?? 'id'); + + return preg_match('/^[a-z_][a-z0-9_]*$/i', $label.$value) === 1 ? ['model' => $source['model'], 'label' => $label, 'value' => $value] : null; + } + + /** + * @param array $items + * @return array> + */ + private static function normalizeItems(array $items): array + { + $fields = array_filter(self::normalize($items), fn (array $field) => in_array($field['type'], self::ITEM_TYPES, true)); + + return $fields; + } + + /** + * One of the words the simple face has of its own (`simple.label`, `simple.help`), or null. + * + * @param array $definition + */ + public static function simpleText(array $definition, string $part): ?string + { + $text = is_array($definition['simple'] ?? null) ? ($definition['simple'][$part] ?? null) : null; + + return is_string($text) && trim($text) !== '' ? trim($text) : null; + } + + /** + * A list of short texts: an array, or a text with one per line; empty ones are dropped. + * + * @return list + */ + private static function strings(mixed $value): array + { + $value = is_string($value) ? preg_split('/\R/u', $value) : (array) $value; + + return array_values(array_filter(array_map(fn ($item) => is_scalar($item) ? trim((string) $item) : '', $value ?: []), fn ($item) => $item !== '')); + } + + /** + * @param array> $items normalized + * @return list> + */ + private static function cleanItems(array $items, mixed $value): array + { + $out = []; + + foreach (is_array($value) ? $value : [] as $item) { + $clean = self::clean($items, is_array($item) ? $item : []); + + if (array_filter($clean, fn ($part) => $part !== '') !== []) { + $out[] = $clean; + } + } + + return $out; + } + + private static function empty(string $type): mixed + { + return match ($type) { + 'toggle' => false, + 'number' => null, + 'list', 'media_list', 'repeater' => [], + default => '', + }; + } +} diff --git a/src/Support/Importer.php b/src/Support/Importer.php new file mode 100644 index 0000000..600a0db --- /dev/null +++ b/src/Support/Importer.php @@ -0,0 +1,186 @@ +, columns: list, required: list, key: list}> + */ + public const TARGETS = [ + 'posts' => [ + 'model' => Post::class, + 'columns' => ['title', 'slug', 'excerpt', 'body', 'cover_image', 'category', 'tags', 'is_featured', 'published_at'], + 'required' => ['title', 'body'], + 'key' => ['slug'], + ], + 'pages' => [ + 'model' => Page::class, + 'columns' => ['slug', 'title', 'body', 'is_published'], + 'required' => ['slug', 'title'], + 'key' => ['slug'], + ], + // The rows only; the files stay where they are. `disk` and `location` say where (use `--set=disk=iriksit` when the source has no disk column). + 'media' => [ + 'model' => Media::class, + 'columns' => ['disk', 'location', 'name', 'filename', 'mime_type', 'size', 'checksum', 'width', 'height', 'alt', 'focus_x', 'focus_y'], + 'required' => ['location', 'filename'], + 'key' => ['disk', 'location'], + ], + // Requests with everything the screening and the follow-up decided. A site that points to a service by id keeps `subject_id` and sets the + // `subject` text with `--set=subject=...` or after the import. + 'leads' => [ + 'model' => Lead::class, + 'columns' => ['kind', 'folder', 'reasons', 'name', 'phone', 'email', 'prefers', 'about', 'message', 'message_hash', 'answers', 'location', 'subject', 'subject_id', 'page', 'channel', 'source', 'ip', 'opened_at', 'handled_at', 'outcome', 'notes', 'notified_at', 'notify_failed', 'created_at'], + 'required' => ['kind', 'name', 'created_at'], + 'key' => ['name', 'kind', 'created_at'], + ], + // How often the phone number and the WhatsApp button were pressed, per day and page. + 'taps' => [ + 'model' => LeadTap::class, + 'columns' => ['day', 'kind', 'path', 'taps'], + 'required' => ['day', 'kind', 'path'], + 'key' => ['day', 'kind', 'path'], + ], + 'reviews' => [ + 'model' => Review::class, + 'columns' => ['author', 'place', 'rating', 'body', 'is_visible'], + 'required' => ['author', 'body'], + 'key' => ['author', 'body'], + ], + ]; + + /** + * @param array $map package column => column of the source table; same name when left out + * @param array $fixed package column => a value for every row that has none of its own + * @return array{created: int, updated: int, skipped: int, problems: list} + */ + public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null, array $fixed = []): array + { + $spec = self::TARGETS[$target] ?? throw new InvalidArgumentException("Unknown target {$target}; use one of: ".implode(', ', array_keys(self::TARGETS))); + + foreach (array_keys($map) as $column) { + if (! in_array($column, $spec['columns'], true)) { + throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns'])); + } + } + + $result = ['created' => 0, 'updated' => 0, 'skipped' => 0, 'problems' => []]; + $query = $source->table($table); + $limit !== null && $query->limit($limit); + + foreach ($query->get() as $number => $row) { + $row = (array) $row; + $values = []; + + foreach ($spec['columns'] as $column) { + $from = $map[$column] ?? $column; + + if (array_key_exists($from, $row)) { + $values[$column] = $this->convert($column, $row[$from]); + } + } + + foreach ($fixed as $column => $value) { + if (! in_array($column, $spec['columns'], true)) { + throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns'])); + } + + if (! isset($values[$column]) || $values[$column] === '') { + $values[$column] = $this->convert($column, $value); + } + } + + if ($target === 'media') { + foreach (['disk' => config('manager.media.disk'), 'mime_type' => 'application/octet-stream', 'size' => 0] as $column => $default) { + if (! isset($values[$column]) || $values[$column] === '') { + $values[$column] = $default; + } + } + + $values['name'] = ($values['name'] ?? '') !== '' ? $values['name'] : pathinfo((string) ($values['filename'] ?? ''), PATHINFO_FILENAME); + } + + if ($target === 'posts' || $target === 'pages') { + $values['slug'] = ($values['slug'] ?? '') !== '' ? Str::slug((string) $values['slug']) : Str::slug((string) ($values['title'] ?? '')); + } + + foreach ($spec['required'] as $column) { + if (! isset($values[$column]) || $values[$column] === '') { + $result['skipped']++; + $result['problems'][] = 'row '.($number + 1).": no value for {$column}"; + + continue 2; + } + } + + $key = Arr::only($values, $spec['key']); + $model = $spec['model']; + $existing = $model::query()->where($key)->first(); + $existing ? $result['updated']++ : $result['created']++; + + if (! $dry) { + $existing ? $existing->update($values) : $model::query()->create($values); + } + } + + return $result; + } + + private function convert(string $column, mixed $value): mixed + { + return match ($column) { + 'tags' => $this->tags($value), + 'reasons', 'answers', 'notes' => $this->json($value), + 'notify_failed' => filter_var($value, FILTER_VALIDATE_BOOLEAN), + 'taps' => max(0, (int) $value), + 'opened_at', 'handled_at', 'notified_at' => $value === null || $value === '' ? null : $value, + 'is_featured', 'is_published', 'is_visible' => filter_var($value, FILTER_VALIDATE_BOOLEAN), + 'size', 'width', 'height' => $value === null || $value === '' ? null : max(0, (int) $value), + 'rating' => $value === null || $value === '' ? null : max(1, min(5, (int) $value)), + 'published_at' => $value === null || $value === '' ? null : $value, + default => is_string($value) ? trim($value) : $value, + }; + } + + /** @return array|null a JSON column as it comes out of another table: text, or already a list */ + private function json(mixed $value): ?array + { + if (is_string($value)) { + $value = json_decode($value, true); + } + + return is_array($value) && $value !== [] ? $value : null; + } + + /** @return list */ + private function tags(mixed $value): array + { + if (is_string($value)) { + $decoded = json_decode($value, true); + $value = is_array($decoded) ? $decoded : array_map('trim', explode(',', $value)); + } + + return array_values(array_filter(array_map(fn ($tag) => is_string($tag) ? trim($tag) : '', (array) $value), fn ($tag) => $tag !== '')); + } +} diff --git a/src/Support/IriksStorage/Adapter.php b/src/Support/IriksStorage/Adapter.php new file mode 100644 index 0000000..033617f --- /dev/null +++ b/src/Support/IriksStorage/Adapter.php @@ -0,0 +1,208 @@ + `iriksit`) whose files live at the IriksIT API. The API knows files by an id of its own, not + * by a path, so every path that is written is remembered next to that id (table `storage_files`). A path that has no entry + * and no slash is taken for an id itself: that is how media rows that were made by a site's own code (the id as location) + * keep working. There are no folders, no visibility and no listing. + */ +class Adapter implements FilesystemAdapter +{ + public function __construct(private readonly Client $client) {} + + public function fileExists(string $path): bool + { + $id = $this->id($path); + + if ($id === null) { + return false; + } + + try { + return $this->client->details($id) !== null; + } catch (MediaStorageException $e) { + throw UnableToRetrieveMetadata::create($path, 'exists', $e->getMessage(), $e); + } + } + + public function directoryExists(string $path): bool + { + return false; + } + + public function write(string $path, string $contents, Config $config): void + { + $stream = fopen('php://temp', 'r+b'); + fwrite($stream, $contents); + rewind($stream); + + try { + $this->writeStream($path, $stream, $config); + } finally { + // The HTTP client closes what it sent itself. + if (is_resource($stream)) { + fclose($stream); + } + } + } + + public function writeStream(string $path, $contents, Config $config): void + { + try { + $stored = $this->client->store($contents, basename($path)); + } catch (MediaStorageException $e) { + throw UnableToWriteFile::atLocation($path, $e->getMessage(), $e); + } + + DB::table($this->table())->updateOrInsert(['path' => $path], ['remote_id' => $stored['id']]); + } + + public function read(string $path): string + { + $stream = $this->readStream($path); + $contents = stream_get_contents($stream); + is_resource($stream) && fclose($stream); + + return $contents === false ? throw UnableToReadFile::fromLocation($path) : $contents; + } + + public function readStream(string $path) + { + $id = $this->id($path) ?? throw UnableToReadFile::fromLocation($path, 'There is no such file.'); + + try { + $body = $this->client->open($id); + } catch (MediaStorageException $e) { + throw UnableToReadFile::fromLocation($path, $e->getMessage(), $e); + } + + $stream = fopen('php://temp', 'r+b'); + while (! $body->eof()) { + fwrite($stream, $body->read(1024 * 1024)); + } + $body->close(); + rewind($stream); + + return $stream; + } + + public function delete(string $path): void + { + $id = $this->id($path); + + if ($id === null) { + return; + } + + try { + $this->client->delete($id); + } catch (MediaStorageException $e) { + throw UnableToDeleteFile::atLocation($path, $e->getMessage(), $e); + } + + DB::table($this->table())->where('path', $path)->delete(); + } + + public function deleteDirectory(string $path): void + { + throw UnableToDeleteDirectory::atLocation($path, 'The IriksIT storage has no folders.'); + } + + public function createDirectory(string $path, Config $config): void + { + throw UnableToCreateDirectory::atLocation($path, 'The IriksIT storage has no folders.'); + } + + public function setVisibility(string $path, string $visibility): void + { + throw UnableToSetVisibility::atLocation($path, 'The IriksIT storage has no visibility.'); + } + + public function visibility(string $path): FileAttributes + { + throw UnableToRetrieveMetadata::visibility($path, 'The IriksIT storage has no visibility.'); + } + + public function mimeType(string $path): FileAttributes + { + $details = $this->details($path, 'mime_type'); + + return new FileAttributes($path, null, null, null, $details['mime_type'] ?? throw UnableToRetrieveMetadata::mimeType($path)); + } + + public function lastModified(string $path): FileAttributes + { + $created = $this->details($path, 'last_modified')['created_at'] ?? null; + + return new FileAttributes($path, null, null, $created !== null ? strtotime($created) ?: null : throw UnableToRetrieveMetadata::lastModified($path)); + } + + public function fileSize(string $path): FileAttributes + { + return new FileAttributes($path, $this->details($path, 'file_size')['size']); + } + + /** @return iterable */ + public function listContents(string $path, bool $deep): iterable + { + return []; + } + + public function move(string $source, string $destination, Config $config): void + { + throw UnableToMoveFile::fromLocationTo($source, $destination); + } + + public function copy(string $source, string $destination, Config $config): void + { + throw UnableToCopyFile::fromLocationTo($source, $destination); + } + + /** @return array{size: int, mime_type: string|null, created_at: string|null} */ + private function details(string $path, string $what): array + { + $id = $this->id($path) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.'); + + try { + return $this->client->details($id) ?? throw UnableToRetrieveMetadata::create($path, $what, 'There is no such file.'); + } catch (MediaStorageException $e) { + throw UnableToRetrieveMetadata::create($path, $what, $e->getMessage(), $e); + } + } + + /** The id the API gave to what was written at this path, or the path itself when it looks like an id. */ + private function id(string $path): ?string + { + $id = DB::table($this->table())->where('path', $path)->value('remote_id'); + + if (is_string($id)) { + return $id; + } + + return $path !== '' && ! str_contains($path, '/') ? $path : null; + } + + private function table(): string + { + return Names::table('storage_files'); + } +} diff --git a/src/Support/IriksStorage/Client.php b/src/Support/IriksStorage/Client.php new file mode 100644 index 0000000..d12c2de --- /dev/null +++ b/src/Support/IriksStorage/Client.php @@ -0,0 +1,293 @@ +value('url') !== '' && $this->value('email') !== '' && $this->value('password') !== ''; + } + + /** + * Store a file. The `id` that comes back is the only handle to it afterwards. + * + * @param resource $stream + * @return array{id: string, size: int, mime_type: string|null, checksum: string|null} + * + * @throws MediaStorageException + */ + public function store($stream, string $filename): array + { + $response = $this->call(fn (PendingRequest $request) => $request->attach('file', $stream, $filename)->post($this->url('/storage'), ['priority' => 'normal'])); + $data = $response->json('data'); + + if ($response->failed() || ! is_array($data) || ! is_string($data['id'] ?? null) || $data['id'] === '') { + throw $this->failure('store a file', $response); + } + + return [ + 'id' => $data['id'], + 'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0, + 'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null, + 'checksum' => is_string($data['checksum'] ?? null) ? $data['checksum'] : null, + ]; + } + + /** + * The content of a file as a stream; read it and close it. + * + * @throws MediaStorageException with status 404 when the API does not know the file + */ + public function open(string $id): StreamInterface + { + $response = $this->call(fn (PendingRequest $request) => $request->withOptions(['stream' => true])->get($this->url('/storage/'.rawurlencode($id).'/download'))); + + if ($response->status() !== 200) { + throw $this->failure('download a file', $response); + } + + return $response->toPsrResponse()->getBody(); + } + + /** + * What the API knows of a file, or null when it does not know it. + * + * @return array{size: int, mime_type: string|null, created_at: string|null}|null + * + * @throws MediaStorageException + */ + public function details(string $id): ?array + { + $response = $this->call(fn (PendingRequest $request) => $request->get($this->url('/storage/'.rawurlencode($id)))); + + if ($response->status() === 404) { + return null; + } + + $data = $response->json('data'); + + if ($response->failed() || ! is_array($data)) { + throw $this->failure('read a file', $response); + } + + return [ + 'size' => is_numeric($data['size'] ?? null) ? (int) $data['size'] : 0, + 'mime_type' => is_string($data['mime_type'] ?? null) ? $data['mime_type'] : null, + 'created_at' => is_string($data['created_at'] ?? null) ? $data['created_at'] : null, + ]; + } + + /** + * Delete a file. One the API no longer knows counts as deleted. + * + * @throws MediaStorageException + */ + public function delete(string $id): void + { + $response = $this->call(fn (PendingRequest $request) => $request->delete($this->url('/storage/'.rawurlencode($id)))); + + if ($response->failed() && $response->status() !== 404) { + throw $this->failure('delete a file', $response); + } + } + + /** + * Whether the account can log in at all: the check behind a "test the connection" button. + * + * @throws MediaStorageException + */ + public function check(): void + { + $this->token(); + } + + /** + * What the tokens of pieces of work cost, as the API worked it out with the price list and the euro rate of each day + * (`POST /tools/ai/cost`, permission `ai.pricing`). A row it has no price or rate for is left out; null when it cannot answer. + * + * @param list}> $items + * @return array|null by reference + */ + public function tokenCosts(array $items): ?array + { + if (! $this->isConfigured() || $items === []) { + return null; + } + + try { + $response = $this->call(fn (PendingRequest $request) => $request->timeout(15)->post($this->url('/tools/ai/cost'), ['items' => $items])); + } catch (MediaStorageException) { + return null; + } + + if ($response->failed()) { + return null; + } + + $costs = []; + $answer = $response->json('data.items'); + + foreach (is_array($answer) ? $answer : [] as $item) { + if (! is_array($item)) { + continue; + } + + $reference = $item['reference'] ?? null; + $usd = is_array($item['usd'] ?? null) ? ($item['usd']['total'] ?? null) : null; + $rate = is_array($item['exchange_rate'] ?? null) ? ($item['exchange_rate']['usd_per_eur'] ?? null) : null; + + if (is_string($reference) && is_numeric($usd) && is_numeric($item['eur'] ?? null) && is_numeric($rate) && (float) $rate > 0) { + $costs[$reference] = ['usd' => (float) $usd, 'eur' => (float) $item['eur'], 'usd_per_eur' => (float) $rate]; + } + } + + return $costs; + } + + /** + * Runs a call with the current token. A 401 means the token was revoked on the API's side: forget it, log in + * again and try once more. + * + * @param \Closure(PendingRequest): Response $call + * + * @throws MediaStorageException + */ + private function call(\Closure $call): Response + { + try { + $response = $call($this->request($this->token())); + + if ($response->status() !== 401) { + return $response; + } + + Cache::forget(self::TOKEN); + Cache::forget(self::REFRESH); + + return $call($this->request($this->token())); + } catch (MediaStorageException $e) { + throw $e; + } catch (Throwable) { + throw new MediaStorageException('The IriksIT storage could not be reached.'); + } + } + + private function request(string $token): PendingRequest + { + $timeout = $this->config['timeout'] ?? null; + + return Http::acceptJson()->withoutRedirecting()->withToken($token)->connectTimeout(5)->timeout(is_numeric($timeout) ? (int) $timeout : 300); + } + + /** @throws MediaStorageException */ + private function token(): string + { + $token = $this->cached(self::TOKEN); + + if ($token !== null) { + return $token; + } + + $refresh = $this->cached(self::REFRESH); + + if ($refresh !== null) { + $response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20)->withToken($refresh)->post($this->url('/auth/refresh')); + + if ($response->successful() && ($kept = $this->keep($response->json('data'))) !== null) { + return $kept; + } + + Cache::forget(self::REFRESH); + } + + if (! $this->isConfigured()) { + throw new MediaStorageException('No IriksIT account is set for the storage (address, email and password).'); + } + + $response = Http::acceptJson()->withoutRedirecting()->connectTimeout(5)->timeout(20) + ->post($this->url('/auth/login'), ['email' => $this->value('email'), 'password' => $this->value('password')]); + + if ($response->failed()) { + throw new MediaStorageException("The IriksIT login failed (HTTP {$response->status()}).", $response->status()); + } + + return $this->keep($response->json('data')) ?? throw new MediaStorageException('The IriksIT API sent a login answer without a token.'); + } + + /** Remembers the tokens of a login answer until they expire (a minute early) and returns the access token. */ + private function keep(mixed $data): ?string + { + if (! is_array($data) || ! is_string($data['token'] ?? null) || $data['token'] === '' || ! is_string($data['expire'] ?? null)) { + return null; + } + + Cache::put(self::TOKEN, Crypt::encryptString($data['token']), Carbon::parse($data['expire'])->subMinute()); + + if (is_string($data['refresh_token'] ?? null) && is_string($data['refresh_expire'] ?? null)) { + Cache::put(self::REFRESH, Crypt::encryptString($data['refresh_token']), Carbon::parse($data['refresh_expire'])->subMinute()); + } + + return $data['token']; + } + + private function cached(string $key): ?string + { + $value = Cache::get($key); + + try { + return is_string($value) ? Crypt::decryptString($value) : null; + } catch (Throwable) { + return null; + } + } + + private function failure(string $action, Response $response): MediaStorageException + { + $reason = $response->json('message'); + $detail = is_string($reason) && $reason !== '' ? ': '.mb_substr($reason, 0, 200) : ''; + $retry = $response->header('Retry-After'); + + return new MediaStorageException( + "The IriksIT storage could not {$action} (HTTP {$response->status()}{$detail}).", + $response->status(), + is_numeric($retry) ? (int) $retry : null, + ); + } + + private function url(string $path): string + { + return rtrim($this->value('url'), '/').$path; + } + + private function value(string $key): string + { + $value = $this->config[$key] ?? ''; + + return is_string($value) ? trim($value) : ''; + } +} diff --git a/src/Support/Leads/Intake.php b/src/Support/Leads/Intake.php new file mode 100644 index 0000000..afd5aa8 --- /dev/null +++ b/src/Support/Leads/Intake.php @@ -0,0 +1,130 @@ + $attributes what the form gave, already validated: kind, name, phone, email, message, about, answers, ... + * @param int|null $seconds how long the form was open (see `secondsOpen()`) + */ + public function take(array $attributes, ?int $seconds, string $ip, string $userAgent = ''): Lead + { + $attributes['ip'] = $ip; + $message = $attributes['message'] ?? null; + + $lead = Lead::create([ + ...$attributes, + ...$this->screening->screen($attributes, $seconds), + 'message_hash' => Lead::hashOf(is_string($message) ? $message : null), + // Where the visit came from: a site that counts its visits says so (`manager.leads.source`, an invokable class + // that gets the address and the browser and returns channel and source). + ...$this->source($ip, $userAgent), + ]); + + // Only a real request is worth a mail: to the owner, and back to whoever sent it. A confirmation for junk would be mail + // to an address someone else made up. + if ($lead->folder === Lead::INBOX) { + $this->tellTheOwner($lead); + $this->confirm($lead); + } + + return $lead; + } + + /** Mails the owner. A mail that cannot be sent never loses the request: it is stored already. */ + public function tellTheOwner(Lead $lead): void + { + $to = (string) config('manager.leads.notify'); + + if ($to === '') { + return; + } + + try { + Mail::to($to)->send(new LeadReceived($lead)); + $lead->update(['notified_at' => now(), 'notify_failed' => false]); + } catch (Throwable $e) { + report($e); + $lead->update(['notify_failed' => true]); + } + } + + /** A signed moment for a form: sent back with it, it tells how long the form was open. */ + public static function formToken(): string + { + return Crypt::encryptString((string) now()->timestamp); + } + + /** How many seconds a form was open, or null when its token says nothing (missing, tampered with, too old). */ + public static function secondsOpen(string $token): ?int + { + if ($token === '' || strlen($token) > 1000) { + return null; + } + + try { + $seconds = now()->timestamp - (int) Crypt::decryptString($token); + } catch (DecryptException) { + return null; + } + + return $seconds < 0 || $seconds > max(1, (int) config('manager.leads.max_hours', 24)) * 3600 ? null : $seconds; + } + + private function confirm(Lead $lead): void + { + if (! config('manager.leads.confirm') || $lead->email === null || $lead->email === '') { + return; + } + + try { + Mail::to($lead->email)->send(new LeadConfirmation($lead)); + } catch (Throwable $e) { + report($e); + } + } + + /** + * Where the visit came from. A site that counts its visits with the statistics module gets it for free; another source is + * `manager.leads.source`, an invokable class that gets the address and the browser and returns `channel` and `source`. + * + * @return array + */ + private function source(string $ip, string $userAgent): array + { + $class = config('manager.leads.source'); + + try { + if (is_string($class) && class_exists($class)) { + $found = (array) app($class)($ip, $userAgent); + } elseif (app(ModuleRegistry::class)->enabled('statistics')) { + $found = app(VisitRecorder::class)->sourceOf($ip, $userAgent); + } else { + return []; + } + + return array_intersect_key($found, ['channel' => 1, 'source' => 1]); + } catch (Throwable) { + return []; + } + } +} diff --git a/src/Support/Leads/Phone.php b/src/Support/Leads/Phone.php new file mode 100644 index 0000000..cf50274 --- /dev/null +++ b/src/Support/Leads/Phone.php @@ -0,0 +1,47 @@ += 9 && strlen($digits) <= 15 ? $digits : null; + } + + /** Whether the number is of the home country. */ + public static function isHome(string $number): bool + { + $digits = self::international($number); + + return $digits !== null && str_starts_with($digits, self::country()); + } + + private static function country(): string + { + return preg_replace('/\D+/', '', (string) config('manager.leads.country_code', '31')) ?: '31'; + } +} diff --git a/src/Support/Leads/Report.php b/src/Support/Leads/Report.php new file mode 100644 index 0000000..92c2a3a --- /dev/null +++ b/src/Support/Leads/Report.php @@ -0,0 +1,83 @@ +upsert([['day' => now()->toDateString(), 'kind' => $kind, 'path' => mb_substr($path, 0, 255), 'taps' => 1]], ['day', 'kind', 'path'], ['taps' => DB::raw($table.'.taps + 1')]); + } + + /** @return array */ + public function over(int $days): array + { + $since = now()->subDays($days - 1)->startOfDay(); + + /** @var Collection $leads */ + $leads = Lead::query()->where('created_at', '>=', $since)->get(['id', 'kind', 'folder', 'page', 'channel', 'source', 'subject', 'outcome', 'handled_at']); + $real = $leads->where('folder', Lead::INBOX); + $taps = LeadTap::query()->where('day', '>=', $since->toDateString())->get(['kind', 'path', 'taps']); + + $ways = [ + ['name' => __('Calls (taps on the number)'), 'count' => self::total($taps->where('kind', LeadTap::CALL))], + ['name' => __('WhatsApp (taps on the button)'), 'count' => self::total($taps->where('kind', LeadTap::WHATSAPP))], + ]; + + foreach ((array) config('manager.leads.kinds', []) as $kind => $label) { + $ways[] = ['name' => __((string) $label), 'count' => $real->where('kind', $kind)->count()]; + } + + return [ + 'days' => $days, + 'requests' => $real->count(), + 'kept_away' => ['other' => $leads->where('folder', Lead::OTHER)->count(), 'spam' => $leads->where('folder', Lead::SPAM)->count()], + 'won' => $real->where('outcome', Lead::WON)->count(), + 'lost' => $real->where('outcome', Lead::LOST)->count(), + 'waiting' => $real->whereNull('handled_at')->count(), + 'ways' => $ways, + 'pages' => self::top($real->groupBy(fn (Lead $lead) => $lead->page ?? '(unknown)')), + 'sources' => self::top($real->groupBy(fn (Lead $lead) => trim(($lead->channel ?? 'unknown').($lead->source ? ': '.$lead->source : '')))), + 'subjects' => self::top($real->groupBy(fn (Lead $lead) => $lead->subject ?: '(none)')), + 'tap_pages' => $taps->groupBy('path')->map(fn (Collection $rows, string $path) => ['name' => $path, 'count' => self::total($rows)])->sortByDesc('count')->take(8)->values()->all(), + ]; + } + + /** @param Collection $taps */ + private static function total(Collection $taps): int + { + return $taps->reduce(fn (int $sum, LeadTap $tap) => $sum + $tap->taps, 0); + } + + /** + * The largest groups, with how many of each became a job. + * + * @param Collection> $groups + * @return list + */ + private static function top(Collection $groups): array + { + return array_values($groups->map(fn (Collection $leads, int|string $name) => [ + 'name' => (string) $name, 'count' => $leads->count(), 'won' => $leads->where('outcome', Lead::WON)->count(), + ])->sortByDesc('count')->take(8)->values()->all()); + } +} diff --git a/src/Support/Leads/Screening.php b/src/Support/Leads/Screening.php new file mode 100644 index 0000000..a3cf425 --- /dev/null +++ b/src/Support/Leads/Screening.php @@ -0,0 +1,167 @@ + $lead the attributes of the request + * @param int|null $seconds how long the form was open; null when that could not be told + * @return array{folder: string, reasons: list} + */ + public function screen(array $lead, ?int $seconds): array + { + $message = self::text($lead['message'] ?? null); + $email = mb_strtolower(self::text($lead['email'] ?? null)); + $phone = self::text($lead['phone'] ?? null); + $ip = self::text($lead['ip'] ?? null); + + if (($block = $this->blocked($email, $phone, $ip)) !== null) { + return ['folder' => Lead::SPAM, 'reasons' => [$block]]; + } + + $spam = 0; + $other = 0; + $reasons = []; + + $links = preg_match_all('#https?://|www\.|\b[a-z0-9-]+\.(?:com|net|org|info|biz|ru|cn|xyz|top|online|site)\b#i', $message); + if ($links > 0) { + $spam += $links > 1 ? 5 : 3; + $reasons[] = $links > 1 ? 'Several links in the text' : 'A link in the text'; + } + + $words = $this->acquisitionWords($message); + if ($words !== []) { + $other += min(6, 2 * count($words)); + $reasons[] = 'Words of selling to a business: '.implode(', ', array_slice($words, 0, 5)); + } + + if ($message !== '' && ! $this->inExpectedLanguage($message)) { + $spam += 3; + $reasons[] = 'The text is not in the expected language'; + } + + if ($seconds === null) { + $spam += 2; + $reasons[] = 'The form could not tell how long it was open'; + } elseif ($seconds < self::number('min_seconds')) { + $spam += 4; + $reasons[] = "Sent within {$seconds} seconds of opening the form"; + } + + if ($email !== '' && in_array(substr((string) strrchr($email, '@'), 1), self::list('throwaway_domains'), true)) { + $spam += 4; + $reasons[] = 'A throwaway mail address'; + } + + $hash = Lead::hashOf($message); + if ($hash !== null && Lead::query()->where('message_hash', $hash)->exists()) { + $spam += 4; + $reasons[] = 'The same text was sent before'; + } + + // Worth knowing, but no reason to put a request aside: it may be a holiday home. + if ($phone !== '' && ! Phone::isHome($phone)) { + $reasons[] = 'Note: the phone number is not of this country'; + } + + $chosenOther = ($lead['about'] ?? 'job') === 'other'; + $folder = match (true) { + $spam >= self::number('spam_from') => Lead::SPAM, + $chosenOther, $other >= self::number('other_from') => Lead::OTHER, + default => Lead::INBOX, + }; + + if ($chosenOther) { + array_unshift($reasons, 'The visitor chose "something else"'); + } + + return ['folder' => $folder, 'reasons' => $reasons]; + } + + /** Why this sender is kept out, or null when they are not. */ + private function blocked(string $email, string $phone, string $ip): ?string + { + $domain = $email !== '' ? substr((string) strrchr($email, '@'), 1) : ''; + $digits = $phone !== '' ? Phone::international($phone) : null; + + $block = LeadBlock::query() + ->where(fn ($query) => $query->whereNull('expires_at')->orWhere('expires_at', '>', now())) + ->where(function ($query) use ($email, $domain, $digits, $ip) { + $query->whereRaw('1 = 0'); + foreach ([[LeadBlock::EMAIL, $email], [LeadBlock::DOMAIN, $domain], [LeadBlock::PHONE, (string) $digits], [LeadBlock::IP, $ip]] as [$type, $value]) { + if ($value !== '') { + $query->orWhere(fn ($q) => $q->where('type', $type)->where('value', $value)); + } + } + })->first(); + + return $block instanceof LeadBlock ? 'This sender is blocked ('.$block->type.')' : null; + } + + /** @return list the words of the list that are in the text, as whole words */ + private function acquisitionWords(string $message): array + { + $text = ' '.preg_replace('/[^\p{L}\p{N}]+/u', ' ', mb_strtolower($message)).' '; + + return array_values(array_filter(self::list('acquisition_words'), fn (string $word) => str_contains($text, ' '.$word.' '))); + } + + /** + * Whether a text is in the language the site expects (`manager.leads.language`: `nl`, `en` or null for no check): it has no + * other alphabet, and of the small words every sentence has the expected language is not outnumbered by the other one. + * A text too short to tell counts as fine. + */ + private function inExpectedLanguage(string $message): bool + { + $language = config('manager.leads.language'); + + if (! in_array($language, ['nl', 'en'], true)) { + return true; + } + + if (preg_match('/[\p{Cyrillic}\p{Han}\p{Arabic}\p{Hebrew}\p{Thai}\p{Hangul}\p{Hiragana}\p{Katakana}]/u', $message) === 1) { + return false; + } + + $words = preg_split('/[^\p{L}]+/u', mb_strtolower($message), -1, PREG_SPLIT_NO_EMPTY) ?: []; + + if (count($words) < 6) { + return true; + } + + $dutch = count(array_intersect($words, ['de', 'het', 'een', 'en', 'ik', 'wij', 'we', 'van', 'voor', 'met', 'niet', 'is', 'zijn', 'op', 'dat', 'die', 'graag', 'ook', 'bij', 'naar', 'om', 'te', 'er', 'aan', 'mijn', 'onze', 'u', 'je', 'kan', 'kunt', 'wil', 'hebben', 'heb', 'of', 'als', 'maar'])); + $english = count(array_intersect($words, ['the', 'and', 'you', 'your', 'our', 'for', 'with', 'that', 'this', 'are', 'have', 'will', 'can', 'to', 'of', 'in', 'on', 'it', 'be', 'from', 'would', 'please', 'hello', 'hi', 'dear'])); + + return $language === 'nl' ? ($english === 0 || $dutch >= $english) : ($dutch === 0 || $english >= $dutch); + } + + private static function text(mixed $value): string + { + return is_string($value) ? trim($value) : ''; + } + + private static function number(string $key): int + { + $value = config("manager.leads.{$key}"); + + return is_numeric($value) ? (int) $value : 0; + } + + /** @return list */ + private static function list(string $key): array + { + $value = config("manager.leads.{$key}"); + + return is_array($value) ? array_values(array_filter($value, 'is_string')) : []; + } +} diff --git a/src/Support/Login/BaseLoginCheck.php b/src/Support/Login/BaseLoginCheck.php new file mode 100644 index 0000000..f4130d2 --- /dev/null +++ b/src/Support/Login/BaseLoginCheck.php @@ -0,0 +1,20 @@ + 'turnstile', 'type' => 'turnstile', 'site_key' => (string) config('manager.login.turnstile.site_key')]]; + } + + public function before(Request $request): void + { + $token = $request->string('turnstile')->limit(2048, '')->toString(); + + if ($token === '' || ! self::passes($token, (string) $request->ip())) { + throw ValidationException::withMessages(['turnstile' => __('Prove you are not a program, then log in again.')]); + } + } + + /** Whether Cloudflare says this token is good. A token that cannot be checked is not good. Also used by the public forms. */ + public static function passes(string $token, string $ip): bool + { + try { + $answer = Http::asForm()->timeout(5)->post(self::VERIFY, ['secret' => config('manager.login.turnstile.secret'), 'response' => $token, 'remoteip' => $ip]); + + return $answer->ok() && $answer->json('success') === true; + } catch (Throwable) { + return false; + } + } +} diff --git a/src/Support/LoginChecks.php b/src/Support/LoginChecks.php new file mode 100644 index 0000000..1f1f0fe --- /dev/null +++ b/src/Support/LoginChecks.php @@ -0,0 +1,47 @@ + */ + public function all(): array + { + $classes = array_values(array_unique([...(array) config('manager.login.checks', []), ...(Turnstile::configured() ? [Turnstile::class] : [])])); + $checks = []; + + foreach ($classes as $class) { + if (is_string($class) && is_subclass_of($class, LoginCheck::class)) { + $checks[] = app($class); + } + } + + return $checks; + } + + /** @return list> */ + public function fields(): array + { + return array_merge(...array_map(fn (LoginCheck $check) => $check->fields(), $this->all()) ?: [[]]); + } + + public function before(Request $request): void + { + foreach ($this->all() as $check) { + $check->before($request); + } + } + + public function after(Request $request, Authenticatable $user): void + { + foreach ($this->all() as $check) { + $check->after($request, $user); + } + } +} diff --git a/src/Support/Markdown.php b/src/Support/Markdown.php new file mode 100644 index 0000000..83373e4 --- /dev/null +++ b/src/Support/Markdown.php @@ -0,0 +1,37 @@ + 'escape', + 'allow_unsafe_links' => false, + 'external_link' => [ + 'internal_hosts' => array_values(array_filter([$host, ...(array) config('manager.markdown.internal_hosts', [])])), + 'open_in_new_window' => true, + 'noopener' => 'external', + 'noreferrer' => 'external', + ], + ], [new ExternalLinkExtension]); + } + + public static function toPlainText(string $markdown): string + { + $text = strip_tags(self::toHtml($markdown)); + + return trim((string) preg_replace('/\s+/', ' ', html_entity_decode($text, ENT_QUOTES | ENT_HTML5))); + } +} diff --git a/src/Support/MediaUsage.php b/src/Support/MediaUsage.php new file mode 100644 index 0000000..cef3f56 --- /dev/null +++ b/src/Support/MediaUsage.php @@ -0,0 +1,36 @@ +> */ + private array $sources = []; + + /** @param Closure(): iterable $source */ + public function register(Closure $source): void + { + $this->sources[] = $source; + } + + /** @return list */ + public function haystacks(): array + { + $texts = []; + + foreach ($this->sources as $source) { + foreach ($source() as $text) { + $texts[] = is_string($text) ? $text : ''; + } + } + + return $texts; + } +} diff --git a/src/Support/Menu.php b/src/Support/Menu.php new file mode 100644 index 0000000..c661789 --- /dev/null +++ b/src/Support/Menu.php @@ -0,0 +1,83 @@ +hasFull($user) ? self::FULL : self::SIMPLE; + } + + public function maySwitch(?object $user): bool + { + return $user !== null && config('manager.simple_view') && ($this->hasFull($user) || Gate::forUser($user)->allows('manager.switch')); + } + + /** + * @param list $allowed the permissions this account has + * @return list + */ + public function for(?object $user, array $allowed): array + { + if ($user === null) { + return []; + } + + $simple = $this->view($user) === self::SIMPLE; + $items = []; + + foreach ($this->modules->navigation() as $item) { + if (($item['permission'] ?? null) !== null && ! in_array($item['permission'], $allowed, true)) { + continue; + } + + if ($simple && ! $item['simple']) { + continue; + } + + $items[] = array_filter([ + 'label' => $simple ? ($item['simple_label'] ?? $item['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); + } + + return $items; + } + + private function hasFull(object $user): bool + { + return (method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin()) || Gate::forUser($user)->allows('manager.full'); + } +} diff --git a/src/Support/ModuleRegistry.php b/src/Support/ModuleRegistry.php new file mode 100644 index 0000000..2b7b9d2 --- /dev/null +++ b/src/Support/ModuleRegistry.php @@ -0,0 +1,262 @@ + */ + private array $all = []; + + /** + * @param list> $available + * @param array $switches + */ + public function __construct(array $available, private readonly array $switches) + { + foreach ($available as $class) { + $module = new $class; + $this->all[$module->key()] = $module; + } + } + + /** @return array every known module */ + public function all(): array + { + return $this->all; + } + + public function has(string $key): bool + { + return isset($this->all[$key]); + } + + public function enabled(string $key): bool + { + if (! $this->has($key)) { + return false; + } + + // A feature of the site with the name of the module is its one switch (see `Features`). + $feature = Features::all()[$key] ?? null; + + if ($feature !== null) { + return $feature['enabled']; + } + + return (bool) ($this->switches[$key] ?? $this->all[$key]->enabledByDefault()); + } + + /** @return array the modules that are on */ + public function active(): array + { + return array_filter($this->all, fn (Module $module) => $this->enabled($module->key())); + } + + /** + * A module that is on while one it needs is off is a configuration mistake: fail loudly at boot. + */ + public function validate(): void + { + foreach ($this->active() as $module) { + foreach ($module->requires() as $needed) { + if (! $this->enabled($needed)) { + throw new ModuleException("Manager module '{$module->key()}' needs module '{$needed}', which is off."); + } + } + } + } + + /** @return array permission value => permission, of the active modules only */ + public function permissions(): array + { + $permissions = []; + + foreach ($this->active() as $module) { + foreach ($module->permissions() as $permission) { + $permissions[$permission->value] = $permission; + } + } + + if (config('manager.simple_view')) { + $permissions['manager.full'] = new Permission('manager.full', 'See the whole manager, not only the simple screens', 'Manager'); + $permissions['manager.switch'] = new Permission('manager.switch', 'Switch between the simple and the whole manager', 'Manager'); + } + + return $permissions; + } + + /** @return list */ + public function permissionValues(): array + { + return array_keys($this->permissions()); + } + + /** + * The given values without what is no permission (any more), completed with what they + * need, in the order of the permissions. + * + * @param array $values + * @return list + */ + public function complete(array $values): array + { + $known = $this->permissions(); + $wanted = []; + + foreach ($values as $value) { + if (is_string($value) && isset($known[$value])) { + $wanted[$value] = true; + + foreach ($known[$value]->needs as $needed) { + $wanted[$needed] = true; + } + } + } + + return array_values(array_filter(array_keys($known), fn (string $value) => isset($wanted[$value]))); + } + + /** + * The list for the group form, per section. + * + * @return list}>}> + */ + public function catalogue(): array + { + $sections = []; + + foreach ($this->permissions() as $permission) { + $sections[__($permission->section)][] = ['value' => $permission->value, 'label' => __($permission->label), 'needs' => $permission->needs]; + } + + $catalogue = []; + foreach ($sections as $section => $permissions) { + $catalogue[] = ['section' => $section, 'permissions' => $permissions]; + } + + return $catalogue; + } + + /** + * The menu: what the modules give, changed by config `manager.menu`, in order. An item has `label`, + * `route` (or `url` for a link of the site's own) and `permission`, and may add `section` (a heading), + * `icon`, `order` (lower comes first; default 100), `simple` (shown in the simple view) and `new_tab`. + * + * @return list + */ + public function navigation(): array + { + $changes = (array) config('manager.menu.items', []); + $items = []; + + foreach ($this->active() as $module) { + foreach ($module->navigation() as $item) { + $short = $item['id'] ?? (isset($item['route']) ? Str::after($item['route'], Names::routePrefix()) : ''); + $item = [...$item, ...(array) ($changes[$short] ?? [])]; + + if (($item['hidden'] ?? false) === true) { + continue; + } + + $items[] = $item; + } + } + + foreach ((array) config('manager.menu.links', []) as $link) { + if (is_array($link) && isset($link['label'], $link['url'])) { + $items[] = $link + ['permission' => null]; + } + } + + $items = array_map(fn (array $item) => [ + ...$item, + 'label' => __($item['label']), + ...(isset($item['simple_label']) && $item['simple_label'] !== null ? ['simple_label' => __($item['simple_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); + + // PHP's sort is stable: items with the same order keep the order of the modules. + usort($items, fn (array $a, array $b) => $a['order'] <=> $b['order']); + + return array_values($items); + } + + /** + * The steps the modules add to the tour, for an account with these permissions. + * + * @param list $allowed + * @return list + */ + 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. + * + * @return array}> + */ + 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']]; + + foreach ($this->active() as $module) { + $actions = [...$actions, ...$module->actions()]; + } + + return $actions; + } + + /** @return array */ + public function views(): array + { + $views = ['dashboard' => 'Opened the dashboard', 'profile.show' => 'Opened own account']; + + foreach ($this->active() as $module) { + $views = [...$views, ...$module->views()]; + } + + return $views; + } + + /** @return list middleware of the active modules for `before` or `after` the site's own */ + public function middleware(string $position): array + { + $middleware = []; + + foreach ($this->active() as $module) { + array_push($middleware, ...($module->middleware()[$position] ?? [])); + } + + return $middleware; + } +} diff --git a/src/Support/Names.php b/src/Support/Names.php new file mode 100644 index 0000000..42f4384 --- /dev/null +++ b/src/Support/Names.php @@ -0,0 +1,33 @@ + '7 days', '30d' => '30 days', '12m' => 'A year']; + + public const DEFAULT_PERIOD = '30d'; + + private const LABELS = ['7d' => 'The last 7 days', '30d' => 'The last 30 days', '12m' => 'The last 12 months']; + + private const BEFORE = ['7d' => 'the 7 days before', '30d' => 'the 30 days before', '12m' => 'the 12 months before']; + + /** How a visit began, in the words of someone who does not build sites. */ + private const WAYS = [ + 'search' => 'Through Google or another search engine', + 'direct' => 'Straight to the site: the address typed or saved', + 'social' => 'Through social media', + 'share' => 'Through a post the site shared itself', + 'referral' => 'Through a link on another site', + 'campaign' => 'Through a campaign or an advertisement', + ]; + + public function __construct(private readonly Statistics $statistics, private readonly ModuleRegistry $modules) {} + + /** The key of a period that can be chosen; anything else is the default. */ + public static function period(string $key): string + { + return isset(self::PERIODS[$key]) ? $key : self::DEFAULT_PERIOD; + } + + /** Visitors of the last seven days, for the line under the button on the start screen. */ + public function visitorsThisWeek(): int + { + return $this->statistics->brief('7d')['totals']['visitors']; + } + + /** + * @param bool $withRequests whether the account may read the requests + * @return array + */ + public function over(string $key, bool $withRequests): array + { + $key = self::period($key); + $brief = $this->statistics->brief($key); + + $periods = []; + + foreach (self::PERIODS as $name => $button) { + $periods[] = ['key' => $name, 'button' => __($button)]; + } + + $found = []; + + foreach ($brief['channels'] as $channel) { + $found[] = ['name' => __(self::WAYS[$channel['name']] ?? 'In another way'), 'visits' => $channel['visits']]; + } + + $leads = $this->modules->enabled('leads'); + + return [ + 'period' => ['key' => $key, 'label' => __(self::LABELS[$key]), 'before' => __(self::BEFORE[$key])], + 'periods' => $periods, + 'visitors' => $brief['totals']['visitors'], + 'visitors_before' => $brief['previous']['visitors'] ?? null, + 'page_views' => $brief['totals']['page_views'], + 'steps' => array_map(fn (array $step) => ['label' => $step['label'], 'visitors' => $step['visitors']], $brief['series']), + 'pages' => array_map(fn (array $page) => ['name' => $page['title'] ?? $page['path'], 'path' => $page['path'], 'views' => $page['views']], $brief['pages']), + 'found' => $found, + 'articles' => array_map(fn (array $post) => ['title' => $post['title'], 'views' => $post['views']], array_slice($brief['posts'], 0, 5)), + 'contact' => $leads ? ['calls' => $this->taps(LeadTap::CALL, $brief['from'], $brief['to']), 'whatsapp' => $this->taps(LeadTap::WHATSAPP, $brief['from'], $brief['to'])] : null, + // What came in is only for who may read the requests. + 'requests' => $leads && $withRequests ? $this->requests($brief['from'], $brief['to']) : null, + ]; + } + + private function taps(string $kind, string $from, string $to): int + { + return (int) LeadTap::query()->whereBetween('day', [$from, $to])->where('kind', $kind)->sum('taps'); + } + + /** + * The requests of the period: how many were real, what became of them, and what they were about. + * + * @return array{count: int, won: int, waiting: int, kept_away: int, subjects: list} + */ + private function requests(string $from, string $to): array + { + /** @var Collection $leads */ + $leads = Lead::query() + ->whereBetween('created_at', [CarbonImmutable::parse($from)->startOfDay(), CarbonImmutable::parse($to)->endOfDay()]) + ->get(['id', 'folder', 'subject', 'outcome', 'handled_at']); + $real = $leads->where('folder', Lead::INBOX); + + $subjects = []; + + foreach ($real->groupBy(fn (Lead $lead) => $lead->subject ?: __('Something else')) as $name => $group) { + $subjects[] = ['name' => (string) $name, 'count' => $group->count()]; + } + + usort($subjects, fn (array $a, array $b) => $b['count'] <=> $a['count'] ?: strcmp($a['name'], $b['name'])); + + return [ + 'count' => $real->count(), + 'won' => $real->where('outcome', Lead::WON)->count(), + 'waiting' => $real->whereNull('handled_at')->count(), + 'kept_away' => $leads->count() - $real->count(), + 'subjects' => array_slice($subjects, 0, 8), + ]; + } +} diff --git a/src/Support/Permission.php b/src/Support/Permission.php new file mode 100644 index 0000000..dce806c --- /dev/null +++ b/src/Support/Permission.php @@ -0,0 +1,23 @@ +.`, also the name of the gate + * @param string $label what the group form says next to the tick box + * @param string $section the heading it is listed under + * @param list $needs values this one is useless without; a group that gets this gets those too + */ + public function __construct( + public string $value, + public string $label, + public string $section, + public array $needs = [], + ) {} +} diff --git a/src/Support/Permissions/RoleMap.php b/src/Support/Permissions/RoleMap.php new file mode 100644 index 0000000..6034bd1 --- /dev/null +++ b/src/Support/Permissions/RoleMap.php @@ -0,0 +1,33 @@ + ['posts.view', 'posts.write'], 'owner' => ['*']]` (`*` is everything). The attribute is + * `manager.permissions.role_attribute`. + */ +final class RoleMap implements PermissionResolver +{ + public function permissions(Authenticatable $user): array + { + $roles = $user->{(string) config('manager.permissions.role_attribute', 'role')} ?? []; + $roles = $roles instanceof Collection ? $roles->all() : (array) $roles; + $map = (array) config('manager.permissions.roles', []); + $out = []; + + foreach ($roles as $role) { + $name = is_object($role) ? (string) ($role->name ?? '') : (string) (is_scalar($role) ? $role : ''); + + foreach ((array) ($map[$name] ?? []) as $permission) { + $out[] = (string) $permission; + } + } + + return array_values(array_unique($out)); + } +} diff --git a/src/Support/Permissions/Sources.php b/src/Support/Permissions/Sources.php new file mode 100644 index 0000000..638f43c --- /dev/null +++ b/src/Support/Permissions/Sources.php @@ -0,0 +1,45 @@ + what the roles of the site allow (empty in `groups` mode) */ + public static function fromHost(Authenticatable $user): array + { + if (self::mode() === 'groups') { + return []; + } + + $class = config('manager.permissions.resolver'); + $resolver = is_string($class) && is_subclass_of($class, PermissionResolver::class) ? app($class) : (config('manager.permissions.roles') ? new RoleMap : null); + + if ($resolver === null) { + return []; + } + + $known = app(ModuleRegistry::class)->permissionValues(); + $given = $resolver->permissions($user); + + return in_array('*', $given, true) ? $known : array_values(array_filter($given, fn ($value) => is_string($value) && in_array($value, $known, true))); + } + + private static function mode(): string + { + return in_array(config('manager.permissions.mode'), ['groups', 'host', 'merge'], true) ? config('manager.permissions.mode') : 'groups'; + } +} diff --git a/src/Support/Presets.php b/src/Support/Presets.php new file mode 100644 index 0000000..72f3227 --- /dev/null +++ b/src/Support/Presets.php @@ -0,0 +1,271 @@ + [ + * 'services' => Presets::services(['model' => App\Models\Service::class, 'feature' => 'services']), + * 'projects' => Presets::projects(['model' => App\Models\Project::class, 'feature' => 'projects'], serviceModel: App\Models\Service::class), + * ], + * + * Without `model` the records are kept in the package's own table. The field keys are the column names of the + * usual site tables (`title`, `summary`, `is_active`, `sort_order`), so a site that has such tables points `model` at them. + */ +final class Presets +{ + /** What the simple face says for each field of a preset, in plain words. */ + private const SIMPLE = [ + 'services' => [ + 'title' => ['label' => 'Name of the service', 'help' => 'What you call it, for example "Roof extensions".'], + 'summary' => ['label' => 'Short description', 'help' => 'One sentence that shows under the name.'], + 'body' => ['label' => 'The full story', 'help' => 'What you do and how you work. This is the text on the page of this service.'], + 'photo' => ['label' => 'Main photo'], + 'points' => ['label' => 'What you do', 'help' => 'Short lines, one per line.'], + 'faq' => ['label' => 'Questions people ask', 'help' => 'Add the questions you hear often, with your answer.'], + 'is_active' => ['label' => 'Show this on my website'], + ], + 'projects' => [ + 'title' => ['label' => 'Name of the job', 'help' => 'For example "New kitchen in a farmhouse".'], + 'service_id' => ['label' => 'What kind of work was it?'], + 'place' => ['label' => 'Town', 'help' => 'The town only, never the street.'], + 'year' => ['label' => 'Year it was finished'], + 'story' => ['label' => 'What happened', 'help' => 'A few sentences about the job. Leave an empty line between paragraphs.'], + 'photo' => ['label' => 'Main photo'], + 'photos_agreed' => ['label' => 'The customer said these photos may be on the website'], + 'on_home' => ['label' => 'Show this on the home page'], + 'is_active' => ['label' => 'Show this on my website'], + ], + 'testimonials' => [ + 'name' => ['label' => 'Who said it'], + 'role' => ['label' => 'Where they live or what they do', 'help' => 'For example "Utrecht" or "owner of a bakery".'], + 'quote' => ['label' => 'What they said', 'help' => 'Their words, as they gave them.'], + 'is_active' => ['label' => 'Show this on my website'], + ], + 'menu' => [ + 'label' => ['label' => 'What the button says'], + 'url' => ['label' => 'Where it goes', 'help' => 'A page of your website, like /contact, or a full web address.'], + 'opens_new_tab' => ['label' => 'Open it in a new tab'], + 'is_active' => ['label' => 'Show this on my website'], + ], + 'socials' => [ + 'label' => ['label' => 'Name', 'help' => 'For example "Facebook".'], + 'url' => ['label' => 'Web address of your page'], + 'is_active' => ['label' => 'Show this on my website'], + ], + 'business' => [ + 'name' => ['label' => 'Name of your business'], + 'owner' => ['label' => 'Your first name', 'help' => 'Used on buttons such as "Call Alex".'], + 'phone' => ['label' => 'Your phone number', 'help' => 'As you want people to read it. It shows on every page, and behind the Call button.'], + 'whatsapp' => ['label' => 'Your WhatsApp number', 'help' => 'Leave it empty and there are no WhatsApp buttons on the website.'], + 'email' => ['label' => 'Your mail address', 'help' => 'It is never printed on the website, so spammers cannot find it. A visitor gets it by pressing a button.'], + 'street' => ['label' => 'Street and number'], + 'kvk' => ['label' => 'Chamber of Commerce number'], + 'vat' => ['label' => 'VAT number', 'help' => 'As on your invoices. Not sure? Leave it empty.'], + 'opening_hours' => ['label' => 'When people can reach you', 'help' => 'One line per day or group of days, as you want it read.'], + 'towns' => ['label' => 'Towns where you work', 'help' => 'One town per line.'], + ], + ]; + + /** What the simple face calls a list as a whole. */ + private const SIMPLE_NAMES = [ + 'testimonials' => ['label' => 'What customers say', 'singular' => 'Customer review'], + 'projects' => ['label' => 'Our jobs', 'singular' => 'Job'], + 'menu' => ['label' => 'Buttons at the top', 'singular' => 'Button'], + 'socials' => ['label' => 'Your pages on other sites', 'singular' => 'Link'], + 'business' => ['title' => 'About your business'], + ]; + + /** @param array $override */ + public static function services(array $override = []): array + { + return self::make('services', [ + 'label' => 'Services', 'singular' => 'Service', 'hint' => 'What you do, each with a page of its own', + 'columns' => ['title', 'summary', 'is_active'], 'order' => ['sort_order', 'asc'], + 'fields' => [ + 'title' => ['label' => 'Title', 'type' => 'text', 'required' => true], + 'slug' => ['label' => 'Address', 'type' => 'slug', 'from' => 'title', 'required' => true], + 'summary' => ['label' => 'One line for a card', 'type' => 'text', 'max' => 300], + 'body' => ['label' => 'Text of the page', 'type' => 'markdown'], + 'photo' => ['label' => 'Photo', 'type' => 'media'], + 'gallery' => ['label' => 'More photos', 'type' => 'media_list', 'advanced' => true], + 'points' => ['label' => 'What we do', 'type' => 'list', 'help' => 'Short lines.'], + 'faq' => ['label' => 'Questions and answers', 'type' => 'repeater', 'items' => self::questionItems()], + 'meta_description' => ['label' => 'Description for search engines', 'type' => 'text', 'max' => 300, 'advanced' => true], + 'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true], + 'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true], + ], + ], $override); + } + + /** + * @param array $override + * @param ?class-string $serviceModel the model of the services, to pick the kind of work a project belongs to + */ + public static function projects(array $override = [], ?string $serviceModel = null): array + { + $fields = [ + 'title' => ['label' => 'Title', 'type' => 'text', 'required' => true], + 'slug' => ['label' => 'Address', 'type' => 'slug', 'from' => 'title', 'required' => true], + ]; + + if ($serviceModel !== null) { + $fields['service_id'] = ['label' => 'Kind of work', 'type' => 'select', 'source' => ['model' => $serviceModel, 'label' => 'title', 'value' => 'id']]; + } + + return self::make('projects', [ + 'label' => 'Projects', 'singular' => 'Project', 'hint' => 'Finished jobs, with photos', + 'columns' => ['title', 'place', 'year', 'is_active'], 'order' => ['sort_order', 'asc'], + 'fields' => $fields + [ + 'place' => ['label' => 'Town', 'type' => 'text', 'max' => 120, 'help' => 'The town only, never a street.'], + 'year' => ['label' => 'Year', 'type' => 'number'], + 'story' => ['label' => 'Story', 'type' => 'textarea', 'help' => 'A few sentences, paragraphs separated by a blank line.'], + 'photo' => ['label' => 'Photo', 'type' => 'media'], + 'gallery' => ['label' => 'More photos', 'type' => 'media_list', 'advanced' => true], + 'before_photo' => ['label' => 'Photo before', 'type' => 'media', 'advanced' => true], + 'after_photo' => ['label' => 'Photo after', 'type' => 'media', 'advanced' => true], + 'photos_agreed' => ['label' => 'The customer agreed to these photos on the site', 'type' => 'toggle', 'default' => false], + 'on_home' => ['label' => 'Show on the home page', 'type' => 'toggle', 'default' => false], + 'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true], + 'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true], + ], + ], $override); + } + + /** @param array $override */ + public static function testimonials(array $override = []): array + { + return self::make('testimonials', [ + 'label' => 'Reviews', 'singular' => 'Review', 'hint' => 'What customers say about you', + 'columns' => ['name', 'role', 'is_active'], 'order' => ['sort_order', 'asc'], + 'fields' => [ + 'name' => ['label' => 'Name', 'type' => 'text', 'required' => true], + 'role' => ['label' => 'Place or function', 'type' => 'text'], + 'quote' => ['label' => 'What they said', 'type' => 'textarea', 'required' => true], + 'photo' => ['label' => 'Photo', 'type' => 'media', 'advanced' => true], + 'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true], + 'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true], + ], + ], $override); + } + + /** + * Work and projects of a person or a company, for a CV or "about" page: a title, role, period, a story, points, links and + * the technology used. `type` says which kind of entry it is (`work` or `project`; the site may offer other kinds with + * `$override['fields']['type']['options']`). + * + * @param array $override + */ + public static function experience(array $override = []): array + { + return self::make('experience', [ + 'label' => 'Experience', 'singular' => 'Experience', 'hint' => 'Work and projects for the CV', + 'columns' => ['title', 'type', 'period', 'is_active'], 'order' => ['sort_order', 'asc'], + 'fields' => [ + 'type' => ['label' => 'Kind', 'type' => 'select', 'required' => true, 'default' => 'work', 'options' => ['work' => 'Work', 'project' => 'Project']], + 'title' => ['label' => 'Title', 'type' => 'text', 'required' => true], + 'role' => ['label' => 'Role', 'type' => 'text'], + 'period' => ['label' => 'Period', 'type' => 'text', 'max' => 60, 'help' => 'As it should be read, for example 2021 - now.'], + 'summary' => ['label' => 'One line', 'type' => 'text'], + 'story' => ['label' => 'Story', 'type' => 'textarea', 'help' => 'A few sentences, paragraphs separated by a blank line.'], + 'bullets' => ['label' => 'Points', 'type' => 'list'], + 'links' => ['label' => 'Links', 'type' => 'repeater', 'items' => ['label' => ['label' => 'Text', 'type' => 'text'], 'url' => ['label' => 'Address', 'type' => 'url']]], + 'tech' => ['label' => 'Technology', 'type' => 'list'], + 'on_cv' => ['label' => 'Show on the CV', 'type' => 'toggle', 'default' => true], + 'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0, 'advanced' => true], + 'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true], + ], + ], $override); + } + + /** @param array $override */ + public static function menu(array $override = []): array + { + return self::make('menu', [ + 'label' => 'Menu', 'singular' => 'Menu item', 'hint' => 'The links at the top of the site', + 'columns' => ['label', 'url', 'is_active'], 'order' => ['sort_order', 'asc'], + 'fields' => [ + 'label' => ['label' => 'Text', 'type' => 'text', 'required' => true], + 'url' => ['label' => 'Address', 'type' => 'text', 'required' => true, 'help' => 'A page of your site (/contact) or a full address.'], + 'opens_new_tab' => ['label' => 'Opens in a new tab', 'type' => 'toggle', 'default' => false], + 'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0], + 'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true], + ], + ], $override); + } + + /** @param array $override */ + public static function socials(array $override = []): array + { + return self::make('socials', [ + 'label' => 'Social links', 'singular' => 'Link', 'hint' => 'Your pages on other sites', + 'columns' => ['label', 'url', 'is_active'], 'order' => ['sort_order', 'asc'], + 'fields' => [ + 'label' => ['label' => 'Name', 'type' => 'text', 'required' => true], + 'url' => ['label' => 'Address', 'type' => 'url', 'required' => true], + 'icon' => ['label' => 'Icon', 'type' => 'text', 'advanced' => true], + 'sort_order' => ['label' => 'Order', 'type' => 'number', 'default' => 0], + 'is_active' => ['label' => 'Shown on the site', 'type' => 'toggle', 'default' => true], + ], + ], $override); + } + + /** + * The page "Business details" for `manager.pages.definitions['business']`: what the site says about the business in its + * header, footer, contact page and legal pages. Entered once, read with `Page::contentFor('business')`. The address for + * visitors and the address where requests are mailed to are not meant to be printed in a page. + * + * @param array $override `title` and `fields` (merged per field) + * @return array{title: string, fields: array>} + */ + public static function business(array $override = []): array + { + return self::make('business', [ + 'title' => 'Business details', + 'fields' => [ + 'name' => ['label' => 'Name of the business', 'type' => 'text'], + 'owner' => ['label' => 'Owner', 'type' => 'text', 'help' => 'The first name is used on buttons such as "Call Alex".'], + 'phone' => ['label' => 'Phone number', 'type' => 'text', 'help' => 'As it should be read, for example 06 12 34 56 78. Shown on every page.'], + 'whatsapp' => ['label' => 'WhatsApp number', 'type' => 'text', 'help' => 'Leave empty to leave the WhatsApp buttons off the site.'], + 'email' => ['label' => 'Mail address for visitors', 'type' => 'text', 'help' => 'Never printed in a page: a visitor gets it by pressing a button.'], + 'street' => ['label' => 'Street and number', 'type' => 'text'], + 'postcode' => ['label' => 'Postcode', 'type' => 'text'], + 'city' => ['label' => 'Town', 'type' => 'text'], + 'kvk' => ['label' => 'Chamber of Commerce number', 'type' => 'text'], + 'vat' => ['label' => 'VAT number', 'type' => 'text', 'help' => 'As on your invoices. Leave empty when you are not sure.'], + 'opening_hours' => ['label' => 'Opening hours', 'type' => 'lines', 'help' => 'One line per day or group of days, as it should be read.'], + 'towns' => ['label' => 'Work area: the towns', 'type' => 'lines', 'help' => 'One per line.'], + 'maps_url' => ['label' => 'Link to the map', 'type' => 'url'], + ], + ], $override); + } + + /** @return array> */ + private static function questionItems(): array + { + return ['question' => ['label' => 'Question', 'type' => 'text'], 'answer' => ['label' => 'Answer', 'type' => 'textarea']]; + } + + /** + * What the site sets wins; `fields` are merged per field, so one field can change without the rest. + * + * @param array $preset + * @param array $override + */ + private static function make(string $name, array $preset, array $override): array + { + // The words of the simple face, for someone who is not a webmaster; a site overrides them like any other field. + foreach (self::SIMPLE[$name] ?? [] as $key => $simple) { + if (isset($preset['fields'][$key])) { + $preset['fields'][$key]['simple'] = $simple; + } + } + $preset['simple'] = self::SIMPLE_NAMES[$name] ?? []; + $fields = array_replace_recursive($preset['fields'], (array) ($override['fields'] ?? [])); + unset($override['fields']); + + return [...$preset, ...$override, 'fields' => $fields]; + } +} diff --git a/src/Support/Resources.php b/src/Support/Resources.php new file mode 100644 index 0000000..6eaf60f --- /dev/null +++ b/src/Support/Resources.php @@ -0,0 +1,130 @@ + ['label' => 'Services', 'singular' => 'Service', 'model' => App\Models\Service::class, + * 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => [...]] + */ +final class Resources +{ + /** Names the permissions of modules that exist already would clash with. */ + private const RESERVED = ['posts', 'pages', 'media', 'accounts', 'groups', 'audit', 'statistics', 'reviews', 'labels', 'profile', 'manager', 'records']; + + /** + * @return array>, columns: list, order: array{0: string, 1: string}, per_page: int}> + */ + public static function all(): array + { + $out = []; + + foreach ((array) config('manager.resources', []) as $key => $definition) { + if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) || in_array($key, self::RESERVED, true) || ! is_array($definition)) { + continue; + } + + // A resource of a feature that is switched off is not there: no menu item, no permissions, no screens. + if (isset($definition['feature']) && ! Features::on((string) $definition['feature'])) { + continue; + } + + $fields = Fields::normalize((array) ($definition['fields'] ?? [])); + $model = $definition['model'] ?? null; + $columns = array_values(array_filter((array) ($definition['columns'] ?? array_slice(array_keys($fields), 0, 3)), fn ($column) => isset($fields[$column]))); + $order = (array) ($definition['order'] ?? []); + + $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), + 'simple_label' => Fields::simpleText($definition, 'label'), + 'simple_singular' => Fields::simpleText($definition, 'singular'), + 'model' => is_string($model) && is_subclass_of($model, Eloquent::class) ? $model : null, + 'fields' => $fields, + 'columns' => $columns, + 'order' => [preg_match('/^[a-z_][a-z0-9_]*$/', (string) ($order[0] ?? '')) ? (string) $order[0] : 'id', ($order[1] ?? 'desc') === 'asc' ? 'asc' : 'desc'], + 'per_page' => max(5, min(200, (int) ($definition['per_page'] ?? 50))), + ]; + } + + return $out; + } + + /** @return ?array */ + public static function find(string $key): ?array + { + return self::all()[$key] ?? null; + } + + /** + * @param array $resource + * @return Builder + */ + public static function query(array $resource): Builder + { + [$column, $direction] = $resource['order']; + + if ($resource['model'] !== null) { + return $resource['model']::query()->orderBy($column, $direction)->orderBy('id', 'desc'); + } + + // The package's own table keeps the values in one JSON column. + $query = Record::query()->where('resource', $resource['key']); + + return $column !== 'id' && isset($resource['fields'][$column]) ? $query->orderBy('data->'.$column, $direction) : $query->orderBy('id', $column === 'id' ? $direction : 'desc'); + } + + /** + * @param array $resource + * @return array + */ + public static function row(array $resource, Eloquent $model): array + { + $stored = $resource['model'] === null ? (array) $model->getAttribute('data') : null; + $values = []; + + foreach ($resource['fields'] as $key => $field) { + $values[$key] = $stored !== null ? ($stored[$key] ?? $field['default']) : ($model->getAttribute($key) ?? $field['default']); + } + + return ['id' => $model->getKey(), 'values' => $values]; + } + + /** + * @param array $resource + * @param array $values cleaned by `Fields::clean` + */ + public static function save(array $resource, ?Eloquent $model, array $values): Eloquent + { + if ($resource['model'] === null) { + $model ??= new Record(['resource' => $resource['key']]); + $model->data = $values; + } else { + $model ??= new $resource['model']; + // Only the keys the site defined: the definition is the whitelist. + $model->forceFill($values); + } + + $model->save(); + + return $model; + } + + /** + * @param array $resource + */ + public static function record(array $resource, int|string $id): ?Eloquent + { + return self::query($resource)->reorder()->whereKey($id)->first(); + } +} diff --git a/src/Support/Revisions.php b/src/Support/Revisions.php new file mode 100644 index 0000000..5f78d8f --- /dev/null +++ b/src/Support/Revisions.php @@ -0,0 +1,118 @@ + ['services' => ['model' => App\Models\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']] + */ +final class Revisions +{ + /** How many states are kept per record unless config `manager.revisions.keep` says otherwise. */ + private const KEEP = 50; + + /** + * What has a history: key => model, the permissions to see and to put back, the attributes that are not part of it (for a + * post that is whether it is on the site: going back in time must not publish or hide anything). + * + * @return array, view: string, restore: string, except: list}> + */ + public static function types(): array + { + $types = [ + 'posts' => ['model' => Post::class, 'view' => 'posts.view', 'restore' => 'posts.write', 'except' => ['published_at']], + 'pages' => ['model' => Page::class, 'view' => 'pages.edit', 'restore' => 'pages.edit', 'except' => ['is_published']], + ]; + + foreach ((array) config('manager.revisions.types', []) as $key => $type) { + if (is_string($key) && preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) && is_array($type) && is_subclass_of($type['model'] ?? '', Eloquent::class)) { + $types[$key] = ['model' => $type['model'], 'view' => (string) ($type['view'] ?? $key.'.view'), 'restore' => (string) ($type['restore'] ?? $key.'.manage'), 'except' => array_values((array) ($type['except'] ?? []))]; + } + } + + return array_filter($types, fn (array $type) => ! in_array($type['model'], (array) config('manager.revisions.skip', []), true)); + } + + /** Starts keeping the history of every type: a save of a record writes its state, a delete removes its history. */ + public static function listen(): void + { + foreach (self::types() as $key => $type) { + $type['model']::saved(fn (Eloquent $model) => self::record($key, $model)); + $type['model']::deleted(fn (Eloquent $model) => Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->delete()); + } + } + + public static function record(string $key, Eloquent $model): ?Revision + { + $type = self::types()[$key] ?? null; + + if ($type === null || ! $model->getKey()) { + return null; + } + + $data = self::snapshot($model, $type['except']); + $latest = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->first(); + + if ($latest !== null && $latest->data == $data) { + return null; + } + + $user = auth()->user(); + $revision = Revision::query()->create([ + 'type' => $key, + 'subject_id' => $model->getKey(), + 'user_id' => $user?->getAuthIdentifier(), + 'user_name' => $user === null ? null : mb_substr((string) ($user->name ?? ''), 0, 255), + 'data' => $data, + 'changed' => $latest === null ? array_keys($data) : self::changed((array) $latest->data, $data), + 'created_at' => now(), + ]); + + // Keep the newest ones only. + $old = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->skip(max(5, (int) config('manager.revisions.keep', self::KEEP)))->take(1000)->pluck('id'); + $old->isNotEmpty() && Revision::query()->whereKey($old)->delete(); + + return $revision; + } + + /** + * Puts a state back. It is a save like any other, so the history shows it and the state before it is not lost. + * + * @param array{except: list} $type + */ + public static function restore(Eloquent $model, Revision $revision, array $type): Eloquent + { + $keep = array_flip([...$type['except'], $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]); + $model->forceFill(array_diff_key((array) $revision->data, $keep))->save(); + + return $model; + } + + /** + * @param list $except + * @return array + */ + private static function snapshot(Eloquent $model, array $except): array + { + $skip = array_flip([...$except, $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]); + + return array_diff_key($model->attributesToArray(), $skip); + } + + /** + * @param array $before + * @param array $after + * @return list + */ + private static function changed(array $before, array $after): array + { + return array_values(array_filter(array_keys($after + $before), fn ($key) => ($before[$key] ?? null) != ($after[$key] ?? null))); + } +} diff --git a/src/Support/Settings/Checks.php b/src/Support/Settings/Checks.php new file mode 100644 index 0000000..09f9378 --- /dev/null +++ b/src/Support/Settings/Checks.php @@ -0,0 +1,91 @@ + SomeClass::class`, a class with an `__invoke(): string` that returns what worked + * (for example "Connected") and throws when it did not (the message is shown as it is, so keep secrets out of it). + */ +class Checks +{ + /** @return array group name (as in the definitions) => check */ + public function all(): array + { + return [ + 'IriksIT API' => fn () => $this->iriksit(), + 'Login' => fn () => $this->turnstile(), + ...array_filter((array) config('manager.settings.checks', []), fn ($check) => is_string($check) && class_exists($check)), + ]; + } + + public function has(string $group): bool + { + return array_key_exists($group, $this->all()); + } + + /** @return array{ok: bool, message: string} */ + public function run(string $group): array + { + $check = $this->all()[$group] ?? null; + + if ($check === null) { + return ['ok' => false, 'message' => __('There is nothing to try here.')]; + } + + try { + return ['ok' => true, 'message' => (string) (is_string($check) ? app($check)() : $check())]; + } catch (Throwable $e) { + return ['ok' => false, 'message' => $e->getMessage()]; + } + } + + private function iriksit(): string + { + $client = new Client((array) config('manager.media.iriksit', [])); + + if (! $client->isConfigured()) { + throw new \RuntimeException(__('The address, the account and the password are not all filled in.')); + } + + try { + $client->check(); + } catch (MediaStorageException $e) { + throw new \RuntimeException(__('Logging in at the IriksIT API failed:').' '.$e->getMessage(), 0, $e); + } + + return __('Logged in at the IriksIT API.'); + } + + /** + * Cloudflare answers a known secret with "invalid-input-response" for a made-up token, and an unknown one with "invalid-input-secret": + * that tells the secret without needing a real visitor. + */ + private function turnstile(): string + { + $secret = (string) config('manager.login.turnstile.secret'); + + if ($secret === '' || (string) config('manager.login.turnstile.site_key') === '') { + throw new \RuntimeException(__('Turnstile is off: the site key and the secret are not both filled in.')); + } + + $answer = Http::asForm()->timeout(8)->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', ['secret' => $secret, 'response' => 'manager-check']); + $codes = (array) $answer->json('error-codes', []); + + if (in_array('invalid-input-secret', $codes, true) || in_array('missing-input-secret', $codes, true)) { + throw new \RuntimeException(__('Cloudflare does not know this secret key.')); + } + + if (! $answer->ok()) { + throw new \RuntimeException(__('Cloudflare did not answer properly.')); + } + + return __('Cloudflare knows this secret key.'); + } +} diff --git a/src/Support/Settings/Definitions.php b/src/Support/Settings/Definitions.php new file mode 100644 index 0000000..448333b --- /dev/null +++ b/src/Support/Settings/Definitions.php @@ -0,0 +1,168 @@ + label), + * `env` (the .env variable that is written along when the site allows it) and `permission` (a right on top of `settings.manage`). + * A secret is never sent back to a browser. + * + * They come from three places: the parts of the manager, the integrations the package knows (Turnstile, the IriksIT API) and + * the site itself (`manager.settings.definitions`, and `settings()` of a module of its own). Nothing else can be set: a key that + * is not defined is refused, so the screen can never write an arbitrary setting or .env line. + */ +class Definitions +{ + public const TYPES = ['toggle', 'text', 'url', 'number', 'select', 'secret']; + + public function __construct(private readonly ModuleRegistry $modules) {} + + /** @return array> keyed by config path */ + public function all(): array + { + $all = []; + + foreach ([...$this->parts(), ...$this->features(), ...$this->integrations(), ...$this->fromModules(), ...(array) config('manager.settings.definitions', [])] as $key => $definition) { + $key = is_string($key) ? $key : (string) ($definition['config'] ?? ''); + $definition = $this->normalise($key, (array) $definition); + + if ($definition !== null) { + $all[$key] = $definition; + } + } + + return $all; + } + + /** + * Turns what was typed into the value of the setting, or says it is no good. + * + * @param array $definition + * + * @throws \InvalidArgumentException + */ + public function cast(array $definition, mixed $raw): mixed + { + $bad = fn () => throw new \InvalidArgumentException('This value is not valid.'); + + return match ($definition['type']) { + 'toggle' => is_bool($raw) || in_array($raw, [0, 1, '0', '1', 'true', 'false'], true) ? filter_var($raw, FILTER_VALIDATE_BOOLEAN) : $bad(), + 'number' => is_numeric($raw) ? $raw + 0 : $bad(), + 'select' => is_string($raw) && array_key_exists($raw, $definition['options']) ? $raw : $bad(), + 'url' => is_string($raw) && mb_strlen($raw) <= 500 && preg_match('#^https?://[^\s<>"\']+$#i', $raw) === 1 ? $raw : $bad(), + default => is_string($raw) && mb_strlen($raw) <= 1000 && preg_match('/[\r\n\0]/', $raw) !== 1 ? trim($raw) : $bad(), + }; + } + + /** @return array|null */ + public function find(string $key): ?array + { + return $this->all()[$key] ?? null; + } + + /** @return array> */ + private function parts(): array + { + $parts = []; + + foreach ($this->modules->all() as $module) { + // Users and media are the core: without them there is no manager. + if (in_array($module->key(), ['users', 'media', 'settings'], true)) { + continue; + } + + // A feature of the site with the name of the module is its switch: it has its own toggle. + if (isset(Features::all()[$module->key()])) { + continue; + } + + $parts['manager.modules.'.$module->key()] = [ + 'label' => $module->label(), + 'type' => 'toggle', + 'group' => 'Parts of the manager', + 'env' => 'MANAGER_'.strtoupper($module->key()), + ]; + } + + return $parts; + } + + /** @return array> */ + private function features(): array + { + $features = []; + + foreach (Features::all() as $key => $feature) { + $features['manager.features.'.$key.'.enabled'] = [ + 'label' => $feature['label'], + 'type' => 'toggle', + 'group' => 'Features of the site', + 'help' => $feature['hint'], + 'env' => $feature['env'], + ]; + } + + return $features; + } + + /** @return array> */ + private function integrations(): array + { + $disks = array_keys((array) config('filesystems.disks', [])); + + return [ + 'manager.media.disk' => ['label' => 'Disk for new media files', 'type' => 'select', 'group' => 'Media', 'sensitive' => true, 'options' => array_combine($disks, $disks), 'env' => 'MANAGER_MEDIA_DISK'], + 'manager.media.iriksit.url' => ['label' => 'IriksIT API: address', 'type' => 'url', 'group' => 'IriksIT API', 'sensitive' => true, 'help' => 'With its version, for example https://api.iriks-it.nl/v1', 'env' => 'MANAGER_IRIKSIT_URL'], + 'manager.media.iriksit.email' => ['label' => 'IriksIT API: account', 'type' => 'text', 'group' => 'IriksIT API', 'sensitive' => true, 'env' => 'MANAGER_IRIKSIT_EMAIL'], + 'manager.media.iriksit.password' => ['label' => 'IriksIT API: password', 'type' => 'secret', 'group' => 'IriksIT API', 'env' => 'MANAGER_IRIKSIT_PASSWORD'], + 'manager.login.turnstile.site_key' => ['label' => 'Turnstile: site key', 'type' => 'text', 'group' => 'Login', 'sensitive' => true, 'env' => 'MANAGER_TURNSTILE_SITE_KEY'], + 'manager.login.turnstile.secret' => ['label' => 'Turnstile: secret key', 'type' => 'secret', 'group' => 'Login', 'env' => 'MANAGER_TURNSTILE_SECRET'], + ]; + } + + /** @return array> */ + private function fromModules(): array + { + $found = []; + + foreach ($this->modules->active() as $module) { + if (method_exists($module, 'settings')) { + foreach ((array) $module->settings() as $key => $definition) { + $found[$key] = $definition; + } + } + } + + return $found; + } + + /** @return array|null null when the definition is no good: it is left out, never half used */ + private function normalise(string $key, array $definition): ?array + { + $type = $definition['type'] ?? 'text'; + + if (preg_match('/^[a-z][a-z0-9_]*(\.[a-zA-Z0-9_-]+)+$/', $key) !== 1 || ! in_array($type, self::TYPES, true) || ! is_string($definition['label'] ?? null)) { + return null; + } + + $env = $definition['env'] ?? null; + + return [ + 'key' => $key, + 'config' => $key, + 'label' => $definition['label'], + 'type' => $type, + 'group' => is_string($definition['group'] ?? null) ? $definition['group'] : 'Site', + 'help' => is_string($definition['help'] ?? null) ? $definition['help'] : null, + 'options' => $type === 'select' ? (array) ($definition['options'] ?? []) : [], + 'env' => is_string($env) && preg_match('/^[A-Z][A-Z0-9_]*$/', $env) === 1 ? $env : null, + 'permission' => is_string($definition['permission'] ?? null) ? $definition['permission'] : null, + // What can send a password or a file somewhere else (an address, an account, a disk) needs the right for secrets too, and the password of whoever saves it. + 'sensitive' => $type === 'secret' || (bool) ($definition['sensitive'] ?? false), + ]; + } +} diff --git a/src/Support/Settings/EnvFile.php b/src/Support/Settings/EnvFile.php new file mode 100644 index 0000000..3717f3a --- /dev/null +++ b/src/Support/Settings/EnvFile.php @@ -0,0 +1,101 @@ +path ?? app()->environmentFilePath(); + } + + public function writable(): bool + { + return is_file($this->path()) && is_writable($this->path()) && is_writable(dirname($this->path())); + } + + /** + * @param array $pairs variable => value (null removes nothing: the line is left alone) + */ + public function set(array $pairs): bool + { + $pairs = array_filter($pairs, fn ($value) => $value !== null); + + if ($pairs === [] || ! $this->writable()) { + return false; + } + + foreach ($pairs as $name => $value) { + if (preg_match('/^[A-Z][A-Z0-9_]*$/', (string) $name) !== 1 || preg_match('/[\r\n\0]/', (string) $this->text($value)) === 1) { + return false; + } + } + + $lock = fopen($this->path().'.manager-lock', 'c'); + + if ($lock === false || ! flock($lock, LOCK_EX)) { + return false; + } + + try { + $old = (string) file_get_contents($this->path()); + $lines = preg_split('/\R/', $old) ?: []; + $left = $pairs; + + foreach ($lines as $i => $line) { + if (preg_match('/^\s*([A-Z][A-Z0-9_]*)\s*=/', $line, $found) === 1 && array_key_exists($found[1], $left)) { + $lines[$i] = $found[1].'='.$this->quote($left[$found[1]]); + unset($left[$found[1]]); + } + } + + foreach ($left as $name => $value) { + $lines[] = $name.'='.$this->quote($value); + } + + $new = rtrim(implode("\n", $lines), "\n")."\n"; + $temporary = $this->path().'.'.bin2hex(random_bytes(4)).'.tmp'; + + if (@copy($this->path(), $this->path().'.manager-backup') === false || @file_put_contents($temporary, $new) === false) { + return false; + } + + @chmod($temporary, fileperms($this->path()) & 0777); + + if (! @rename($temporary, $this->path())) { + @unlink($temporary); + + return false; + } + + return true; + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + } + + private function text(mixed $value): string + { + return is_bool($value) ? ($value ? 'true' : 'false') : (string) $value; + } + + private function quote(mixed $value): string + { + $text = $this->text($value); + + if (preg_match('/^[A-Za-z0-9_.:\/@+,-]*$/', $text) === 1) { + return $text; + } + + return '"'.str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $text).'"'; + } +} diff --git a/src/Support/Settings/Store.php b/src/Support/Settings/Store.php new file mode 100644 index 0000000..f9dde51 --- /dev/null +++ b/src/Support/Settings/Store.php @@ -0,0 +1,114 @@ +bootstrapPath('cache/manager-settings.php'); + } + + /** Lays the saved settings over the config. Called while the provider registers; it must never fail the app. */ + public static function overlay(): void + { + try { + $values = is_file(self::file()) ? (array) (include self::file()) : self::fromTable(); + + foreach ($values as $key => $value) { + if (is_array($value) && array_key_exists('__enc', $value)) { + $value = json_decode(Crypt::decryptString((string) $value['__enc']), true); + } + + config([$key => $value]); + } + } catch (Throwable) { + // A missing table (before the first migrate), a changed APP_KEY, a broken file: the config keeps what it had. + } + } + + /** @return array */ + private static function fromTable(): array + { + $values = []; + + foreach (DB::table(Names::table('settings'))->get() as $row) { + $values[$row->key] = $row->is_secret ? ['__enc' => $row->value] : json_decode((string) $row->value, true); + } + + return $values; + } + + /** + * Saves values (null: back to what the config says) and rewrites the compiled file. Returns whether that file could be written. + * + * @param array $values by config path, already checked against the definitions + */ + public function put(array $values, mixed $userId = null): bool + { + $table = Names::table('settings'); + + DB::transaction(function () use ($values, $table, $userId) { + foreach ($values as $key => $value) { + $definition = $this->definitions->find($key); + + if ($value === null || $definition === null) { + DB::table($table)->where('key', $key)->delete(); + + continue; + } + + $secret = $definition['type'] === 'secret'; + $stored = $secret ? Crypt::encryptString(json_encode($value)) : json_encode($value); + + DB::table($table)->updateOrInsert(['key' => $key], ['value' => $stored, 'is_secret' => $secret, 'updated_by' => $userId, 'updated_at' => now(), 'created_at' => now()]); + } + }); + + return $this->compile(); + } + + /** Writes the compiled file from the table: to a temporary file first, then moved over the old one in one step. */ + public function compile(): bool + { + $known = $this->definitions->all(); + $values = array_filter(self::fromTable(), fn ($value, $key) => isset($known[$key]), ARRAY_FILTER_USE_BOTH); + $file = self::file(); + $temporary = $file.'.'.bin2hex(random_bytes(4)).'.tmp'; + + try { + if (@file_put_contents($temporary, 'where('key', $key)->exists(); + } +} diff --git a/src/Support/Settings/Writer.php b/src/Support/Settings/Writer.php new file mode 100644 index 0000000..35b6ff4 --- /dev/null +++ b/src/Support/Settings/Writer.php @@ -0,0 +1,77 @@ + $changes config path => value; null puts the setting back to what the config says + * @return array{file_written: bool, env_written: bool} + */ + public function apply(array $changes, mixed $userId = null): array + { + if ($changes === []) { + return ['file_written' => true, 'env_written' => false]; + } + + $written = $this->store->put($changes, $userId); + + foreach ($changes as $key => $value) { + config([$key => $value ?? config($key)]); + } + + return ['file_written' => $written, 'env_written' => $this->writeEnv($changes)]; + } + + /** Writes the compiled file again and empties what caches the old values. */ + public function refresh(): bool + { + $written = $this->store->compile(); + function_exists('opcache_reset') && @opcache_reset(); + $this->recache(); + + return $written; + } + + /** @param array $changes */ + private function writeEnv(array $changes): bool + { + if (! config('manager.settings.write_env')) { + return false; + } + + $pairs = []; + + foreach ($changes as $key => $value) { + $env = $this->definitions->find($key)['env'] ?? null; + + if ($env !== null && $value !== null) { + $pairs[$env] = $value; + } + } + + $done = $this->env->set($pairs); + $done && $this->recache(); + + return $done; + } + + private function recache(): void + { + if (! app()->configurationIsCached()) { + return; + } + + try { + Artisan::call('config:cache'); + } catch (Throwable) { + // The overlay still applies on top of a config cache that is a bit old. + } + } +} diff --git a/src/Support/Sharing/PostSharing.php b/src/Support/Sharing/PostSharing.php new file mode 100644 index 0000000..4042cef --- /dev/null +++ b/src/Support/Sharing/PostSharing.php @@ -0,0 +1,127 @@ +isPublished()) { + throw new SharingException(__('Only a post that is live can be shared.')); + } + + if (! $this->sharers->isConnected($platform)) { + throw new SharingException(__(':platform is not connected. Connect it under Sharing.', ['platform' => $this->sharers->for($platform)->label()])); + } + + PostShare::query()->where('post_id', $post->id)->where('platform', $platform)->whereIn('status', [PostShare::PENDING, PostShare::FAILED])->delete(); + + return $this->share(PostShare::query()->create(['post_id' => $post->id, 'platform' => $platform, 'status' => PostShare::PENDING])); + } + + /** + * How sharing stands for a post, per platform, for the manager. + * + * @return list + */ + public function overview(Post $post): array + { + $shares = PostShare::query()->where('post_id', $post->id)->orderByDesc('id')->get(); + $overview = []; + + foreach ($this->sharers->names() as $name) { + $sharer = $this->sharers->for($name); + $last = $shares->first(fn (PostShare $share) => $share->platform === $name && $share->status !== PostShare::PENDING); + + $overview[] = [ + 'platform' => $name, + 'label' => $sharer->label(), + 'connected' => $sharer->connection() !== null, + 'preview' => ShareText::for($post, $sharer->maxLength()), + 'last' => $last instanceof PostShare ? [ + 'status' => $last->status, + 'shared_at' => $last->shared_at?->toIso8601String(), + 'url' => $last->external_url, + 'error' => $last->error, + 'dry_run' => (bool) $last->dry_run, + ] : null, + ]; + } + + return $overview; + } + + private function share(PostShare $share): PostShare + { + // Claim the row: whoever changes it from pending to sharing is the one that posts. + $claimed = PostShare::query()->whereKey($share->id)->where('status', PostShare::PENDING)->update(['status' => PostShare::SHARING]); + + if ($claimed !== 1) { + return $share->refresh(); + } + + $post = $share->post; + + try { + if (! $post instanceof Post || ! $this->sharers->isConnected($share->platform)) { + throw new SharingException(__('This platform is not connected. Connect it under Sharing.')); + } + + $sharer = $this->sharers->for($share->platform); + $text = ShareText::for($post, $sharer->maxLength()); + $url = ShareText::url($post, $share->platform); + + if ($url === null) { + throw new SharingException(__('The site did not say where its posts live (manager.sharing.post_url).')); + } + + $share->update(['text' => $text]); + + if (! self::isLive()) { + $share->update(['status' => PostShare::SHARED, 'dry_run' => true, 'shared_at' => now(), 'error' => null]); + + return $share; + } + + $posted = $sharer->publish(new ShareContent($text, $url, (string) $post->title, ShareText::description($post))); + + $share->update([ + 'status' => PostShare::SHARED, + 'external_id' => mb_substr($posted->id, 0, 255), + 'external_url' => $posted->url, + 'shared_at' => now(), + 'error' => null, + ]); + } catch (SharingException $e) { + $share->update(['status' => PostShare::FAILED, 'error' => mb_substr($e->getMessage(), 0, 500)]); + } catch (Throwable $e) { + report($e); + $share->update(['status' => PostShare::FAILED, 'error' => __('Something went wrong on this site while sharing. It is in the log.')]); + } + + return $share; + } +} diff --git a/src/Support/Sharing/ShareContent.php b/src/Support/Sharing/ShareContent.php new file mode 100644 index 0000000..97338df --- /dev/null +++ b/src/Support/Sharing/ShareContent.php @@ -0,0 +1,18 @@ +` + */ + public function __construct( + public readonly string $text, + public readonly string $url, + public readonly string $title, + public readonly string $description, + ) {} +} diff --git a/src/Support/Sharing/ShareText.php b/src/Support/Sharing/ShareText.php new file mode 100644 index 0000000..9504597 --- /dev/null +++ b/src/Support/Sharing/ShareText.php @@ -0,0 +1,41 @@ +slug), $pattern); + + return $url.(str_contains($url, '?') ? '&' : '?').'via='.rawurlencode($platform); + } + + public static function description(Post $post): string + { + $excerpt = trim((string) $post->excerpt); + + return $excerpt !== '' ? $excerpt : Str::limit(Markdown::toPlainText((string) $post->body), 160); + } + + /** The words as they are posted, cut to what the platform takes. */ + public static function for(Post $post, int $limit): string + { + return Str::limit(self::description($post), max(1, $limit)); + } +} diff --git a/src/Support/Sharing/SharedPost.php b/src/Support/Sharing/SharedPost.php new file mode 100644 index 0000000..32c2e99 --- /dev/null +++ b/src/Support/Sharing/SharedPost.php @@ -0,0 +1,9 @@ + class of a `Sharer`). */ +final class Sharers +{ + /** @return list the names of the platforms, as the routes and the database know them */ + public function names(): array + { + return array_values(array_filter(array_keys((array) config('manager.sharing.platforms', [])), fn ($name) => is_string($name) && preg_match('/^[a-z][a-z0-9_]{0,19}$/', $name) === 1)); + } + + public function has(string $name): bool + { + return in_array($name, $this->names(), true); + } + + public function for(string $name): Sharer + { + $class = config("manager.sharing.platforms.{$name}"); + + abort_unless($this->has($name) && is_string($class) && is_subclass_of($class, Sharer::class), 404); + + return app($class); + } + + /** The owner has connected this platform. */ + public function isConnected(string $name): bool + { + return $this->has($name) && $this->for($name)->connection() !== null; + } +} diff --git a/src/Support/Sharing/SharingException.php b/src/Support/Sharing/SharingException.php new file mode 100644 index 0000000..8565424 --- /dev/null +++ b/src/Support/Sharing/SharingException.php @@ -0,0 +1,8 @@ +, css: string, scripts: string, styles: string} */ + public function data(Request $request): array + { + $user = $request->user(); + $key = $this->themes->keyFor($user); + $theme = $this->themes->all()[$key]; + $dist = __DIR__.'/../../resources/dist'; + + $allowed = $user === null ? [] : array_values(array_filter( + [...$this->modules->permissionValues(), ManagerServiceProvider::MANAGE_GROUPS], + fn (string $permission) => Gate::forUser($user)->allows($permission), + )); + + $navigation = $this->menu->for($user, $allowed); + $base = '/'.trim((string) config('manager.path'), '/'); + $primary = $user !== null && method_exists($user, 'managerPrimaryGroup') ? $user->managerPrimaryGroup() : null; + // The start screen of the primary group, when this account has it in its menu. + $start = $primary?->start !== null && in_array($base.$primary->start, array_column($navigation, 'href'), true) ? $base.$primary->start : null; + + $extensions = array_values(array_filter( + (array) config('manager.extensions', []), + fn ($url) => is_string($url) && preg_match('#^(/(?!/)|https://)[^\s<>"\'\\\\]*$#', $url) === 1, + )); + + return [ + 'extensions' => $extensions, + 'css' => $this->themes->css($theme), + 'title' => $theme['name'] ?? config('manager.name') ?? config('app.name', 'Manager'), + 'version' => is_file($dist.'/manager.js') ? substr(md5_file($dist.'/manager.js').md5_file($dist.'/manager.css'), 0, 10) : 'dev', + 'boot' => [ + 'base' => '/'.trim((string) config('manager.path'), '/'), + 'name' => $theme['name'] ?? config('manager.name') ?? config('app.name', 'Manager'), + 'logo' => $theme['logo'], + 'locale' => app()->getLocale(), + 'user' => $user === null ? null : [ + 'name' => (string) ($user->name ?? ''), + 'email' => (string) ($user->email ?? ''), + 'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(), + 'group' => $primary?->name, + ], + 'start' => $start, + 'permissions' => $allowed, + 'navigation' => $navigation, + '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() : [], + ], + ]; + } +} diff --git a/src/Support/Tables.php b/src/Support/Tables.php new file mode 100644 index 0000000..ce60706 --- /dev/null +++ b/src/Support/Tables.php @@ -0,0 +1,83 @@ +> The columns the package reads and writes, per table (by the name the package uses). */ + public const COLUMNS = [ + 'audit_logs' => ['id', 'event', 'action', 'summary', 'subject_type', 'subject_id', 'subject_label', 'details', 'user_id', 'user_name', 'email', 'ip', 'user_agent', 'created_at'], + 'audit_settings' => ['id', 'auto_ban', 'max_failures', 'window_minutes', 'ban_minutes', 'keep_days', 'created_at', 'updated_at'], + 'bot_hits' => ['id', 'day', 'bot', 'kind', 'path', 'hits'], + 'group_user' => ['group_id', 'user_id', 'is_primary'], + 'groups' => ['id', 'name', 'description', 'permissions', 'created_at', 'updated_at', 'start'], + 'ip_bans' => ['id', 'ip', 'reason', 'automatic', 'whole_site', 'user_id', 'user_name', 'hits', 'last_hit_at', 'expires_at', 'created_at'], + 'ip_notes' => ['id', 'ip', 'group_name', 'note', 'user_id', 'user_name', 'created_at', 'updated_at'], + 'lead_blocks' => ['id', 'type', 'value', 'reason', 'expires_at', 'user_id', 'user_name', 'created_at', 'updated_at'], + 'lead_taps' => ['id', 'day', 'kind', 'path', 'taps'], + 'leads' => ['id', 'kind', 'folder', 'reasons', 'name', 'phone', 'email', 'prefers', 'about', 'message', 'message_hash', 'answers', 'location', 'subject', 'subject_id', 'page', 'channel', 'source', 'ip', 'opened_at', 'handled_at', 'outcome', 'notes', 'notified_at', 'notify_failed', 'created_at', 'updated_at'], + 'media' => ['id', 'disk', 'location', 'name', 'filename', 'mime_type', 'size', 'checksum', 'width', 'height', 'alt', 'focus_x', 'focus_y', 'uploaded_by', 'created_at', 'updated_at'], + 'page_views' => ['id', 'token', 'visit_id', 'path', 'post_id', 'viewed_at', 'day', 'hour', 'seconds'], + 'pages' => ['id', 'slug', 'title', 'body', 'is_published', 'created_at', 'updated_at', 'meta_description', 'content'], + 'post_shares' => ['id', 'post_id', 'platform', 'status', 'text', 'external_id', 'external_url', 'error', 'dry_run', 'shared_at', 'created_at', 'updated_at'], + 'social_connections' => ['name', 'access_token', 'expires_at', 'refresh_token', 'refresh_token_expires_at', 'account_id', 'account_name', 'details', 'created_at', 'updated_at'], + 'post_labels' => ['id', 'type', 'name', 'created_at', 'updated_at'], + 'posts' => ['id', 'title', 'slug', 'excerpt', 'body', 'cover_image', 'category', 'tags', 'is_featured', 'published_at', 'created_at', 'updated_at'], + 'records' => ['id', 'resource', 'data', 'created_at', 'updated_at'], + 'reviews' => ['id', 'author', 'place', 'rating', 'body', 'is_visible', 'created_at', 'updated_at'], + 'revisions' => ['id', 'type', 'subject_id', 'user_id', 'user_name', 'data', 'changed', 'created_at'], + 'settings' => ['id', 'key', 'value', 'is_secret', 'updated_by', 'created_at', 'updated_at'], + 'storage_files' => ['id', 'path', 'remote_id'], + 'user_settings' => ['id', 'user_id', 'theme', 'created_at', 'updated_at', 'view', 'locale', 'tutorial'], + 'work_costs' => ['id', 'fingerprint', 'date', 'name', 'version', 'model', 'usd', 'eur', 'usd_per_eur', 'priced_at', 'created_at', 'updated_at'], + 'visitor_salts' => ['day', 'salt'], + 'visits' => ['id', 'visitor_hash', 'started_at', 'last_seen_at', 'day', 'hour', 'weekday', 'entry_path', 'exit_path', 'channel', 'source', 'referrer_host', 'country', 'device', 'browser', 'os', 'page_views', 'seconds'], + ]; + + public static function create(string $table, Closure $callback): bool + { + if (Schema::hasTable($table)) { + return false; + } + + Schema::create($table, $callback); + + return true; + } + + /** Adds a column only when it is not there yet. */ + public static function addColumn(string $table, string $column, Closure $callback): void + { + if (Schema::hasTable($table) && ! Schema::hasColumn($table, $column)) { + Schema::table($table, fn (Blueprint $blueprint) => $callback($blueprint)); + } + } + + /** + * The columns a table lacks for the package, by the name the package uses for it (`groups`, not `site_groups`). + * A table the package does not know, or that does not exist, lacks nothing. + * + * @return list + */ + public static function missingColumns(string $name): array + { + $table = Names::table($name); + + if (! isset(self::COLUMNS[$name]) || ! Schema::hasTable($table)) { + return []; + } + + return array_values(array_filter(self::COLUMNS[$name], fn (string $column) => ! Schema::hasColumn($table, $column))); + } +} diff --git a/src/Support/Themes.php b/src/Support/Themes.php new file mode 100644 index 0000000..fd665b1 --- /dev/null +++ b/src/Support/Themes.php @@ -0,0 +1,128 @@ + ['label' => 'Dark', 'scheme' => 'dark', 'colors' => [ + 'ink' => '#0a0a12', 'panel' => '#12121d', 'panel2' => '#191927', 'line' => '#26263a', + 'muted' => '#a3a3b8', 'text' => '#f4f4f8', 'brand' => '#f43676', 'brand_alt' => '#ff6b9d', + ]], + 'light' => ['label' => 'Light', 'scheme' => 'light', 'colors' => [ + 'ink' => '#f4f6f8', 'panel' => '#ffffff', 'panel2' => '#eceff3', 'line' => '#d9dee5', + 'muted' => '#5d6a73', 'text' => '#192c27', 'brand' => '#009ba3', 'brand_alt' => '#007c83', + ]], + ]; + + /** @return array> */ + public function all(): array + { + $themes = self::BUILT_IN; + + foreach ((array) config('manager.themes', []) as $key => $theme) { + $themes[(string) $key] = $theme; + } + + $path = config('manager.themes_path') ?: (function_exists('resource_path') ? resource_path('manager-themes') : null); + + foreach ($path && is_dir($path) ? glob($path.'/*.json') : [] as $file) { + $theme = json_decode((string) file_get_contents($file), true); + + if (is_array($theme)) { + $themes[basename($file, '.json')] = $theme; + } + } + + $clean = []; + + foreach ($themes as $key => $theme) { + if (preg_match('/^[a-z0-9][a-z0-9-]{0,40}$/', (string) $key) && ($safe = $this->sanitize($key, $theme))) { + $clean[$key] = $safe; + } + } + + return $clean; + } + + /** The key of the theme this account sees: its own choice when allowed, else the site's. */ + public function keyFor(?object $user): string + { + $all = $this->all(); + $default = array_key_exists(config('manager.theme'), $all) ? config('manager.theme') : 'dark'; + + if ($user !== null && config('manager.user_themes') && $user->getKey() !== null) { + $chosen = UserSetting::query()->where('user_id', $user->getKey())->value('theme'); + + if ($chosen !== null && isset($all[$chosen])) { + return $chosen; + } + } + + return $default; + } + + /** @return array|null */ + public function sanitize(string $key, mixed $theme): ?array + { + if (! is_array($theme)) { + return null; + } + + $base = self::BUILT_IN[($theme['scheme'] ?? 'dark') === 'light' ? 'light' : 'dark']; + $colors = $base['colors']; + + foreach (self::COLORS as $name) { + $value = $theme['colors'][$name] ?? null; + + if (is_string($value) && preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $value)) { + $colors[$name] = $value; + } + } + + $radius = $theme['radius'] ?? '0.5rem'; + $font = $theme['font'] ?? null; + $display = $theme['font_display'] ?? null; + $logo = $theme['logo'] ?? null; + $name = $theme['name'] ?? null; + $label = $theme['label'] ?? ucfirst(str_replace('-', ' ', $key)); + + return [ + 'label' => is_string($label) ? mb_substr(strip_tags($label), 0, 60) : $key, + 'scheme' => $base['scheme'], + 'colors' => $colors, + 'radius' => is_string($radius) && preg_match('/^\d{1,2}(\.\d{1,2})?(px|rem)$/', $radius) ? $radius : '0.5rem', + 'font' => is_string($font) && preg_match('/^[\w ,\'"-]{1,120}$/', $font) ? $font : null, + 'font_display' => is_string($display) && preg_match('/^[\w ,\'"-]{1,120}$/', $display) ? $display : null, + 'logo' => is_string($logo) && preg_match('#^(/|https://)[\w\-./%~]{1,300}$#', $logo) ? $logo : null, + 'name' => is_string($name) ? mb_substr(strip_tags($name), 0, 80) : null, + ]; + } + + /** The CSS variables of one theme, ready for a style block (values are already checked). */ + public function css(array $theme): string + { + $vars = []; + + foreach ($theme['colors'] as $name => $value) { + $vars[] = '--m-'.str_replace('_', '-', $name).':'.$value; + } + + $vars[] = '--m-radius:'.$theme['radius']; + $theme['font'] && $vars[] = '--m-font:'.$theme['font']; + $theme['font_display'] && $vars[] = '--m-font-display:'.$theme['font_display']; + $vars[] = 'color-scheme:'.$theme['scheme']; + + return ':root{'.implode(';', $vars).'}'; + } +} diff --git a/src/Support/Tiles.php b/src/Support/Tiles.php new file mode 100644 index 0000000..47bf16e --- /dev/null +++ b/src/Support/Tiles.php @@ -0,0 +1,59 @@ + */ + public function for(?object $user): array + { + if ($user === null) { + return []; + } + + $can = fn (string $permission): bool => Gate::forUser($user)->allows($permission); + $facts = []; + + if ($this->modules->enabled('leads') && $can('leads.view')) { + $waiting = Lead::query()->where('folder', Lead::INBOX)->whereNull('handled_at'); + $new = (clone $waiting)->whereNull('opened_at')->count(); + $count = $waiting->count(); + + $facts[Names::route('leads.index')] = [ + 'summary' => $count === 0 + ? __('Nothing is waiting for an answer.') + : trans_choice('{1} :count is waiting for an answer|[2,*] :count are waiting for an answer', $count, ['count' => $count]).($new > 0 ? ', '.__(':new of them new', ['new' => $new]) : '').'.', + 'badge' => $new, + ]; + } + + if ($this->modules->enabled('posts') && $can('posts.view')) { + $drafts = Post::query()->whereNull('published_at')->count(); + + if ($drafts > 0) { + $facts[Names::route('posts.index')] = ['summary' => trans_choice('{1} :count post is waiting for you.|[2,*] :count posts are waiting for you.', $drafts, ['count' => $drafts])]; + } + } + + if ($this->modules->enabled('numbers') && $can('numbers.view')) { + $visitors = $this->numbers->visitorsThisWeek(); + + if ($visitors > 0) { + $facts[Names::route('numbers.index')] = ['summary' => trans_choice('{1} :count visitor in the last 7 days.|[2,*] :count visitors in the last 7 days.', $visitors, ['count' => $visitors])]; + } + } + + return $facts; + } +} diff --git a/src/Support/UserAgent.php b/src/Support/UserAgent.php new file mode 100644 index 0000000..eb7751b --- /dev/null +++ b/src/Support/UserAgent.php @@ -0,0 +1,215 @@ +line) === '' || preg_match(self::BOTS, $this->line) === 1; + } + + /** + * The programs the statistics know by name, as pattern => [name, kind]. The + * first one that fits wins, so a longer name stands before the one it holds + * ("Applebot-Extended" before "Applebot"). + * + * Kinds: search (search engine), ai (collects for or answers through an AI), + * seo (marketing tools), social (the preview of a shared link), monitor, feed, + * archive, scanner (looks for weak spots), script (a program or library). + */ + private const KNOWN_BOTS = [ + '/GPTBot/i' => ['GPTBot', 'ai'], + '/ChatGPT-User/i' => ['ChatGPT', 'ai'], + '/OAI-SearchBot/i' => ['OpenAI search', 'ai'], + '/Claude-SearchBot/i' => ['Claude search', 'ai'], + '/Claude-User/i' => ['Claude', 'ai'], + '/ClaudeBot|anthropic-ai|claude-web/i' => ['ClaudeBot', 'ai'], + '/Perplexity-User/i' => ['Perplexity', 'ai'], + '/PerplexityBot/i' => ['PerplexityBot', 'ai'], + '/Google-Extended|GoogleOther|Google-CloudVertexBot/i' => ['Google (AI and other)', 'ai'], + '/Applebot-Extended/i' => ['Applebot-Extended', 'ai'], + '/meta-externalagent|meta-externalfetcher/i' => ['Meta AI', 'ai'], + '/Bytespider/i' => ['Bytespider', 'ai'], + '/Amazonbot/i' => ['Amazonbot', 'ai'], + '/CCBot/i' => ['Common Crawl', 'ai'], + '/cohere-ai|cohere-training/i' => ['Cohere', 'ai'], + '/MistralAI/i' => ['Mistral', 'ai'], + '/DuckAssistBot/i' => ['DuckAssist', 'ai'], + '/YouBot/i' => ['YouBot', 'ai'], + '/Diffbot/i' => ['Diffbot', 'ai'], + '/ImagesiftBot/i' => ['ImagesiftBot', 'ai'], + '/Timpibot/i' => ['Timpibot', 'ai'], + + '/Googlebot|Google-InspectionTool|Storebot-Google|AdsBot-Google|Mediapartners-Google|APIs-Google/i' => ['Googlebot', 'search'], + '/bingbot|BingPreview|adidxbot|msnbot/i' => ['Bingbot', 'search'], + '/DuckDuckBot|DuckDuckGo/i' => ['DuckDuckBot', 'search'], + '/YandexBot|YandexImages|Yandex/i' => ['YandexBot', 'search'], + '/Baiduspider/i' => ['Baiduspider', 'search'], + '/Applebot/i' => ['Applebot', 'search'], + '/Slurp/i' => ['Yahoo', 'search'], + '/Qwantbot|Qwantify/i' => ['Qwant', 'search'], + '/SeznamBot/i' => ['SeznamBot', 'search'], + '/PetalBot/i' => ['PetalBot', 'search'], + '/Sogou/i' => ['Sogou', 'search'], + '/MojeekBot/i' => ['Mojeek', 'search'], + '/Bravebot/i' => ['Brave', 'search'], + '/Kagibot/i' => ['Kagi', 'search'], + + '/AhrefsBot|AhrefsSiteAudit/i' => ['AhrefsBot', 'seo'], + '/SemrushBot|SiteAuditBot|SplitSignalBot/i' => ['SemrushBot', 'seo'], + '/MJ12bot/i' => ['Majestic', 'seo'], + '/DotBot|rogerbot/i' => ['Moz', 'seo'], + '/DataForSeoBot/i' => ['DataForSEO', 'seo'], + '/BLEXBot/i' => ['BLEXBot', 'seo'], + '/SerpstatBot/i' => ['Serpstat', 'seo'], + '/Barkrowler/i' => ['Barkrowler', 'seo'], + '/Screaming Frog/i' => ['Screaming Frog', 'seo'], + '/SEOkicks|seobility|Sistrix|linkdexbot/i' => ['Other SEO tool', 'seo'], + + '/facebookexternalhit|Facebot|facebookcatalog/i' => ['Facebook', 'social'], + '/LinkedInBot/i' => ['LinkedIn', 'social'], + '/Twitterbot/i' => ['X', 'social'], + '/WhatsApp/i' => ['WhatsApp', 'social'], + '/TelegramBot/i' => ['Telegram', 'social'], + '/Slackbot|Slack-ImgProxy/i' => ['Slack', 'social'], + '/Discordbot/i' => ['Discord', 'social'], + '/Pinterestbot|Pinterest\\/0/i' => ['Pinterest', 'social'], + '/redditbot/i' => ['Reddit', 'social'], + '/Mastodon|Pleroma|Akkoma|Misskey/i' => ['Mastodon and the fediverse', 'social'], + '/Bluesky/i' => ['Bluesky', 'social'], + '/SkypeUriPreview|MicrosoftPreview/i' => ['Microsoft link preview', 'social'], + '/Embedly|Iframely/i' => ['Embed service', 'social'], + + '/UptimeRobot/i' => ['UptimeRobot', 'monitor'], + '/Uptime-Kuma/i' => ['Uptime Kuma', 'monitor'], + '/Pingdom/i' => ['Pingdom', 'monitor'], + '/StatusCake/i' => ['StatusCake', 'monitor'], + '/Better Uptime|BetterStack/i' => ['Better Stack', 'monitor'], + '/Site24x7/i' => ['Site24x7', 'monitor'], + '/Lighthouse|PageSpeed|GTmetrix/i' => ['Speed test', 'monitor'], + '/Cloudflare/i' => ['Cloudflare', 'monitor'], + '/Zabbix|Nagios|check_http|Datadog|NewRelic/i' => ['Other monitoring', 'monitor'], + + '/Feedly|Feedbin|Inoreader|NewsBlur|Miniflux|FreshRSS|Tiny Tiny RSS|FeedFetcher/i' => ['Feed reader', 'feed'], + '/archive\.org_bot|ia_archiver|Wayback/i' => ['Internet Archive', 'archive'], + + '/CensysInspect/i' => ['Censys', 'scanner'], + '/Shodan/i' => ['Shodan', 'scanner'], + '/Expanse|Palo Alto/i' => ['Palo Alto Expanse', 'scanner'], + '/InternetMeasurement/i' => ['InternetMeasurement', 'scanner'], + '/l9explore|l9tcpid|LeakIX/i' => ['LeakIX', 'scanner'], + '/zgrab|masscan|Nmap|Nuclei|Nikto|sqlmap|WPScan|dirbuster|gobuster/i' => ['Scanning tool', 'scanner'], + + '/HeadlessChrome|Puppeteer|Playwright|Selenium|PhantomJS/i' => ['Headless browser', 'script'], + '/curl/i' => ['curl', 'script'], + '/Wget/i' => ['Wget', 'script'], + '/python|aiohttp|httpx|scrapy/i' => ['Python', 'script'], + '/Go-http-client/i' => ['Go', 'script'], + '/okhttp|Java\/|Apache-HttpClient/i' => ['Java', 'script'], + '/axios|node-fetch|undici|node/i' => ['Node.js', 'script'], + '/Guzzle|PHP/i' => ['PHP', 'script'], + '/Ruby|Faraday/i' => ['Ruby', 'script'], + '/libwww-perl|Perl/i' => ['Perl', 'script'], + '/Postman|Insomnia/i' => ['API client', 'script'], + ]; + + /** For a program that is not in the list: the word in its line that names it. */ + private const BOT_WORD = '/[A-Za-z0-9][A-Za-z0-9._-]*(?:bot|crawler|crawl|spider|scan|fetch|monitor|preview|archive|validator)[A-Za-z0-9._-]*/i'; + + /** + * Which program this is, or null for a person. A program that is not known + * by name is called by the one word of its line that names it ("FooBot"), + * never by the line; without such a word it is `null` as a name, for the + * caller to file under "other". + * + * @return array{name: string|null, kind: string}|null + */ + public function bot(): ?array + { + if (! $this->isBot()) { + return null; + } + + foreach (self::KNOWN_BOTS as $pattern => [$name, $kind]) { + if (preg_match($pattern, $this->line) === 1) { + return ['name' => $name, 'kind' => $kind]; + } + } + + $word = preg_match(self::BOT_WORD, $this->line, $match) === 1 ? substr($match[0], 0, 40) : null; + + return ['name' => $word, 'kind' => 'other']; + } + + public function device(): string + { + if (preg_match('/iPad|Tablet|PlayBook|Silk/i', $this->line) === 1 + || (str_contains($this->line, 'Android') && ! str_contains($this->line, 'Mobile'))) { + return 'tablet'; + } + + return preg_match('/Mobi|iPhone|iPod|Android/i', $this->line) === 1 ? 'mobile' : 'desktop'; + } + + public function browser(): string + { + // Order matters: nearly every browser also says "Chrome" and "Safari". + $browsers = [ + 'Edge' => '/Edg(e|A|iOS)?\//', + 'Opera' => '/OPR\/|Opera/', + 'Samsung Internet' => '/SamsungBrowser\//', + 'Vivaldi' => '/Vivaldi\//', + 'Firefox' => '/Firefox\/|FxiOS\//', + 'Chrome' => '/Chrome\/|CriOS\//', + 'Safari' => '/Safari\//', + ]; + + foreach ($browsers as $name => $pattern) { + if (preg_match($pattern, $this->line) === 1) { + return $name; + } + } + + return 'Other'; + } + + public function os(): string + { + $systems = [ + 'iOS' => '/iPhone|iPad|iPod/', + 'Android' => '/Android/', + 'Windows' => '/Windows/', + 'macOS' => '/Mac OS X|Macintosh/', + 'ChromeOS' => '/CrOS/', + 'Linux' => '/Linux|X11/', + ]; + + foreach ($systems as $name => $pattern) { + if (preg_match($pattern, $this->line) === 1) { + return $name; + } + } + + return 'Other'; + } +}