diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 03209a98..4db96db9 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -325,7 +325,8 @@ php artisan tinker The application includes GitHub Actions workflows in `.github/workflows/`: - `deploy-preview.yml` - PR previews, `deploy-nightly.yml` - nightly build of `main`, and `upload-altervista-reusable.yml` - deployments, called by other repositories -- `run-tests.yml` - Test execution with coverage +- `run-pest-tests.yml` - Pest tests (unit and feature), with coverage +- `run-e2e-tests.yml` - Playwright end-to-end tests (`tests/e2e`), on SQLite and MySQL - `check-translations.yml` - Translation validation - **PR previews** (`deploy-preview.yml`): the `PREVIEW_MODE` repository variable sets which PRs get a preview diff --git a/.github/workflows/run-e2e-tests.yml b/.github/workflows/run-e2e-tests.yml new file mode 100644 index 00000000..6322cb6a --- /dev/null +++ b/.github/workflows/run-e2e-tests.yml @@ -0,0 +1,194 @@ +name: E2E tests + +on: + # Every pull request (forks included), and what lands on main + push: + branches: + - main + pull_request: + workflow_dispatch: # Manually trigger a workflow run + +permissions: + contents: read + +env: + # Same major version installed in the Sail image (see docker-compose.yml) + node_version: "24.x" + php_extensions: >- + bcmath,calendar,ctype,curl,date,dom,exif,fileinfo,filter + ,gd,gettext,gmp,hash,iconv,imagick,intl,json,libxml,mbstring + ,mysqli,mysqlnd,openssl,pcre,PDO,pdo_mysql,pdo_sqlite + ,Phar,random,Reflection,session,SimpleXML,SPL,sqlite3,standard + ,tokenizer,xml,xmlreader,xmlwriter,xsl,zip,zlib + +jobs: + run-e2e-tests: + name: E2E (${{ matrix.database }}) + runs-on: ubuntu-latest + timeout-minutes: 45 + + # The application supports these databases: each one runs the whole suite, the setup wizard included (which + # configures the database of its run, see `tests/e2e/setup-wizard.spec.ts`). PostgreSQL is not supported yet. + strategy: + fail-fast: false + matrix: + database: [sqlite, mysql] + include: + - database: sqlite + mysql_image: "" + - database: mysql + # Same version as docker-compose.yml + mysql_image: mysql:8.0 + port: 3306 + username: root + + # A service with an empty image is not started: only the runs on MySQL have it + services: + mysql: + image: ${{ matrix.mysql_image }} + env: + MYSQL_ROOT_PASSWORD: password + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping --silent --host=127.0.0.1 -uroot -ppassword" + --health-interval=5s --health-timeout=5s --health-retries=30 + + env: + # Read by `tests/e2e/support/serve.sh` and the setup wizard test + E2E_DB_CONNECTION: ${{ matrix.database }} + E2E_DB_HOST: 127.0.0.1 + E2E_DB_PORT: ${{ matrix.port }} + E2E_DB_USERNAME: ${{ matrix.username }} + E2E_DB_PASSWORD: password + + steps: + - name: Checkout code + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Setup PHP and Composer + uses: shivammathur/setup-php@v2 + with: + # The version of the platform of composer.json + php-version: "8.2" + extensions: ${{ env.php_extensions }} + coverage: none + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + fail-fast: true + + - name: Print the OPcache settings of PHP + run: php -i | grep -E "^opcache\.(enable|enable_cli|jit|jit_buffer_size) " || echo "OPcache is not loaded" + + - name: Setup NodeJS + uses: actions/setup-node@v7 + with: + node-version: ${{ env.node_version }} + cache: npm + + - name: Cache Composer dependencies + uses: actions/cache@v6 + with: + path: vendor + key: composer-${{ hashFiles('**/composer.lock') }} + restore-keys: composer- + + - name: Install Composer dependencies + run: composer install --no-ansi --no-interaction --no-progress --no-scripts --optimize-autoloader + + # The assets must be built after the Composer dependencies are installed, since the Filament themes import CSS + # from `vendor` + - name: Install NodeJS dependencies + run: npm ci + + - name: Build front-end assets + run: npm run build + + - name: Get Playwright version + id: playwright + run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT" + + - name: Cache Playwright browsers + id: playwright-cache + uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }} + + - name: Install Playwright browsers + if: steps.playwright-cache.outputs.cache-hit != 'true' + run: npx playwright install --with-deps chromium + + - name: Install Playwright system dependencies + if: steps.playwright-cache.outputs.cache-hit == 'true' + run: npx playwright install-deps chromium + + - name: Run E2E tests + run: | + # Note when the app server stops answering, with its processes and the memory at that moment (printed by + # the "Print the state of the test servers" step) + ( + up="" + while true; do + if curl -s -o /dev/null --max-time 10 http://127.0.0.1:8010/up; then now=yes; else now=no; fi + if [[ "$now" != "$up" ]]; then + echo "$(date -u +%T) answering: ${now}" + ps -eo pid,ppid,etime,rss,args | grep -E "[p]hp .*-S " || echo "No PHP server is running" + free -m | head -2 + up="$now" + fi + sleep 5 + done + ) > "${RUNNER_TEMP}/server-watch.log" 2>&1 & + + npx playwright test + + # Printed at the end of the log (the earlier lines of a long log can be hard to reach): why the test servers may + # have stopped, e.g. a crash or the kernel killing them for lack of memory + - name: Print the state of the test servers + if: failure() + run: | + echo "::group::When the app server answered (checked every 5 seconds)" + cat "${RUNNER_TEMP}/server-watch.log" || true + echo "::endgroup::" + echo "::group::Errors of the test servers" + tail -n 200 storage/e2e/*/logs/server.log || true + echo "::endgroup::" + echo "::group::Last errors of the application" + grep -h "\.ERROR:" storage/e2e/*/logs/laravel.log | cut -c1-400 | tail -n 50 || true + echo "::endgroup::" + echo "::group::Processes killed by the kernel" + sudo dmesg 2>/dev/null | grep -iE "killed process|out of memory|segfault" | tail -n 20 || true + echo "::endgroup::" + echo "::group::Memory and PHP servers" + free -m + ps -eo pid,ppid,etime,rss,args | grep -E "[p]hp .*-S " || echo "No PHP server is running" + echo "::endgroup::" + + - name: Upload test report + if: failure() + uses: actions/upload-artifact@v7 + with: + name: playwright-report-${{ matrix.database }} + path: | + playwright-report/ + test-results/ + storage/e2e/*/logs/ + retention-days: 14 + + - name: Explain how to debug the failed tests + if: failure() + env: + DATABASE: ${{ matrix.database }} + run: | + { + echo "### Debugging the failed E2E tests (${DATABASE})" + echo + echo "Download the \`playwright-report-${DATABASE}\` artifact of this run, unzip it, then:" + echo + echo "- \`npx playwright show-report playwright-report\`: the report, with the screenshot, the video and the trace of each failed test;" + echo "- \`npx playwright show-trace test-results//trace.zip\` (or drop the file on https://trace.playwright.dev) to replay a test step by step, with the page, the network and the console;" + echo "- \`storage/e2e//logs/laravel.log\`: the errors of the application." + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-pest-tests.yml similarity index 98% rename from .github/workflows/run-tests.yml rename to .github/workflows/run-pest-tests.yml index 83cf4637..be9ab2ba 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-pest-tests.yml @@ -1,4 +1,4 @@ -name: Run tests +name: Pest tests on: # Every pull request (forks included), and what lands on main @@ -26,8 +26,8 @@ env: sail_image_max_age_days: 7 jobs: - run-tests: - name: Run tests (prefixed=${{ matrix.db-prefix != '' && 'yes' || 'no' }}) + run-pest-tests: + name: Pest (prefixed=${{ matrix.db-prefix != '' && 'yes' || 'no' }}) runs-on: ubuntu-latest # The PR previews share one database, prefixing their tables with `p_` (`DB_PREFIX`): the suite also runs with diff --git a/.gitignore b/.gitignore index 008bbfc4..e6331b0c 100755 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,10 @@ _ide_helper_models.php .secrets.* .vars .vars.* + +# End-to-end tests (see `playwright.config.ts`) +/storage/e2e +/tests/e2e/.auth +/test-results +/playwright-report +/blob-report diff --git a/CHANGELOG.md b/CHANGELOG.md index 395496e9..9e6aa34b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 confirmation (from the territories list and the campaign assignments); the bulk assignment skips such territories unless asked to include them, and the AI assistants ask the user before assigning it again ([#114](https://github.com/OpenCHelper/OpenCongregationHelper/pull/114)). +- **End-to-end tests**: browser tests of every feature of the app and of the main workflows (e.g. a zone, then a + territory in it, assigned and returned), run on every pull request on SQLite and MySQL; a failed test keeps a video + and a trace to replay it ([#116](https://github.com/OpenCHelper/OpenCongregationHelper/pull/116)). +- The busy timeout and the journal mode of SQLite can be set with `DB_BUSY_TIMEOUT` and `DB_JOURNAL_MODE` + ([#116](https://github.com/OpenCHelper/OpenCongregationHelper/pull/116)). ### Changed @@ -150,6 +155,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **AI assistants**: the deployments of the environments that keep their database (e.g. TEST) keep the keys signing the tokens of the assistants, which were replaced on every deployment, disconnecting every assistant ([#112](https://github.com/OpenCHelper/OpenCongregationHelper/pull/112)). +- The fake data (`FakeDataSeeder`, used by the PR previews) could fail to seed when an assignment picked a campaign that + had already ended ([#116](https://github.com/OpenCHelper/OpenCongregationHelper/pull/116)). ### Security diff --git a/CLAUDE.md b/CLAUDE.md index 92fd857f..2ddce6a9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,6 +15,20 @@ - Never put screenshots meant only for an issue or a PR in a temporary branch or anywhere else public (other branches, gists, image hosts) unless explicitly asked: send them to the user instead; +## E2E tests + +- The Playwright tests in `tests/e2e/` (one spec per feature area, run by `run-e2e-tests.yml`) must always follow the + UI: every change that adds, changes or removes something in the UI (a page, field, action, filter, label, navigation + item, permission) updates, adds or removes the E2E tests that cover it, in the same change; +- They document what a user does and check that it works end to end: beside the single features, cover the whole + workflows that chain them (e.g. creating a zone, then a territory in it, then assigning the territory and returning + it), so that the tests read as the steps a user follows; +- Prefer the helpers of `tests/e2e/support/` (`filament.ts`, `fixtures.ts`, `artisan.ts`, `mail.ts`) and give the + records unique names (`uniqueName()`), since the tests run in parallel on one database; tests that change the whole + app (settings, root user) go in `tests/e2e/global-state/`; +- A bug found by an E2E test that is not fixed in the same change stays visible as a `test.fixme` explaining it, never + as a removed or weakened test. + ## CI/CD - **PR previews** (`deploy-preview.yml`): the `PREVIEW_MODE` repository variable sets which PRs get a preview diff --git a/README.md b/README.md index 28b27b9f..7a79fbbc 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,28 @@ The preferred way of developing is by using **Docker Compose** to build the cont sail npm install && sail npm run dev ``` +### End-to-end tests + +The browser tests in [`tests/e2e`](./tests/e2e) use [Playwright](https://playwright.dev) on two instances of the +application, each with its own `.env.e2e-*` file, storage (`storage/e2e/`) and database, so they never touch the +development ones: `app`, installed and seeded with `E2eSeeder` (a user for each role, password `password`), and +`setup`, empty, for the setup wizard. They are served by +[`tests/e2e/support/serve.sh`](./tests/e2e/support/serve.sh) on the ports 8010 and 8011. + +1. Build the frontend assets and install Chromium (once): + ```shell + npm run build && npx playwright install chromium + ``` +2. Run the tests (`npm run test:e2e:ui` opens the interactive runner): + ```shell + npm run test:e2e + ``` + +They use SQLite by default: set `E2E_DB_CONNECTION` (`mysql`, `mariadb` or `pgsql`) and `E2E_DB_HOST`, `E2E_DB_PORT`, +`E2E_DB_USERNAME`, `E2E_DB_PASSWORD` to run them on another database (the databases `e2e_app` and `e2e_setup` are +created). Outside of CI, servers already running on the ports are reused: stop them to start from fresh data. The +`E2E tests` workflow (`run-e2e-tests.yml`) runs them on SQLite and MySQL. + ### Run workflows locally You can run the Github Action workflows locally using [`nektos/act`](https://github.com/nektos/act) (already included in the [DevContainer](./.devcontainer/devcontainer.json)). diff --git a/config/database.php b/config/database.php index 96a01cee..f434dac6 100644 --- a/config/database.php +++ b/config/database.php @@ -38,8 +38,9 @@ 'database' => env('DB_DATABASE', database_path('database.sqlite')), 'prefix' => env('DB_PREFIX', ''), 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), - 'busy_timeout' => null, - 'journal_mode' => null, + // E.g. `DB_BUSY_TIMEOUT=10000` and `DB_JOURNAL_MODE=wal` for concurrent writers (the end-to-end tests) + 'busy_timeout' => env('DB_BUSY_TIMEOUT'), + 'journal_mode' => env('DB_JOURNAL_MODE'), 'synchronous' => null, ], diff --git a/database/seeders/E2eSeeder.php b/database/seeders/E2eSeeder.php new file mode 100644 index 00000000..302d91fc --- /dev/null +++ b/database/seeders/E2eSeeder.php @@ -0,0 +1,181 @@ + + */ + public const USERS = [ + 'admin@e2e.test' => ['first_name' => 'Adam', 'last_name' => 'Admin', 'role' => 'super_admin'], + 'servant@e2e.test' => ['first_name' => 'Simon', 'last_name' => 'Servant', 'role' => 'territory_servant'], + 'overseer@e2e.test' => ['first_name' => 'Oscar', 'last_name' => 'Overseer', 'role' => 'service_overseer'], + 'group@e2e.test' => ['first_name' => 'Gino', 'last_name' => 'Group', 'role' => 'group_overseer'], + 'publisher@e2e.test' => ['first_name' => 'Paul', 'last_name' => 'Publisher', 'role' => 'publisher'], + 'norole@e2e.test' => ['first_name' => 'Nora', 'last_name' => 'Norole', 'role' => null], + ]; + + /** + * The other users of the congregation, without a login of their own. + */ + public const OTHER_USERS_COUNT = 8; + + /** + * Run the database seeds. + */ + public function run(): void + { + fake()->seed(20261127); + + // The roles first: `FakeRoleSeeder` gives a role to the users that have none + $this->call(FakeRoleSeeder::class); + + $users = $this->createUsers(); + + User::factory(self::OTHER_USERS_COUNT)->create() + ->each(fn (User $user) => $user->assignRole('publisher')); + + $this->call([ + FakeTagSeeder::class, + FakeCampaignSeeder::class, + FakeTerritorySeeder::class, + FakeTerritoryAssignmentSeeder::class, + FakePosterSeeder::class, + FakePublicationSubscriberSeeder::class, + FakePublicationRequestSeeder::class, + ]); + + $this->createDepartments($users); + $this->createTerritories($users); + } + + /** + * @return array + */ + private function createUsers(): array + { + $users = []; + + foreach (self::USERS as $email => $data) { + $user = User::factory()->create([ + 'first_name' => $data['first_name'], + 'last_name' => $data['last_name'], + 'email' => $email, + 'password' => self::PASSWORD, + 'email_verified_at' => now(), + 'can_login' => true, + // The tests read the pages, emails and notifications in English + 'locale' => 'en', + ]); + + if ($data['role'] !== null) { + $user->assignRole($data['role']); + } + + $users[$email] = $user; + } + + return $users; + } + + /** + * The territory servant is the overseer of the territories department, who is notified of the return requests. + * + * @param array $users + */ + private function createDepartments(array $users): void + { + Department::for(DepartmentKey::Territories)->members()->syncWithoutDetaching([ + $users['servant@e2e.test']->getKey() => ['role' => DepartmentRole::Overseer], + ]); + + Department::for(DepartmentKey::PublicWitnessing); + Department::for(DepartmentKey::Publications); + } + + /** + * A zone with a free territory, a commercial one, one assigned to the publisher and one assigned in a campaign that + * has ended since (overdue). + * + * @param array $users + */ + private function createTerritories(array $users): void + { + $publisher = $users['publisher@e2e.test']; + $servant = $users['servant@e2e.test']; + + $zone = TerritoryZone::factory()->create([ + 'name' => 'E2E Zone', + 'color' => '#00897b', + 'created_by' => $servant->getKey(), + ]); + + $territory = fn (string $name, array $attributes = []): Territory => Territory::factory()->withMap()->for($zone)->create([ + 'name' => $name, + 'description' => "{$name} description", + 'notes' => "{$name} notes", + 'created_by' => $servant->getKey(), + ...$attributes, + ]); + + $territory('E2E Free'); + $territory('E2E Commercial', ['is_commercial' => true]); + $assigned = $territory('E2E Assigned'); + $overdue = $territory('E2E Overdue'); + + $expiredCampaign = Campaign::factory()->create([ + 'name' => 'E2E Expired Campaign', + 'short_name' => 'E2E-EXP', + 'valid_from' => now()->subMonths(3)->startOfDay(), + 'valid_until' => now()->addMonth()->endOfDay(), + 'created_by' => $servant->getKey(), + ]); + + TerritoryAssignment::factory()->create([ + 'territory_id' => $assigned->getKey(), + 'assignee_id' => $publisher->getKey(), + 'campaign_id' => null, + 'started_at' => now()->subDays(10), + 'ended_at' => null, + 'notes' => null, + 'created_by' => $servant->getKey(), + ]); + + TerritoryAssignment::factory()->create([ + 'territory_id' => $overdue->getKey(), + 'assignee_id' => $publisher->getKey(), + 'campaign_id' => $expiredCampaign->getKey(), + 'started_at' => now()->subMonths(2), + 'ended_at' => null, + 'notes' => null, + 'created_by' => $servant->getKey(), + ]); + + // The campaign ends once the territory is assigned: an assignment cannot start in a terminated campaign + Campaign::query()->whereKey($expiredCampaign->getKey())->update(['valid_until' => now()->subMonth()->endOfDay()]); + } +} diff --git a/database/seeders/FakeTerritoryAssignmentSeeder.php b/database/seeders/FakeTerritoryAssignmentSeeder.php index dcadd20c..865a2a29 100644 --- a/database/seeders/FakeTerritoryAssignmentSeeder.php +++ b/database/seeders/FakeTerritoryAssignmentSeeder.php @@ -32,13 +32,14 @@ class FakeTerritoryAssignmentSeeder extends Seeder * Run the database seeds. * * Each territory gets at most one assignment, so that it is never assigned to two users at - * once, and only the campaigns already started (see `FakeCampaignSeeder`) are used. + * once, and only the campaigns already started and not terminated (see `FakeCampaignSeeder`) are used: a + * terminated campaign gets no new assignments. */ public function run(): void { $users = User::all(); $campaigns = Campaign::query() - ->where(fn ($query) => $query->whereNull('valid_from')->orWhere('valid_from', '<=', now())) + ->withActive() ->get(); if ($campaigns->isEmpty()) { diff --git a/package-lock.json b/package-lock.json index 87d93aee..49b8edf2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,6 +6,7 @@ "": { "name": "opencongregationhelper", "devDependencies": { + "@playwright/test": "1.63.0", "@tailwindcss/forms": "^0.5.7", "@tailwindcss/typography": "^0.5.20", "@tailwindcss/vite": "^4.3.3", @@ -131,6 +132,22 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@playwright/test": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz", + "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.19", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", @@ -1309,6 +1326,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/postcss": { "version": "8.5.32", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", diff --git a/package.json b/package.json index b347b851..0e47d0ea 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,12 @@ "type": "module", "scripts": { "build": "vite build", - "dev": "vite" + "dev": "vite", + "test:e2e": "playwright test", + "test:e2e:ui": "playwright test --ui" }, "devDependencies": { + "@playwright/test": "1.63.0", "@tailwindcss/forms": "^0.5.7", "@tailwindcss/typography": "^0.5.20", "@tailwindcss/vite": "^4.3.3", diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 00000000..bc60e7ae --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,91 @@ +import { defineConfig, devices } from '@playwright/test'; + +/** + * The end-to-end tests (see the "End-to-end tests" section of `README.md`). + * + * Two instances of the application are served by `tests/e2e/support/serve.sh`, each with its own `.env`, storage and + * database: `app`, installed and seeded with `E2eSeeder`, and `setup`, empty, for the setup wizard. + */ +const appPort = Number(process.env.E2E_APP_PORT ?? 8010); +// The name of the seeded instance (its `.env`, storage and database), e.g. to run a second one next to the first +export const appInstance = process.env.E2E_APP_INSTANCE ?? 'app'; +const setupPort = Number(process.env.E2E_SETUP_PORT ?? 8011); + +export const appURL = `http://127.0.0.1:${appPort}`; +export const setupURL = `http://127.0.0.1:${setupPort}`; + +export default defineConfig({ + testDir: './tests/e2e', + outputDir: './test-results', + timeout: 60_000, + expect: { timeout: 10_000 }, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + workers: process.env.CI ? 2 : 3, + reporter: process.env.CI + ? [['github'], ['list'], ['html', { open: 'never' }]] + : [['list'], ['html', { open: 'never' }]], + use: { + baseURL: appURL, + locale: 'en-US', + timezoneId: 'UTC', + // What helps to debug a failed test: on CI its retry is recorded (a trace, to replay it step by step with the + // page, the network and the console, and a video), so that the tests that pass are not slowed down; locally + // the trace of every failed test is kept + trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure', + video: process.env.CI ? 'on-first-retry' : 'off', + screenshot: 'only-on-failure', + }, + projects: [ + { + name: 'auth-setup', + testMatch: /auth\.setup\.ts/, + }, + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + testIgnore: [/global-state\//, /setup-wizard\.spec\.ts/, /\.setup\.ts/], + dependencies: ['auth-setup'], + }, + { + // The tests that change what the whole application does (settings, root user): one at a time, after the + // others, so that they never change it under their feet + name: 'global-state', + use: { ...devices['Desktop Chrome'] }, + testMatch: /global-state\/.*\.spec\.ts/, + workers: 1, + dependencies: ['chromium', 'mobile'], + }, + { + name: 'mobile', + use: { ...devices['Pixel 7'] }, + grep: /@mobile/, + testIgnore: [/global-state\//, /setup-wizard\.spec\.ts/, /\.setup\.ts/], + dependencies: ['auth-setup'], + }, + { + name: 'setup-wizard', + use: { ...devices['Desktop Chrome'], baseURL: setupURL }, + testMatch: /setup-wizard\.spec\.ts/, + workers: 1, + }, + ], + webServer: [ + { + command: `tests/e2e/support/serve.sh ${appInstance} ${appPort}`, + url: `${appURL}/up`, + reuseExistingServer: !process.env.CI, + timeout: 180_000, + stdout: 'ignore', + stderr: 'pipe', + }, + { + command: `tests/e2e/support/serve.sh setup ${setupPort}`, + url: `${setupURL}/up`, + reuseExistingServer: !process.env.CI, + timeout: 180_000, + stdout: 'ignore', + stderr: 'pipe', + }, + ], +}); diff --git a/tests/Feature/E2eSeederTest.php b/tests/Feature/E2eSeederTest.php new file mode 100644 index 00000000..d7e4d8ed --- /dev/null +++ b/tests/Feature/E2eSeederTest.php @@ -0,0 +1,57 @@ +artisan('och:install')->assertSuccessful(); + $this->seed(E2eSeeder::class); +}); + +test('the users of the end-to-end tests have their role and the known password', function () { + foreach (E2eSeeder::USERS as $email => $data) { + $user = User::query()->where('email', $email)->sole(); + + expect($user->first_name)->toBe($data['first_name']) + ->and($user->can_login)->toBeTrue() + ->and($user->hasVerifiedEmail())->toBeTrue() + ->and($user->locale)->toBe('en') + ->and(Hash::check(E2eSeeder::PASSWORD, $user->password))->toBeTrue() + ->and($user->roles->pluck('name')->all())->toBe(array_filter([$data['role']])); + } +}); + +test('the root user keeps being the only root user', function () { + expect(User::rootUser()->email)->toBe(config('app.initial_root_user.email')); +}); + +test('the territory servant is the overseer of the territories department', function () { + $servant = User::query()->where('email', 'servant@e2e.test')->sole(); + + expect(Department::for(DepartmentKey::Territories)->members->pluck('id'))->toContain($servant->id); +}); + +test('the known territories are free, assigned and overdue', function () { + $publisher = User::query()->where('email', 'publisher@e2e.test')->sole(); + $territory = fn (string $name): Territory => Territory::query()->where('name', $name)->sole(); + + expect($territory('E2E Free')->assignments()->exists())->toBeFalse() + ->and($territory('E2E Commercial')->is_commercial)->toBeTrue() + ->and($territory('E2E Assigned')->assignments()->sole()->assignee_id)->toBe($publisher->id) + ->and(TerritoryAssignment::query()->overdue()->pluck('territory_id'))->toContain($territory('E2E Overdue')->id); +}); + +test('the fake data of the congregation is seeded too', function () { + expect(User::count())->toBe(1 + count(E2eSeeder::USERS) + E2eSeeder::OTHER_USERS_COUNT) + ->and(Territory::count())->toBeGreaterThan(4); +}); diff --git a/tests/Feature/FakeDataSeederTest.php b/tests/Feature/FakeDataSeederTest.php index e51ebf71..cf8e2f4e 100644 --- a/tests/Feature/FakeDataSeederTest.php +++ b/tests/Feature/FakeDataSeederTest.php @@ -136,7 +136,7 @@ ->and(Campaign::whereIn('short_name', ['H2H', 'COM'])->exists())->toBeFalse(); }); -test('the fake assignments use started campaigns and one territory each', function () { +test('the fake assignments use started, not terminated campaigns and one territory each', function () { Notification::fake(); User::factory()->create(['id' => 1]); @@ -146,7 +146,8 @@ expect($assignments)->not->toBeEmpty() ->and($assignments->pluck('territory_id')->duplicates())->toBeEmpty() - ->and($assignments->every(fn (TerritoryAssignment $assignment): bool => $assignment->campaign->valid_from === null || $assignment->campaign->valid_from->isPast()))->toBeTrue(); + ->and($assignments->every(fn (TerritoryAssignment $assignment): bool => $assignment->campaign->valid_from === null || $assignment->campaign->valid_from->isPast()))->toBeTrue() + ->and($assignments->contains(fn (TerritoryAssignment $assignment): bool => $assignment->campaign->isTerminated()))->toBeFalse(); }); test('the fake role seeder gives a role to every user but the root one', function () { diff --git a/tests/Feature/SqliteConnectionConfigTest.php b/tests/Feature/SqliteConnectionConfigTest.php new file mode 100644 index 00000000..7ddcfa02 --- /dev/null +++ b/tests/Feature/SqliteConnectionConfigTest.php @@ -0,0 +1,26 @@ +toBe('15000') + ->and($config['connections']['sqlite']['journal_mode'])->toBe('wal'); +}); + +test('SQLite keeps its defaults when the environment sets nothing', function () { + $config = require config_path('database.php'); + + expect($config['connections']['sqlite']['busy_timeout'])->toBeNull() + ->and($config['connections']['sqlite']['journal_mode'])->toBeNull(); +}); diff --git a/tests/e2e/api.spec.ts b/tests/e2e/api.spec.ts new file mode 100644 index 00000000..dd616625 --- /dev/null +++ b/tests/e2e/api.spec.ts @@ -0,0 +1,170 @@ +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { test, expect } from '@playwright/test'; +import { php } from './support/artisan'; +import { appInstance } from '../../playwright.config'; + +/** + * The token of the Artisan endpoints, kept in the storage of the seeded instance (see `EnsureArtisanToken`). The same one + * is written by every run, and never removed, so that the runs in parallel never pull it from under each other: the + * storage is emptied when `serve.sh` starts anyway. + */ +const artisanToken = 'e2e-artisan-token'; +const artisanTokenFile = path.join( + fileURLToPath(new URL('../..', import.meta.url)), + 'storage', + 'e2e', + appInstance, + 'framework', + '.artisan-token', +); + +/** + * The token of the cron endpoints (`ARTISAN_CRON_TOKEN` in `serve.sh`). + */ +const cronToken = 'e2e-cron-token'; + +/** + * Headers making a request come from an address of its own: the cron endpoints are limited to 10 requests a minute by + * address, and the tests in parallel all come from 127.0.0.1. + */ +const ownAddress = (): Record => ({ + 'X-Forwarded-For': `10.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${1 + Math.floor(Math.random() * 254)}`, + Accept: 'application/json', +}); + +/** + * Store the token of the Artisan endpoints, unless it already is. + */ +function setUpArtisanToken(): void { + if (!existsSync(artisanTokenFile) || readFileSync(artisanTokenFile, 'utf8').trim() !== artisanToken) { + writeFileSync(artisanTokenFile, `${artisanToken}\n`); + } +} + +test.describe('Artisan command endpoints', () => { + test.beforeAll(() => setUpArtisanToken()); + + test('reject the requests without a token', async ({ request }) => { + const list = await request.get('/api/artisan/list', { headers: ownAddress() }); + expect(list.status()).toBe(401); + expect(await list.json()).toEqual({ error: 'Unauthorized' }); + + const execute = await request.post('/api/artisan/execute/about', { headers: ownAddress() }); + expect(execute.status()).toBe(401); + }); + + test('reject the requests with a wrong token, or with the old bypass header', async ({ request }) => { + const variants: Record[] = [{ 'X-Artisan-Token': 'wrong' }, { 'X-Artisan-Token-Bypass': 'true' }, { 'X-Artisan-Token': '' }]; + + for (const headers of variants) { + const list = await request.get('/api/artisan/list', { headers: { ...ownAddress(), ...headers } }); + expect(list.status(), JSON.stringify(headers)).toBe(401); + + const execute = await request.post('/api/artisan/execute/test-endpoint', { headers: { ...ownAddress(), ...headers } }); + expect(execute.status(), JSON.stringify(headers)).toBe(401); + } + }); + + test('list the commands with the right token', async ({ request }) => { + const response = await request.get('/api/artisan/list', { headers: { ...ownAddress(), 'X-Artisan-Token': artisanToken } }); + + expect(response.status()).toBe(200); + const body = await response.json(); + expect(body.success).toBe(true); + expect(body.output).toEqual(expect.arrayContaining(['about', 'migrate', 'queue:work', 'schedule:run'])); + }); + + test('execute a command with the right token, and refuse an unknown one', async ({ request }) => { + const headers = { ...ownAddress(), 'X-Artisan-Token': artisanToken }; + + const ping = await request.post('/api/artisan/execute/test-endpoint', { headers, data: { params: '--e2e' } }); + expect(ping.status()).toBe(200); + expect(await ping.json()).toMatchObject({ success: true, returnCode: 0 }); + expect((await ping.json()).output).toContain('>>> --e2e <<<'); + + const about = await request.post('/api/artisan/execute/about', { headers, data: { params: '--only=environment' } }); + expect(about.status()).toBe(200); + expect(await about.json()).toMatchObject({ success: true, returnCode: 0 }); + expect((await about.json()).output).toContain('OCH E2E'); + + const unknown = await request.post('/api/artisan/execute/e2e:no-such-command', { headers }); + expect(unknown.status()).toBe(404); + expect(await unknown.json()).toMatchObject({ success: false, returnCode: -1 }); + + const invalid = await request.post('/api/artisan/execute/about', { headers, data: { params: ['--json'] } }); + expect(invalid.status()).toBe(422); + }); +}); + +test.describe('Cron endpoints', () => { + for (const endpoint of ['/api/artisan/queue/process', '/api/artisan/schedule/process']) { + test(`${endpoint} rejects a missing or wrong X-Cron-Token`, async ({ request }) => { + const missing = await request.post(endpoint, { headers: ownAddress() }); + expect(missing.status()).toBe(401); + expect(await missing.json()).toEqual({ error: 'Unauthorized' }); + + const wrong = await request.post(endpoint, { headers: { ...ownAddress(), 'X-Cron-Token': 'wrong' } }); + expect(wrong.status()).toBe(401); + + // The token of the Artisan commands is not the one of the cron endpoints + const artisan = await request.post(endpoint, { headers: { ...ownAddress(), 'X-Artisan-Token': artisanToken } }); + expect(artisan.status()).toBe(401); + }); + + test(`${endpoint} runs with the right X-Cron-Token`, async ({ request }) => { + const response = await request.post(endpoint, { headers: { ...ownAddress(), 'X-Cron-Token': cronToken } }); + + expect(response.status()).toBe(200); + expect(await response.json()).toMatchObject({ success: true, returnCode: 0 }); + }); + } + + test('the queue endpoint refuses parameters out of its limits', async ({ request }) => { + const response = await request.post('/api/artisan/queue/process', { + headers: { ...ownAddress(), 'X-Cron-Token': cronToken }, + data: { maxJobs: 1000 }, + }); + + expect(response.status()).toBe(400); + expect(await response.json()).toMatchObject({ success: false, output: 'Invalid max_jobs parameter' }); + }); +}); + +test.describe('MCP server of the AI assistants', () => { + test.beforeAll(() => { + // The tests expect the default of the Security settings, which they never change + const enabled = php('return app(\\App\\Settings\\SecuritySettings::class)->ai_assistants_enabled;'); + test.skip(enabled, 'The AI assistants have been allowed in the Security settings.'); + }); + + test('is not served while the AI assistants are not allowed', async ({ request }) => { + const initialize = await request.post('/mcp', { + headers: ownAddress(), + data: { jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }, + }); + expect(initialize.status()).toBe(404); + + const withToken = await request.post('/mcp', { + headers: { ...ownAddress(), Authorization: 'Bearer not-a-token' }, + data: { jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }, + }); + expect(withToken.status()).toBe(404); + expect(withToken.headers()['www-authenticate']).toBeUndefined(); + }); + + test('hides the OAuth discovery and registration endpoints while the AI assistants are not allowed', async ({ request }) => { + for (const url of ['/.well-known/oauth-protected-resource/mcp', '/.well-known/oauth-protected-resource', '/.well-known/oauth-authorization-server']) { + const response = await request.get(url, { headers: ownAddress() }); + expect(response.status(), url).toBe(404); + } + + const register = await request.post('/oauth/register', { + headers: ownAddress(), + data: { client_name: 'E2E', redirect_uris: ['https://claude.ai/api/mcp/auth_callback'] }, + }); + expect(register.status()).toBe(404); + expect(php("return \\Laravel\\Passport\\Client::query()->where('name', 'E2E')->count();")).toBe(0); + }); +}); diff --git a/tests/e2e/assignments.spec.ts b/tests/e2e/assignments.spec.ts new file mode 100644 index 00000000..f7faac65 --- /dev/null +++ b/tests/e2e/assignments.spec.ts @@ -0,0 +1,302 @@ +import type { Browser, Page } from '@playwright/test'; +import { appURL } from '../../playwright.config'; +import { php } from './support/artisan'; +import { bulkMenuAction, chooseOption, confirmModal, expectNotification, field, modal, row, rowMenuAction, searchTableUntilApplied, settle, visit } from './support/filament'; +import { expect, logIn, test, uniqueName, users } from './support/fixtures'; + +/** + * The assignments of the territories (`app/Filament/Resources/TerritoryAssignments`), and the actions assigning and + * returning the territories. + * + * Every test assigns territories of a zone of its own, to people of its own when it needs to sign in as them. + */ + +test.describe.configure({ mode: 'parallel' }); + +type Arranged = { zoneId: number; ids: Record; assignments: Record }; + +/** + * Create a zone with territories, assigning those that have an assignee (by email) to them, in a campaign when given + * one (by id). + */ +function arrange(zoneName: string, territories: { name: string; assignee?: string; campaignId?: number }[]): Arranged { + return php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(zoneName)}]); + $ids = []; + $assignments = []; + + foreach (json_decode(${JSON.stringify(JSON.stringify(territories))}, true) as $attributes) { + $territory = \\App\\Models\\Territory::factory()->withMap()->for($zone)->create(['name' => $attributes['name']]); + $ids[$territory->name] = $territory->id; + + if (isset($attributes['assignee'])) { + $assignments[$territory->name] = $territory->assignments()->create([ + 'assignee_id' => \\App\\Models\\User::where('email', $attributes['assignee'])->sole()->id, + 'campaign_id' => $attributes['campaignId'] ?? null, + 'started_at' => now()->subDays(7), + ])->id; + } + } + + return ['zoneId' => $zone->id, 'ids' => $ids, 'assignments' => $assignments]; + `); +} + +/** + * Create a user who can sign in, with the role, returning their id, name and email (their password is `password`). + */ +function createUser(role: string): { id: number; name: string; email: string } { + const firstName = uniqueName('Pat').replace(/\s+/g, ''); + + return php(` + $user = \\App\\Models\\User::factory()->create([ + 'first_name' => ${JSON.stringify(firstName)}, + 'last_name' => 'Tester', + 'email' => strtolower(${JSON.stringify(firstName)}).'@e2e.test', + 'email_verified_at' => now(), + 'locale' => 'en', + ]); + $user->assignRole(${JSON.stringify(role)}); + + return ['id' => $user->id, 'name' => $user->full_name, 'email' => $user->email]; + `); +} + +/** + * Sign in as a user in a browser context of their own. + */ +async function signIn(browser: Browser, email: string): Promise { + const context = await browser.newContext({ baseURL: appURL }); + const page = await context.newPage(); + await logIn(page, email, 'password'); + await expect(page).not.toHaveURL(/\/login/); + + return page; +} + +/** + * The assignment in progress of a territory, if any: its id, assignee and campaign. + */ +const currentAssignmentOf = (territoryId: number): { id: number; assignee: string; campaign: string | null } | null => php(` + $assignment = \\App\\Models\\TerritoryAssignment::with('assignee', 'campaign')->where('territory_id', ${territoryId})->whereNull('ended_at')->first(); + + return $assignment ? ['id' => $assignment->id, 'assignee' => $assignment->assignee->full_name, 'campaign' => $assignment->campaign?->name] : null; +`); + +/** + * Create a campaign of the given validity, returning its id. + */ +const createCampaign = (name: string, validFrom: string, validUntil: string): number => php(` + return \\App\\Models\\Campaign::factory()->createQuietly(['name' => ${JSON.stringify(name)}, 'valid_from' => ${validFrom}, 'valid_until' => ${validUntil}])->id; +`); + +/** The rows of the records of the table (not the individual search row). */ +const tableRows = (page: Page) => page.locator('.fi-ta-row:has(.fi-ta-record-checkbox)'); + +test.describe('Assigning territories', () => { + test('assigns a free territory from the territories table, in a campaign', async ({ adminPage: page }) => { + const zone = uniqueName('Assign Zone'); + const name = `${zone} Free`; + const campaign = uniqueName('Assign Campaign'); + const { ids } = arrange(zone, [{ name }]); + createCampaign(campaign, 'now()->subDay()', 'now()->addMonths(2)'); + + await visit(page, '/app/territories'); + await searchTableUntilApplied(page, name); + await rowMenuAction(page, name, 'Assign Territory'); + await expect(modal(page).getByRole('heading', { name: 'Create new assignment' })).toBeVisible(); + await chooseOption(modal(page), 'Assigned to', users.servant.name); + await chooseOption(modal(page), 'Campaign', campaign); + await confirmModal(page, 'Create'); + + await expectNotification(page, 'Territory assigned'); + await expect(row(page, name)).toContainText(users.servant.name); + expect(currentAssignmentOf(ids[name])).toMatchObject({ assignee: users.servant.name, campaign }); + }); + + test('assigns a free territory from its page @mobile', async ({ adminPage: page }) => { + const zone = uniqueName('Assign Zone'); + const name = `${zone} Free`; + const { ids } = arrange(zone, [{ name }]); + + await visit(page, `/app/territories/${ids[name]}`); + await page.locator('.fi-header').getByRole('button', { name: 'Assign Territory' }).click(); + await chooseOption(modal(page), 'Assigned to', users.publisher.name); + await confirmModal(page, 'Create'); + + await expectNotification(page, 'Territory assigned'); + // The header actions only follow the new assignment once the page is reloaded + await visit(page, `/app/territories/${ids[name]}`); + await expect(page.locator('.fi-header').getByRole('button', { name: 'End Assignment' })).toBeVisible(); + await expect(page.locator('.fi-header').getByRole('button', { name: 'Assign Territory' })).toHaveCount(0); + expect(currentAssignmentOf(ids[name])).toMatchObject({ assignee: users.publisher.name, campaign: null }); + }); + + test('ends the assignment of a territory from the territories table', async ({ adminPage: page }) => { + const zone = uniqueName('Cancel Zone'); + const name = `${zone} Out`; + const { ids } = arrange(zone, [{ name, assignee: users.publisher.email }]); + + await visit(page, '/app/territories'); + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText(users.publisher.name); + await rowMenuAction(page, name, 'End Assignment'); + await expect(modal(page).getByRole('button', { name: 'Assigned to' })).toBeDisabled(); + await confirmModal(page, 'End'); + + await expectNotification(page, 'Territory returned successfully'); + await expect(row(page, name)).toContainText('Ended today'); + expect(currentAssignmentOf(ids[name])).toBeNull(); + }); + + test('assigns several territories at once, then ends their assignments at once', async ({ adminPage: page }) => { + const zone = uniqueName('Bulk Zone'); + const names = [`${zone} One`, `${zone} Two`]; + const { ids } = arrange(zone, names.map((name) => ({ name }))); + + await visit(page, '/app/territories'); + await searchTableUntilApplied(page, zone); + await expect(tableRows(page)).toHaveCount(2); + await bulkMenuAction(page, names, 'Assign Massively'); + await chooseOption(modal(page), 'Assigned to', users.group.name); + await confirmModal(page, /submit|confirm/i); + + await expectNotification(page, '2 territories assigned'); + for (const name of names) { + await expect(row(page, name)).toContainText(users.group.name); + expect(currentAssignmentOf(ids[name])).toMatchObject({ assignee: users.group.name }); + } + + await bulkMenuAction(page, names, 'End Assignments'); + await confirmModal(page, /confirm/i); + + await expectNotification(page, '2 territories returned'); + for (const name of names) { + expect(currentAssignmentOf(ids[name])).toBeNull(); + } + }); +}); + +test.describe('Assignments list', () => { + test('shows the assignments of ended campaigns in their tab, with a banner', async ({ adminPage: page }) => { + const zone = uniqueName('Overdue Zone'); + const name = `${zone} Late`; + const campaign = uniqueName('Ended Campaign'); + const campaignId = createCampaign(campaign, 'now()->subMonths(2)', 'now()->addMonth()'); + arrange(zone, [{ name, assignee: users.publisher.email, campaignId }]); + // The campaign ends once the territory is assigned: an assignment cannot start in a terminated campaign + php(`\\App\\Models\\Campaign::query()->whereKey(${campaignId})->update(['valid_until' => now()->subWeek()]); return true;`); + + await visit(page, '/app/territory-assignments'); + const tabs = page.getByRole('group', { name: 'Filter records' }); + await expect(tabs.getByRole('button', { name: 'All' })).toBeVisible(); + await expect(tabs.getByRole('button', { name: /^Campaign ending soon/ })).toBeVisible(); + await expect(page.getByRole('heading', { name: /still out for a campaign that has ended/ })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Return all' })).toBeVisible(); + + await tabs.getByRole('button', { name: /^Campaign ended \d+$/ }).click(); + await settle(page); + await expect(row(page, 'E2E Overdue')).toBeVisible(); + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText(`Campaign ended 7 days ago`); + + await tabs.getByRole('button', { name: /^Campaign ending soon/ }).click(); + await settle(page); + await expect(tableRows(page)).toHaveCount(0); + }); + + test('returns an assignment from the list', async ({ adminPage: page }) => { + const zone = uniqueName('Return Zone'); + const name = `${zone} Done`; + const { assignments } = arrange(zone, [{ name, assignee: users.publisher.email }]); + + await visit(page, '/app/territory-assignments'); + await searchTableUntilApplied(page, name); + await row(page, name).getByRole('button', { name: 'End Assignment' }).click(); + await confirmModal(page, 'End'); + + await expectNotification(page, 'Territory returned successfully'); + // Only the assignments in progress are listed by default + await expect(tableRows(page)).toHaveCount(0); + expect(php(`return \\App\\Models\\TerritoryAssignment::find(${assignments[name]})->ended_at !== null;`)).toBe(true); + + await visit(page, `/app/territory-assignments/${assignments[name]}`); + await expect(page.getByText('Assignment End')).toBeVisible(); + await expect(page.locator('.fi-header').getByRole('button', { name: 'End Assignment' })).toHaveCount(0); + }); + + test('edits the notes of an assignment', async ({ adminPage: page }) => { + const zone = uniqueName('Edit Zone'); + const name = `${zone} Noted`; + const { assignments } = arrange(zone, [{ name, assignee: users.publisher.email }]); + + await visit(page, '/app/territory-assignments'); + await searchTableUntilApplied(page, name); + await rowMenuAction(page, name, 'Edit'); + await expect(modal(page).getByRole('button', { name: 'Territory' })).toBeDisabled(); + await field(modal(page), 'Any Notes').fill('Keys at the reception'); + await confirmModal(page, 'Save changes'); + + await expectNotification(page, 'Saved'); + expect(php(`return \\App\\Models\\TerritoryAssignment::find(${assignments[name]})->notes;`)).toBe('Keys at the reception'); + }); +}); + +test.describe('Returning on request', () => { + test('the assignee asks to return their territory, then the servant is notified and returns it', async ({ browser, servantPage }) => { + const publisher = createUser('publisher'); + const zone = uniqueName('Request Zone'); + const name = `${zone} Asked`; + const { assignments } = arrange(zone, [{ name, assignee: publisher.email }]); + const assignmentId = assignments[name]; + + const publisherPage = await signIn(browser, publisher.email); + await visit(publisherPage, `/app/territory-assignments/${assignmentId}`); + await expect(publisherPage.getByText(name).first()).toBeVisible(); + await publisherPage.locator('.fi-header').getByRole('button', { name: 'Ask to return' }).click(); + await expect(modal(publisherPage).getByRole('heading', { name: 'Ask to return the territory?' })).toBeVisible(); + await confirmModal(publisherPage, 'Ask to return'); + + await expectNotification(publisherPage, 'Return requested'); + await expect(publisherPage.getByRole('heading', { name: /Return requested on / })).toBeVisible(); + await expect(publisherPage.locator('.fi-header').getByRole('button', { name: 'Ask to return' })).toHaveCount(0); + expect(php(`return \\App\\Models\\TerritoryAssignment::find(${assignmentId})->return_requested_at !== null;`)).toBe(true); + + // The territory department is notified (in the language of the servant, which the seeder picks at random) + expect(php(` + return \\App\\Models\\User::where('email', ${JSON.stringify(users.servant.email)})->sole()->notifications()->get() + ->contains(fn ($notification) => str_contains($notification->data['title'] ?? '', ${JSON.stringify(name)}) + && str_ends_with($notification->data['actions'][0]['url'] ?? '', '/app/territory-assignments/${assignmentId}')); + `)).toBe(true); + await visit(servantPage, '/app'); + await servantPage.getByRole('button', { name: /^Notifications/ }).click(); + await expect(servantPage.getByRole('dialog').getByText(name).first()).toBeVisible(); + await servantPage.keyboard.press('Escape'); + + await visit(servantPage, `/app/territory-assignments/${assignmentId}`); + await expect(servantPage.getByRole('heading', { name: /Return requested on / })).toBeVisible(); + await servantPage.locator('.fi-sc-callout, [class*="callout"]').filter({ hasText: 'Return requested on' }) + .getByRole('button', { name: 'End Assignment' }).click(); + await confirmModal(servantPage, 'End'); + + await expectNotification(servantPage, 'Assignment returned'); + await expect(servantPage.getByText('Assignment End')).toBeVisible(); + expect(php(`return \\App\\Models\\TerritoryAssignment::find(${assignmentId})->ended_at !== null;`)).toBe(true); + await publisherPage.context().close(); + }); +}); + +test.describe('Assignments of a user', () => { + test('lists the assignments of a user on their page', async ({ adminPage: page }) => { + const user = createUser('publisher'); + const zone = uniqueName('User Zone'); + arrange(zone, [{ name: `${zone} First`, assignee: user.email }, { name: `${zone} Second`, assignee: user.email }, { name: `${zone} Other` }]); + + await visit(page, `/app/users/${user.id}/assignments`); + + await expect(page.getByRole('heading', { level: 1, name: `Assignments of ${user.name}` })).toBeVisible(); + await expect(tableRows(page)).toHaveCount(2); + await expect(row(page, `${zone} First`)).toContainText('(in progress)'); + await expect(row(page, `${zone} Second`)).toBeVisible(); + }); +}); diff --git a/tests/e2e/auth.setup.ts b/tests/e2e/auth.setup.ts new file mode 100644 index 00000000..622078a2 --- /dev/null +++ b/tests/e2e/auth.setup.ts @@ -0,0 +1,14 @@ +import { test as setup, expect } from '@playwright/test'; +import { logIn } from './support/fixtures'; +import { roles, storageStateOf, users } from './support/users'; + +/** + * Sign in once with every user, saving the browser state that the tests reuse (see `pageAs()`). + */ +for (const role of roles) { + setup(`sign in as ${role}`, async ({ page }) => { + await logIn(page, users[role].email, users[role].password); + await expect(page).not.toHaveURL(/\/login/); + await page.context().storageState({ path: storageStateOf(role) }); + }); +} diff --git a/tests/e2e/auth.spec.ts b/tests/e2e/auth.spec.ts new file mode 100644 index 00000000..6be50ab3 --- /dev/null +++ b/tests/e2e/auth.spec.ts @@ -0,0 +1,252 @@ +import { type Page } from '@playwright/test'; +import { test, expect, logIn, uniqueName, useOwnAddress } from './support/fixtures'; +import { php } from './support/artisan'; +import { expectNotification, field, modal, settle, visit } from './support/filament'; +import { linkInLastMailTo } from './support/mail'; +import { totp } from './support/totp'; + +/** + * A user of its own for a test that changes it (password, two-factor authentication, failed attempts), with the + * password `password`, English as language and a verified email. + */ +function createThrowawayUser(attributes: Record = {}): { id: number; email: string; name: string } { + const name = uniqueName('Auth'); + const email = `${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}@e2e.test`; + const id = php(` + $user = \\App\\Models\\User::factory()->create(array_merge([ + 'first_name' => 'Auth', + 'last_name' => ${JSON.stringify(name.slice(5))}, + 'email' => ${JSON.stringify(email)}, + 'email_verified_at' => now(), + 'locale' => 'en', + ], json_decode(${JSON.stringify(JSON.stringify(attributes))}, true))); + $user->assignRole('publisher'); + + return $user->id; + `); + + return { id, email, name }; +} + +/** + * Sign out through the user menu. + */ +async function logOut(page: Page): Promise { + await page.getByRole('button', { name: 'User menu' }).click(); + await page.getByRole('button', { name: 'Sign out' }).or(page.getByRole('menuitem', { name: 'Sign out' })).first().click(); + await expect(page).toHaveURL(/\/app\/login$/); +} + +/** + * Enable the authenticator app on the profile page, returning its secret and recovery codes. + */ +async function enableAuthenticatorApp(page: Page, password: string): Promise<{ secret: string; recoveryCodes: string[] }> { + await visit(page, '/app/edit-profile'); + await page.getByRole('button', { name: 'Set up' }).click(); + + const dialog = modal(page); + await expect(dialog.getByRole('heading', { name: 'Set up authenticator app' })).toBeVisible(); + const secret = (await dialog.getByRole('button', { name: /^[A-Z2-7]{16,}$/ }).textContent())!.trim(); + + // The form may be sent by itself once the 6 digits are typed: the password first, then "Next" unless it was sent + await dialog.getByRole('textbox', { name: /Current password/ }).fill(password); + await dialog.getByRole('textbox', { name: /6-digit code/ }).first().click(); + await page.keyboard.type(totp(secret)); + await settle(page); + + const codes = dialog.getByRole('group', { name: 'recovery' }).getByRole('listitem'); + if (!(await codes.first().isVisible())) { + await dialog.getByRole('button', { name: 'Next' }).click(); + } + await expect(codes.first()).toBeVisible(); + const recoveryCodes = (await codes.allTextContents()).map((code) => code.trim()); + + await dialog.getByRole('button', { name: 'Enable authenticator app' }).click(); + await expect(page.locator('.fi-sc-actions-label-ctn').filter({ hasText: 'Authenticator app' })).toContainText('Enabled'); + + return { secret, recoveryCodes }; +} + +test.describe('Login', () => { + test('signs in with the right credentials and opens the dashboard @mobile', async ({ page }) => { + const user = createThrowawayUser(); + + await logIn(page, user.email, 'password'); + + await expect(page).toHaveURL(/\/app$/); + await expect(page.getByRole('heading', { level: 1, name: 'Dashboard' })).toBeVisible(); + }); + + test('refuses a wrong password', async ({ page }) => { + const user = createThrowawayUser(); + + await logIn(page, user.email, 'not-the-password'); + + await expect(page.getByText('These credentials do not match our records.')).toBeVisible(); + await expect(page).toHaveURL(/\/app\/login$/); + }); + + test('refuses users who are not allowed to log in', async ({ page }) => { + const user = createThrowawayUser({ can_login: false }); + + await logIn(page, user.email, 'password'); + + await expect(page.getByText('These credentials do not match our records.')).toBeVisible(); + await visit(page, '/app'); + await expect(page).toHaveURL(/\/app\/login$/); + }); + + test('signs out from the user menu', async ({ page }) => { + const user = createThrowawayUser(); + await logIn(page, user.email, 'password'); + await expect(page).toHaveURL(/\/app$/); + + await logOut(page); + + await visit(page, '/app'); + await expect(page).toHaveURL(/\/app\/login$/); + }); + + test('remembers the user with "Remember me"', async ({ page }) => { + const user = createThrowawayUser(); + await useOwnAddress(page); + await visit(page, '/app/login'); + await field(page, 'Email address').fill(user.email); + await field(page, 'Password').fill('password'); + await page.getByRole('checkbox', { name: 'Remember me' }).check(); + await page.getByRole('button', { name: 'Sign in' }).click(); + await expect(page).toHaveURL(/\/app$/); + + const cookies = await page.context().cookies(); + expect(cookies.some((cookie) => cookie.name.startsWith('remember_web_'))).toBe(true); + + // Without the session cookie, the "remember me" cookie alone signs the user in again + const remembered = cookies.filter((cookie) => !/session/i.test(cookie.name)); + await page.context().clearCookies(); + await page.context().addCookies(remembered); + await visit(page, '/app'); + await expect(page).toHaveURL(/\/app$/); + await expect(page.getByRole('heading', { level: 1, name: 'Dashboard' })).toBeVisible(); + }); + + test('does not remember the user without "Remember me"', async ({ page }) => { + const user = createThrowawayUser(); + await logIn(page, user.email, 'password'); + await expect(page).toHaveURL(/\/app$/); + + const cookies = await page.context().cookies(); + expect(cookies.some((cookie) => cookie.name.startsWith('remember_web_'))).toBe(false); + }); + + test('blocks an email after too many failed attempts, whatever the address', async ({ page }) => { + const user = createThrowawayUser(); + await visit(page, '/app/login'); + await field(page, 'Email address').fill(user.email); + + // Every attempt from a new address, so that only the throttling by email can stop them (10 per 15 minutes) + for (let attempt = 1; attempt <= 10; attempt++) { + await useOwnAddress(page); + await field(page, 'Password').fill(`wrong-password-${attempt}`); + await page.getByRole('button', { name: 'Sign in' }).click(); + await expect(page.getByText('These credentials do not match our records.')).toBeVisible(); + await settle(page); + } + + await useOwnAddress(page); + await field(page, 'Password').fill('password'); + await page.getByRole('button', { name: 'Sign in' }).click(); + + await expectNotification(page, 'Too many login attempts'); + await expect(page).toHaveURL(/\/app\/login$/); + }); +}); + +test.describe('Password reset', () => { + test('resets the password from the link sent by email', async ({ page }) => { + const user = createThrowawayUser(); + const newPassword = 'E2e-Reset-Passw0rd!'; + await useOwnAddress(page); + + await visit(page, '/app/login'); + await page.getByRole('link', { name: 'Forgot password?' }).click(); + await expect(page).toHaveURL(/\/app\/password-reset\/request$/); + + await field(page, 'Email address').fill(user.email); + await page.getByRole('button', { name: 'Send email' }).click(); + await expectNotification(page, /sent|email/i); + + await expect.poll(() => { + try { + return linkInLastMailTo(user.email, /password-reset\/reset/); + } catch { + return null; + } + }).not.toBeNull(); + await visit(page, linkInLastMailTo(user.email, /password-reset\/reset/)); + + await expect(field(page, 'Email address')).toHaveValue(user.email); + await field(page, 'Password').fill(newPassword); + await field(page, 'Confirm password').fill(newPassword); + await page.getByRole('button', { name: 'Reset password' }).click(); + await expect(page).toHaveURL(/\/app\/login$/); + + await logIn(page, user.email, 'password'); + await expect(page.getByText('These credentials do not match our records.')).toBeVisible(); + + await logIn(page, user.email, newPassword); + await expect(page).toHaveURL(/\/app$/); + }); +}); + +test.describe('Two-factor authentication', () => { + test('enables the authenticator app, then asks for its code when signing in', async ({ page }) => { + const user = createThrowawayUser(); + await logIn(page, user.email, 'password'); + await expect(page).toHaveURL(/\/app$/); + + const { secret } = await enableAuthenticatorApp(page, 'password'); + expect(php(`return filled(\\App\\Models\\User::find(${user.id})->getAppAuthenticationSecret());`)).toBe(true); + + await logOut(page); + await logIn(page, user.email, 'password'); + + // The form is sent as soon as the 6 digits are typed + const code = page.getByRole('textbox', { name: /6-digit code/ }).first(); + await code.click(); + await page.keyboard.type('000000'); + await expect(page.getByText('The code you entered is invalid.')).toBeVisible(); + await expect(page).toHaveURL(/\/app\/login$/); + + await logIn(page, user.email, 'password'); + // A code of a later period: the one used to enable the app cannot be used again + await page.getByRole('textbox', { name: /6-digit code/ }).first().click(); + await page.keyboard.type(totp(secret, Date.now() + 60_000)); + + await expect(page).toHaveURL(/\/app$/); + await expect(page.getByRole('heading', { level: 1, name: 'Dashboard' })).toBeVisible(); + }); + + test('signs in with a recovery code instead of the code of the app', async ({ page }) => { + const user = createThrowawayUser(); + await logIn(page, user.email, 'password'); + await expect(page).toHaveURL(/\/app$/); + + const { recoveryCodes } = await enableAuthenticatorApp(page, 'password'); + expect(recoveryCodes).toHaveLength(8); + + await logOut(page); + await logIn(page, user.email, 'password'); + + await page.getByRole('button', { name: 'Use a recovery code instead' }).click(); + await settle(page); + await page.getByRole('textbox', { name: 'Or, enter a recovery code' }).fill(recoveryCodes[0]); + // The field is sent to the server when it loses the focus: a click on the button meanwhile can get lost + const committed = page.waitForResponse((response) => response.url().includes('/update')); + await page.getByRole('textbox', { name: 'Or, enter a recovery code' }).press('Tab'); + await committed; + await page.getByRole('button', { name: 'Confirm sign in' }).click(); + + await expect(page).toHaveURL(/\/app$/); + await expect(page.getByRole('heading', { level: 1, name: 'Dashboard' })).toBeVisible(); + }); +}); diff --git a/tests/e2e/authorization.spec.ts b/tests/e2e/authorization.spec.ts new file mode 100644 index 00000000..f577ef34 --- /dev/null +++ b/tests/e2e/authorization.spec.ts @@ -0,0 +1,236 @@ +import type { Locator, Page } from '@playwright/test'; +import { test, expect, pageAs } from './support/fixtures'; +import { php } from './support/artisan'; +import { field, modal, visit } from './support/filament'; +import type { Role } from './support/users'; + +/** + * The items of the sidebar, with the page each one opens (the Settings cluster by its first page, the cluster itself + * only redirects to it). + */ +const navigation = { + Dashboard: '/app', + Territories: '/app/territories', + Zones: '/app/territory-zones', + Campaigns: '/app/campaigns', + Assignments: '/app/territory-assignments', + Posters: '/app/posters', + Storage: '/app/storage-locations', + 'Regular publications': '/app/publication-subscribers', + Requests: '/app/publication-requests', + 'Publication list': '/app/publications', + Users: '/app/users', + Departments: '/app/departments', + Roles: '/app/shield/roles', + Tags: '/app/tags', + Settings: '/app/settings/general', + 'Mail Logs': '/app/mail-logs', + 'Activity Logs': '/app/activitylogs', + 'Log Viewer': '/app/logs', +} as const; + +type NavigationItem = keyof typeof navigation; + +const territoryDepartment: NavigationItem[] = ['Territories', 'Zones', 'Campaigns', 'Assignments']; + +/** + * What each seeded role reaches (see `FakeRoleSeeder` and the policies): `super_admin` everything; the territory servant + * the territory department (and Departments, as the overseer of the territories department, see `DepartmentPolicy`), + * the users and the tags; the service overseer reads the territories, users and tags; the group overseer reads the + * territories and the users; the publisher reads the territories, zones and campaigns; a user without a role only the + * dashboard. The logs are for the super administrators only (the `view-logs` gate), even with the Activity permission + * of the service overseer. + */ +const visibleNavigation: Record, NavigationItem[]> = { + admin: Object.keys(navigation) as NavigationItem[], + servant: ['Dashboard', ...territoryDepartment, 'Users', 'Departments', 'Tags'], + overseer: ['Dashboard', ...territoryDepartment, 'Users', 'Tags'], + group: ['Dashboard', ...territoryDepartment, 'Users'], + publisher: ['Dashboard', 'Territories', 'Zones', 'Campaigns'], + norole: ['Dashboard'], +}; + +const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** + * A link of the sidebar, whatever its badge (e.g. "Campaigns 1"). + */ +const sidebarLink = (page: Page, item: NavigationItem): Locator => + page.getByRole('navigation', { name: 'Sidebar navigation' }).getByRole('link', { name: new RegExp(`^${escapeRegExp(item)}(\\s+\\d+)?$`) }); + +/** + * A button or link of the header of the page. + */ +const headerControl = (page: Page, name: string): Locator => { + const header = page.locator('.fi-header'); + const exact = new RegExp(`^\\s*${escapeRegExp(name)}\\s*$`); + + return header.getByRole('link', { name: exact }).or(header.getByRole('button', { name: exact })); +}; + +/** + * The HTTP status of a page for the user of the page (without following the redirects). + */ +async function statusOf(page: Page, url: string): Promise { + return (await page.context().request.get(url, { maxRedirects: 0 })).status(); +} + +test.describe('Navigation and pages by role', () => { + for (const [role, visible] of Object.entries(visibleNavigation) as [Exclude, NavigationItem[]][]) { + test(`${role} sees only the sidebar items of their permissions`, async ({ browser }) => { + const page = await pageAs(browser, role); + await visit(page, '/app'); + + for (const item of Object.keys(navigation) as NavigationItem[]) { + if (visible.includes(item)) { + await expect(sidebarLink(page, item), `${item} for ${role}`).toBeVisible(); + } else { + await expect(sidebarLink(page, item), `${item} for ${role}`).toHaveCount(0); + } + } + + await page.context().close(); + }); + + test(`${role} opens the pages of their items and is forbidden the others`, async ({ browser }) => { + const page = await pageAs(browser, role); + + for (const [item, url] of Object.entries(navigation) as [NavigationItem, string][]) { + expect(await statusOf(page, url), `${url} for ${role}`).toBe(visible.includes(item) ? 200 : 403); + } + + await page.context().close(); + }); + } + + test('a publisher is shown the forbidden page for the administration pages', async ({ publisherPage }) => { + for (const url of ['/app/users', '/app/settings/general', '/app/logs', '/app/shield/roles']) { + const response = await publisherPage.goto(url); + + expect(response?.status(), url).toBe(403); + await expect(publisherPage.getByText(/forbidden/i).first()).toBeVisible(); + } + }); + + test('a publisher navigates the territories from the menu on a phone @mobile', async ({ publisherPage, isMobile }) => { + test.skip(!isMobile, 'The sidebar of the desktop is checked above.'); + + await visit(publisherPage, '/app'); + + // On a phone the sidebar is closed: the bottom navigation has the first items, and opens it with "More" + const bottomNavigation = publisherPage.getByRole('navigation', { name: 'Bottom navigation' }); + await expect(bottomNavigation.getByRole('link', { name: 'Territories' })).toBeVisible(); + await bottomNavigation.getByRole('button', { name: 'More' }).click(); + + await expect(sidebarLink(publisherPage, 'Zones')).toBeInViewport(); + await expect(sidebarLink(publisherPage, 'Users')).toHaveCount(0); + await expect(sidebarLink(publisherPage, 'Assignments')).toHaveCount(0); + await sidebarLink(publisherPage, 'Territories').click(); + + await expect(publisherPage).toHaveURL(/\/app\/territories$/); + await expect(publisherPage.getByRole('heading', { name: 'Territories', level: 1 })).toBeVisible(); + await expect(headerControl(publisherPage, 'New territory')).toHaveCount(0); + }); +}); + +test.describe('Actions by role', () => { + let territoryId: number; + let zoneId: number; + let campaignId: number; + + test.beforeAll(() => { + ({ territoryId, zoneId, campaignId } = php<{ territoryId: number; zoneId: number; campaignId: number }>(` + return [ + 'territoryId' => \\App\\Models\\Territory::where('name', 'E2E Free')->value('id'), + 'zoneId' => \\App\\Models\\TerritoryZone::where('name', 'E2E Zone')->value('id'), + 'campaignId' => \\App\\Models\\Campaign::where('name', 'E2E Expired Campaign')->value('id'), + ]; + `)); + }); + + /** + * The create actions of the lists, by role: the publisher only reads, the service overseer organizes the + * campaigns, the group overseer assigns the territories. + */ + const createActions: { url: string; action: string; roles: Role[] }[] = [ + { url: '/app/territories', action: 'New territory', roles: ['admin', 'servant'] }, + { url: '/app/territories', action: 'Import territories', roles: ['admin', 'servant'] }, + { url: '/app/territory-zones', action: 'New zone', roles: ['admin', 'servant'] }, + { url: '/app/campaigns', action: 'New campaign', roles: ['admin', 'servant', 'overseer'] }, + { url: '/app/territory-assignments', action: 'New assignment', roles: ['admin', 'servant', 'group'] }, + { url: '/app/users', action: 'New user', roles: ['admin'] }, + ]; + + for (const role of ['admin', 'servant', 'overseer', 'group', 'publisher'] as const) { + test(`${role} is offered only the create actions of their permissions`, async ({ browser }) => { + const page = await pageAs(browser, role); + + for (const { url, action, roles } of createActions) { + if ((await statusOf(page, url)) !== 200) { + continue; + } + + await visit(page, url); + + if (roles.includes(role)) { + await expect(headerControl(page, action), `${action} for ${role}`).toBeVisible(); + } else { + await expect(headerControl(page, action), `${action} for ${role}`).toHaveCount(0); + } + } + + await page.context().close(); + }); + } + + test('a publisher reads the territories, zones and campaigns without edit or delete actions', async ({ publisherPage }) => { + await visit(publisherPage, `/app/territories/${territoryId}`); + await expect(publisherPage.getByRole('heading', { name: 'E2E Free', level: 1 })).toBeVisible(); + await expect(headerControl(publisherPage, 'Assign Territory')).toHaveCount(0); + await expect(headerControl(publisherPage, 'Edit')).toHaveCount(0); + + await visit(publisherPage, `/app/territory-zones/${zoneId}`); + await expect(publisherPage.getByRole('heading', { name: 'E2E Zone', level: 1 })).toBeVisible(); + await expect(headerControl(publisherPage, 'Edit')).toHaveCount(0); + await expect(headerControl(publisherPage, 'Delete')).toHaveCount(0); + + await visit(publisherPage, '/app/campaigns'); + await expect(publisherPage.locator('.fi-ta-row').first()).toBeVisible(); + await expect(publisherPage.locator('.fi-ta-row').getByRole('button', { name: /^(Edit|Delete)$/ })).toHaveCount(0); + await expect(publisherPage.locator('.fi-ta-row').getByRole('link', { name: /^Edit$/ })).toHaveCount(0); + + for (const url of [`/app/territories/${territoryId}/edit`, `/app/territory-zones/${zoneId}/edit`, '/app/territories/create']) { + expect(await statusOf(publisherPage, url), url).toBe(403); + } + }); + + test('the service overseer edits the campaigns but only reads the zones', async ({ browser }) => { + const page = await pageAs(browser, 'overseer'); + + await visit(page, `/app/campaigns/${campaignId}`); + await headerControl(page, 'Edit').click(); + // The campaigns are edited in a modal + await expect(field(modal(page), 'Name')).toHaveValue('E2E Expired Campaign'); + await modal(page).getByRole('button', { name: 'Cancel' }).click(); + + await visit(page, `/app/territory-zones/${zoneId}`); + await expect(page.getByRole('heading', { name: 'E2E Zone', level: 1 })).toBeVisible(); + await expect(headerControl(page, 'Edit')).toHaveCount(0); + await expect(headerControl(page, 'Delete')).toHaveCount(0); + + await page.context().close(); + }); + + test('the territory servant edits and assigns the territories', async ({ servantPage }) => { + await visit(servantPage, `/app/territories/${territoryId}`); + await expect(headerControl(servantPage, 'Assign Territory')).toBeVisible(); + + await visit(servantPage, `/app/territory-zones/${zoneId}`); + await expect(headerControl(servantPage, 'Edit')).toBeVisible(); + await expect(headerControl(servantPage, 'Delete')).toBeVisible(); + + expect(await statusOf(servantPage, `/app/territories/${territoryId}/edit`)).toBe(200); + // Users are read only for them + expect(await statusOf(servantPage, '/app/users/create')).toBe(403); + }); +}); diff --git a/tests/e2e/campaigns.spec.ts b/tests/e2e/campaigns.spec.ts new file mode 100644 index 00000000..11dcf69e --- /dev/null +++ b/tests/e2e/campaigns.spec.ts @@ -0,0 +1,282 @@ +import type { Page } from '@playwright/test'; +import { php } from './support/artisan'; +import { bulkMenuAction, chooseOption, confirmModal, expectNotification, field, modal, row, rowAction, searchTableUntilApplied, settle, visit } from './support/filament'; +import { expect, test, uniqueName, users } from './support/fixtures'; + +/** + * The campaigns (`app/Filament/Resources/Campaigns`): their list, page, widgets and assignments. + */ + +test.describe.configure({ mode: 'parallel' }); + +/** + * Create a campaign ending in the given number of days (started a month ago), returning its id. + */ +const createCampaign = (name: string, endsInDays: number): number => php(` + return \\App\\Models\\Campaign::factory()->createQuietly([ + 'name' => ${JSON.stringify(name)}, + 'valid_from' => now()->subMonth(), + 'valid_until' => now()->addDays(${endsInDays}), + ])->id; +`); + +/** + * Create territories in a zone of their own, returning their ids by name; those with an assignee (by email) are + * assigned in the campaign. + */ +function createTerritories(zoneName: string, territories: { name: string; assignee?: string }[], campaignId?: number): Record { + return php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(zoneName)}]); + $ids = []; + + foreach (json_decode(${JSON.stringify(JSON.stringify(territories))}, true) as $attributes) { + $territory = \\App\\Models\\Territory::factory()->for($zone)->create(['name' => $attributes['name']]); + $ids[$territory->name] = $territory->id; + + if (isset($attributes['assignee'])) { + $territory->assignments()->create([ + 'assignee_id' => \\App\\Models\\User::where('email', $attributes['assignee'])->sole()->id, + 'campaign_id' => ${campaignId ?? 'null'}, + 'started_at' => now()->subDays(3), + ]); + } + } + + return $ids; + `); +} + +/** + * A date as the value of a `datetime-local` input, in UTC (the timezone of the tests). + */ +const dateTimeInput = (date: Date): string => date.toISOString().slice(0, 16); + +/** The rows of the records of the table (not the individual search row). */ +const tableRows = (page: Page) => page.locator('.fi-ta-row:has(.fi-ta-record-checkbox)'); + +/** + * Set a filter of the table and apply it. + */ +async function applyFilter(page: Page, label: string, option: string): Promise { + const apply = page.getByRole('button', { name: 'Apply filters' }); + + // Clicked while the page is still loading, the button may not open the panel yet + await expect(async () => { + if (!(await apply.isVisible())) { + await page.getByRole('button', { name: 'Filter', exact: true }).click(); + } + + await expect(apply).toBeVisible({ timeout: 2_000 }); + }).toPass({ timeout: 20_000 }); + + await chooseOption(page.locator('.fi-dropdown-panel').filter({ visible: true }), label, option); + await apply.click(); + await expect(apply).toBeHidden(); + await settle(page); +} + +test.describe('Campaigns list', () => { + test('creates a campaign in the modal, which is listed with its status', async ({ adminPage: page }) => { + test.slow(); + const name = uniqueName('Campaign'); + const day = 24 * 60 * 60 * 1000; + + await visit(page, '/app/campaigns'); + await page.getByRole('button', { name: 'New campaign' }).click(); + await field(modal(page), 'Name').fill(name); + await field(modal(page), 'Description').fill('Invite everyone to the memorial'); + await field(modal(page), 'Short Name').fill('MEM'); + const color = modal(page).getByRole('combobox', { name: 'Color' }); + await color.fill('#336699'); + await color.press('Tab'); + await expect(color).toHaveValue('#336699'); + await field(modal(page), 'Valid From').fill(dateTimeInput(new Date(Date.now() - day))); + await field(modal(page), 'Valid Until').fill(dateTimeInput(new Date(Date.now() + 60 * day))); + await confirmModal(page, 'Create'); + + // Everyone is notified (and emailed) of the new campaign while it is created, which takes a while + await expect(page.locator('.fi-modal-window').filter({ hasText: 'Create Campaign' })).toBeHidden({ timeout: 150_000 }); + await expectNotification(page, 'Created'); + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText('Active'); + await expect(row(page, name)).toContainText('MEM'); + expect(php(`return \\App\\Models\\Campaign::where('name', ${JSON.stringify(name)})->sole()->only(['short_name', 'color', 'description']);`)) + .toEqual({ short_name: 'MEM', color: '#336699', description: 'Invite everyone to the memorial' }); + }); + + test('refuses a campaign ending before it starts', async ({ adminPage: page }) => { + const name = uniqueName('Backwards Campaign'); + + await visit(page, '/app/campaigns'); + await page.getByRole('button', { name: 'New campaign' }).click(); + await field(modal(page), 'Name').fill(name); + await field(modal(page), 'Valid From').fill('2026-06-10T10:00'); + await field(modal(page), 'Valid Until').fill('2026-06-01T10:00'); + await confirmModal(page, 'Create'); + + await expect(modal(page).getByText(/must be a date after/i)).toBeVisible(); + expect(php(`return \\App\\Models\\Campaign::where('name', ${JSON.stringify(name)})->exists();`)).toBe(false); + }); + + test('shows the status of the campaigns', async ({ adminPage: page }) => { + const prefix = uniqueName('Status'); + createCampaign(`${prefix} Expiring`, 5); + createCampaign(`${prefix} Ended`, -5); + + await visit(page, '/app/campaigns'); + await searchTableUntilApplied(page, prefix); + await expect(row(page, `${prefix} Expiring`)).toContainText(/Expiring|Almost Expired/); + await expect(row(page, `${prefix} Ended`)).toContainText('Terminated'); + }); + + test('edits a campaign', async ({ adminPage: page }) => { + const name = uniqueName('Campaign'); + const id = createCampaign(name, 30); + + await visit(page, '/app/campaigns'); + await searchTableUntilApplied(page, name); + await expect(tableRows(page)).toHaveCount(1); + await rowAction(page, name, 'Edit'); + await field(modal(page), 'Name').fill(`${name} edited`); + await field(modal(page), 'Short Name').fill('EDT'); + await confirmModal(page, 'Save changes'); + + await expectNotification(page, 'Saved'); + expect(php(`return \\App\\Models\\Campaign::find(${id})->only(['name', 'short_name']);`)).toEqual({ name: `${name} edited`, short_name: 'EDT' }); + }); + + test('deletes a campaign and restores it from the trashed ones', async ({ adminPage: page }) => { + const name = uniqueName('Campaign'); + const id = createCampaign(name, 30); + const isTrashed = (): boolean => php(`return \\App\\Models\\Campaign::withTrashed()->find(${id})->trashed();`); + + await visit(page, '/app/campaigns'); + await searchTableUntilApplied(page, name); + await expect(tableRows(page)).toHaveCount(1); + await rowAction(page, name, 'Delete'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + await expect(tableRows(page)).toHaveCount(0); + expect(isTrashed()).toBe(true); + + await applyFilter(page, 'Trashed Items', 'Only deleted records'); + await expect(tableRows(page)).toHaveCount(1); + await rowAction(page, name, 'Restore'); + await confirmModal(page, 'Restore'); + await expectNotification(page, 'Restored'); + expect(isTrashed()).toBe(false); + }); + + test('counts the campaigns about to end in the navigation badge', async ({ adminPage: page }) => { + createCampaign(uniqueName('Ending Campaign'), 3); + const badge = page.getByRole('navigation', { name: 'Sidebar navigation' }).getByRole('link', { name: /^Campaigns/ }); + + // Other tests may create campaigns meanwhile: compare with the count at the time of the page + await expect.poll(async () => { + await visit(page, '/app/campaigns'); + const shown = Number((await badge.innerText()).replace(/\D/g, '')); + + return shown === php('return \\App\\Models\\Campaign::query()->expiring()->count();') && shown > 0; + }).toBe(true); + }); +}); + +test.describe('Campaign page', () => { + test('shows the overview and the chart of the assignments of the campaign', async ({ adminPage: page }) => { + const name = uniqueName('Campaign'); + const id = createCampaign(name, 20); + const zone = uniqueName('Campaign Zone'); + createTerritories(zone, [{ name: `${zone} Out`, assignee: users.publisher.email }], id); + + await visit(page, `/app/campaigns/${id}`); + + await expect(page.getByRole('heading', { level: 1, name: `View ${name}` })).toBeVisible(); + const overview = page.locator('.fi-wi-stats-overview'); + await expect(overview).toContainText('Remaining days'); + await expect(overview).toContainText('20'); + await expect(overview).toContainText('Completion status'); + await expect(overview).toContainText(/\d+(\.\d+)?%/); + // The chart is loaded once scrolled into view + await page.getByRole('combobox', { name: 'Created By' }).scrollIntoViewIfNeeded(); + await page.mouse.wheel(0, 2000); + await expect(page.getByRole('heading', { name: 'Assignment status overview' })).toBeVisible(); + await expect(page.locator('.fi-wi-chart canvas')).toBeVisible(); + await expect(page.getByRole('navigation', { name: 'Tabs' }).getByRole('link', { name: 'Assignments 1' })).toBeVisible(); + }); +}); + +test.describe('Campaign assignments', () => { + test('assigns a territory in the campaign with the three steps wizard', async ({ adminPage: page }) => { + const name = uniqueName('Campaign'); + const id = createCampaign(name, 30); + const zone = uniqueName('Wizard Zone'); + const territory = `${zone} Free`; + const ids = createTerritories(zone, [{ name: territory }]); + + await visit(page, `/app/campaigns/${id}/assignments`); + await expect(page.getByRole('heading', { level: 1, name: 'Manage assignments' })).toBeVisible(); + await page.getByRole('button', { name: 'New territory assignment' }).click(); + + const wizard = modal(page); + await expect(wizard.getByRole('heading', { name: 'Create new assignment' })).toBeVisible(); + await expect(wizard.getByText(`Create a new assignment for campaign "${name}"`)).toBeVisible(); + await chooseOption(wizard, 'Territory', territory); + await chooseOption(wizard, 'Assigned to', users.servant.name); + await wizard.getByRole('button', { name: 'Next' }).click(); + + await field(wizard, 'Any Notes').fill('Start from the north side'); + await wizard.getByRole('button', { name: 'Next' }).click(); + + await expect(wizard.getByText('Review the assignment before creating')).toBeVisible(); + await expect(wizard).toContainText(name); + await expect(wizard).toContainText(users.servant.name); + await expect(wizard).toContainText(territory); + await expect(wizard).toContainText('Start from the north side'); + // The button of the last step of the wizard, not of the footer of the modal + await wizard.getByRole('button', { name: 'Create', exact: true }).click(); + + await expectNotification(page, 'Created'); + await expect(row(page, territory)).toContainText(users.servant.name); + expect(php(` + $assignment = \\App\\Models\\TerritoryAssignment::where('territory_id', ${ids[territory]})->sole(); + + return [$assignment->campaign_id, $assignment->assignee->email, $assignment->notes, $assignment->ended_at]; + `)).toEqual([id, users.servant.email, 'Start from the north side', null]); + }); + + test('terminates the selected assignments of the campaign', async ({ adminPage: page }) => { + const name = uniqueName('Campaign'); + const id = createCampaign(name, 30); + const zone = uniqueName('Terminate Zone'); + const territory = `${zone} One`; + // A single assignment: the page fails with several of them (see the test below) + createTerritories(zone, [{ name: territory, assignee: users.publisher.email }], id); + + await visit(page, `/app/campaigns/${id}/assignments`); + await expect(tableRows(page)).toHaveCount(1); + await bulkMenuAction(page, [territory], 'Terminate assignments'); + await expect(modal(page).getByRole('heading', { name: 'Terminate selected assignments' })).toBeVisible(); + await confirmModal(page, 'Terminate'); + + await expectNotification(page, 'Assignments terminated'); + await expectNotification(page, 'Successfully terminated 1 assignment(s)'); + expect(php(`return \\App\\Models\\TerritoryAssignment::where('campaign_id', ${id})->whereNull('ended_at')->count();`)).toBe(0); + // Only the assignments in progress are listed by default + await expect(tableRows(page)).toHaveCount(0); + }); + + // Bug: the assignments page of a campaign with several assignments in progress fails with a + // LazyLoadingViolationException (outside production, where models are strict): the table hides its campaign column, + // so the campaign is no longer eager loaded, but `TerritoryAssignment::isOverdue()` (called by the row classes of + // `TerritoryAssignmentResource::table()`) reads it for every row. + test.fixme('lists the assignments of a campaign that has several in progress', async ({ adminPage: page }) => { + const id = createCampaign(uniqueName('Campaign'), 30); + const zone = uniqueName('Several Zone'); + const territories = [`${zone} One`, `${zone} Two`]; + createTerritories(zone, territories.map((territory) => ({ name: territory, assignee: users.publisher.email })), id); + + await visit(page, `/app/campaigns/${id}/assignments`); + + await expect(tableRows(page)).toHaveCount(2); + }); +}); diff --git a/tests/e2e/dashboard.spec.ts b/tests/e2e/dashboard.spec.ts new file mode 100644 index 00000000..e200f055 --- /dev/null +++ b/tests/e2e/dashboard.spec.ts @@ -0,0 +1,200 @@ +import { type Browser, type Page } from '@playwright/test'; +import { test, expect, logIn, pageAs, uniqueName } from './support/fixtures'; +import { php } from './support/artisan'; +import { settle, visit } from './support/filament'; + +/** + * A publisher of its own (the dashboard remembers some choices in the session, e.g. the coverage period), signed in + * in a browser context of its own on the dashboard. + */ +async function signInAsThrowawayPublisher(browser: Browser): Promise<{ page: Page; id: number }> { + const lastName = uniqueName('Dashboard').slice('Dashboard '.length); + const email = `dashboard-${lastName}@e2e.test`; + const id = php(` + $user = \\App\\Models\\User::factory()->create([ + 'first_name' => 'Dana', + 'last_name' => ${JSON.stringify(lastName)}, + 'email' => ${JSON.stringify(email)}, + 'email_verified_at' => now(), + 'locale' => 'en', + ]); + $user->assignRole('publisher'); + + return $user->id; + `); + + const page = await (await browser.newContext()).newPage(); + await logIn(page, email, 'password'); + await expect(page).toHaveURL(/\/app$/); + await settle(page); + + return { page, id }; +} + +/** + * The number of territories worked at least once in the period chosen in the coverage widget. + */ +async function workedTerritories(page: Page): Promise { + const text = await page.locator('main').innerText(); + const match = text.match(/worked at least once\s*[\d.,]+%\s*\((\d+) of \d+\)/); + expect(match, 'the coverage widget shows the territories worked').not.toBeNull(); + + return Number(match![1]); +} + +test.describe('Dashboard widgets', () => { + test('shows the statistics, the coverage and the map to the administrators', async ({ adminPage }) => { + await visit(adminPage, '/app'); + const main = adminPage.getByRole('main'); + + await expect(main.getByText('Total number of territories')).toBeVisible(); + await expect(main.getByText('Average monthly assignment duration')).toBeVisible(); + await expect(main.getByRole('heading', { name: 'Territory coverage' })).toBeVisible(); + await expect(main.getByRole('heading', { name: 'Territory map' })).toBeVisible(); + await expect(main.getByText('Your account cannot see the territories yet')).toHaveCount(0); + }); + + test('shows the territory widgets to the publishers, whose role lets them see the territories @mobile', async ({ publisherPage }) => { + await visit(publisherPage, '/app'); + const main = publisherPage.getByRole('main'); + + await expect(main.getByText('Total number of territories')).toBeVisible(); + await expect(main.getByRole('heading', { name: 'Territory coverage' })).toBeVisible(); + await expect(main.getByRole('heading', { name: 'Territory map' })).toBeVisible(); + }); + + test('tells users without a role that there is nothing to see', async ({ browser }) => { + const page = await pageAs(browser, 'norole'); + await visit(page, '/app'); + const main = page.getByRole('main'); + + await expect(main.getByRole('heading', { name: 'Welcome, Nora Norole' })).toBeVisible(); + await expect(main.getByText('Your account cannot see the territories yet')).toBeVisible(); + await expect(main.getByText('Total number of territories')).toHaveCount(0); + await expect(main.getByRole('heading', { name: 'Territory map' })).toHaveCount(0); + await expect(main.getByText('E2E Zone')).toHaveCount(0); + await page.context().close(); + }); +}); + +test.describe('Territory coverage', () => { + test('changes the figures with the period', async ({ browser }) => { + // A territory worked only 18 months ago: covered in the last 24 months, not in the last 6 + php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(uniqueName('Coverage Zone'))}]); + $territory = \\App\\Models\\Territory::factory()->for($zone)->create(['name' => ${JSON.stringify(uniqueName('Coverage'))}]); + \\App\\Models\\TerritoryAssignment::factory()->create([ + 'territory_id' => $territory->id, + 'assignee_id' => \\App\\Models\\User::where('email', 'publisher@e2e.test')->value('id'), + 'campaign_id' => null, + 'started_at' => now()->subMonths(19), + 'ended_at' => now()->subMonths(18), + ]); + + return $territory->id; + `); + const { page } = await signInAsThrowawayPublisher(browser); + const period = page.getByRole('combobox', { name: 'Period' }); + + await period.selectOption({ label: 'Last 6 months' }); + await settle(page); + await expect(period).toHaveValue('6'); + const inSixMonths = await workedTerritories(page); + + await period.selectOption({ label: 'Last 24 months' }); + await settle(page); + await expect.poll(() => workedTerritories(page)).toBeGreaterThan(inSixMonths); + + // Remembered for the session + await visit(page, '/app'); + await expect(page.getByRole('combobox', { name: 'Period' })).toHaveValue('24'); + await page.context().close(); + }); +}); + +test.describe('Territory map', () => { + test('draws the territories with a legend of the zones', async ({ adminPage }) => { + await visit(adminPage, '/app'); + + const map = adminPage.locator('.leaflet-container'); + await expect(map).toBeVisible(); + await expect(map.locator('path.leaflet-interactive').first()).toBeAttached(); + expect(await map.locator('path.leaflet-interactive').count()).toBeGreaterThan(1); + await expect(adminPage.getByRole('button', { name: 'Zoom In' })).toBeVisible(); + + await expect(adminPage.getByRole('list', { name: 'Legend' }).getByRole('listitem').filter({ hasText: /E2E Zone\s+\(\d+\)/ })).toBeVisible(); + }); + + test('colors the territories by their current status', async ({ browser }) => { + const { page } = await signInAsThrowawayPublisher(browser); + const legend = page.getByRole('list', { name: 'Legend' }); + + await page.getByRole('combobox', { name: 'Color the territories by' }).selectOption({ label: 'Current status' }); + await settle(page); + + await expect(legend.getByRole('listitem').filter({ hasText: /^\s*Available\s+\(\d+\)\s*$/ })).toBeVisible(); + await expect(legend.getByRole('listitem').filter({ hasText: /Not available\s+\(\d+\)/ })).toBeVisible(); + await expect(legend.getByRole('listitem').filter({ hasText: /E2E Zone/ })).toHaveCount(0); + await page.context().close(); + }); +}); + +test.describe('Top bar and sidebar', () => { + test('finds a territory with the global search and opens it', async ({ servantPage }) => { + await visit(servantPage, '/app'); + + await servantPage.keyboard.press('Control+k'); + const search = servantPage.getByRole('searchbox', { name: 'Global search' }); + await expect(search).toBeFocused(); + await servantPage.keyboard.type('E2E Free'); + + const result = servantPage.getByRole('region', { name: 'Global search results' }).getByRole('link', { name: /^E2E Free \(E2E Zone\)/ }); + await expect(result).toBeVisible(); + await result.click(); + + await expect(servantPage).toHaveURL(/\/app\/territories\/\d+/); + await expect(servantPage.getByRole('heading', { level: 1 })).toContainText('E2E Free'); + }); + + test('lists the notifications of the user in the drawer', async ({ browser }) => { + const { page, id } = await signInAsThrowawayPublisher(browser); + const title = uniqueName('Notification'); + php(` + \\Filament\\Notifications\\Notification::make() + ->title(${JSON.stringify(title)}) + ->body('Sent by the end-to-end tests.') + ->sendToDatabase(\\App\\Models\\User::find(${id})); + + return true; + `); + + await visit(page, '/app'); + const bell = page.getByRole('button', { name: /^Notifications, 1 unread notification/ }); + await expect(bell).toBeVisible(); + await bell.click(); + + const drawer = page.locator('.fi-modal-window').filter({ visible: true }).last(); + const notification = drawer.getByRole('list', { name: 'Notifications' }).getByRole('listitem').filter({ hasText: title }); + await expect(notification).toBeVisible(); + await expect(notification).toContainText('Sent by the end-to-end tests.'); + + await drawer.getByRole('button', { name: 'Mark all as read' }).click(); + await expect(page.getByRole('button', { name: /unread notification/ })).toHaveCount(0); + await expect.poll(() => php(`return \\App\\Models\\User::find(${id})->unreadNotifications()->count();`)).toBe(0); + await page.context().close(); + }); + + test('collapses and expands the sidebar', async ({ adminPage }) => { + await visit(adminPage, '/app'); + const sidebar = adminPage.locator('.fi-main-sidebar'); + const expandedWidth = (await sidebar.boundingBox())!.width; + + await adminPage.getByRole('button', { name: 'Collapse sidebar' }).click(); + await expect(adminPage.getByRole('button', { name: 'Expand sidebar' })).toBeVisible(); + await expect.poll(async () => (await sidebar.boundingBox())!.width).toBeLessThan(expandedWidth); + + await adminPage.getByRole('button', { name: 'Expand sidebar' }).click(); + await expect(adminPage.getByRole('button', { name: 'Collapse sidebar' })).toBeVisible(); + await expect.poll(async () => (await sidebar.boundingBox())!.width).toBe(expandedWidth); + }); +}); diff --git a/tests/e2e/departments.spec.ts b/tests/e2e/departments.spec.ts new file mode 100644 index 00000000..5ea674d2 --- /dev/null +++ b/tests/e2e/departments.spec.ts @@ -0,0 +1,193 @@ +import type { Locator, Page } from '@playwright/test'; +import { test, expect, uniqueName, users } from './support/fixtures'; +import { php } from './support/artisan'; +import { confirmModal, expectNotification, labelled, modal, row, rowAction, visit } from './support/filament'; + +/** + * A throwaway user of the congregation, to be made a member of a department. + */ +function createUser(): { id: number; firstName: string; name: string } { + const firstName = uniqueName('Member'); + const id = php(` + return \\App\\Models\\User::factory()->create([ + 'first_name' => ${JSON.stringify(firstName)}, + 'last_name' => 'Department', + 'locale' => 'en', + ])->assignRole('publisher')->id; + `); + + return { id, firstName, name: `${firstName} Department` }; +} + +/** + * The id of a department, by its key. + */ +const departmentId = (key: string): number => php(`return \\App\\Models\\Department::where('key', ${JSON.stringify(key)})->value('id');`); + +/** + * The role of a user in a department, `null` when they are not a member. + */ +const roleIn = (departmentKey: string, userId: number): string | null => php(` + $member = \\App\\Models\\Department::where('key', ${JSON.stringify(departmentKey)})->first()->members()->whereKey(${userId})->first(); + $role = $member?->pivot->role; + + return $role instanceof \\BackedEnum ? $role->value : $role; +`); + +/** + * Add members to a department: pick them in the "Brothers" select of the modal, by name. + */ +async function addMembers(page: Page, users: { firstName: string }[], role: 'Overseer' | 'Assistant'): Promise { + await page.getByRole('button', { name: 'Add members' }).click(); + const dialog = modal(page); + await expect(dialog.getByRole('heading', { name: /^Add members to / })).toBeVisible(); + + for (const user of users) { + await pickOption(page, dialog, 'Brothers', user.firstName); + await expect(dialog.getByRole('button', { name: `Remove ${user.firstName} Department` })).toBeVisible(); + } + + await chooseRole(dialog, role); + await confirmModal(page, 'Add'); +} + +/** + * Choose the role in the department, in the modal. + */ +async function chooseRole(dialog: Locator, role: 'Overseer' | 'Assistant'): Promise { + await dialog.getByRole('radiogroup', { name: labelled('Role in the department') }).getByText(role, { exact: true }).click(); + await expect(dialog.getByRole('radio', { name: role })).toBeChecked(); +} + +/** + * Pick an option of a searchable select of Filament by searching it (the users are searched by first or last name). + */ +async function pickOption(page: Page, scope: Locator, label: string, option: string): Promise { + const search = page.locator('.fi-select-input-search-ctn input').filter({ visible: true }).first(); + + // The select is a button (named after its label, then after the options chosen); a multiple one stays open + if (!(await search.isVisible())) { + await scope.locator('.fi-fo-field').filter({ has: page.locator('label', { hasText: labelled(label) }) }).locator('.fi-select-input-btn').click(); + } + + await search.fill(option); + await page.getByRole('option', { name: option }).filter({ visible: true }).first().click(); +} + +test.describe('Departments', () => { + test('list the departments with their sections and overseers', async ({ adminPage }) => { + await visit(adminPage, '/app/departments'); + + await expect(adminPage.getByRole('heading', { name: 'Departments', level: 1 })).toBeVisible(); + await expect(adminPage.getByText('The members of a department manage its sections.')).toBeVisible(); + + const territories = row(adminPage, 'Territory Department'); + await expect(territories).toContainText('Territories, zones, assignments and campaigns.'); + await expect(territories).toContainText(users.servant.name); + for (const section of ['Territories', 'Zones', 'Assignments', 'Campaigns']) { + await expect(territories.getByRole('listitem').filter({ hasText: section })).toBeVisible(); + } + + await expect(row(adminPage, 'Public Witnessing')).toContainText('Posters'); + await expect(row(adminPage, 'Publications')).toContainText('Publication list'); + // Departments are defined by the application + await expect(adminPage.locator('.fi-header').getByRole('link', { name: /new/i })).toHaveCount(0); + }); + + test('view a department with its sections, overseers and members', async ({ adminPage }) => { + await visit(adminPage, '/app/departments'); + await row(adminPage, 'Territory Department').getByRole('link').first().click(); + + await expect(adminPage).toHaveURL(new RegExp(`/app/departments/${departmentId('territories')}$`)); + await expect(adminPage.getByRole('heading', { name: 'Territory Department', level: 1 })).toBeVisible(); + await expect(adminPage.getByRole('definition').filter({ hasText: users.servant.name })).toBeVisible(); + + const servant = row(adminPage, 'servant@e2e.test'); + await expect(servant).toContainText('Overseer'); + await expect(servant.getByRole('button', { name: 'Change role' })).toBeVisible(); + }); +}); + +test.describe('Members of a department', () => { + test('the administrator adds a member as overseer, changes their role and removes them', async ({ adminPage }) => { + const user = createUser(); + + await visit(adminPage, `/app/departments/${departmentId('publications')}`); + await addMembers(adminPage, [user], 'Overseer'); + await expectNotification(adminPage, 'Members added'); + + await expect(row(adminPage, user.name)).toContainText('Overseer'); + expect(roleIn('publications', user.id)).toBe('overseer'); + + await rowAction(adminPage, user.name, 'Change role'); + await expect(modal(adminPage).getByRole('heading', { name: user.name })).toBeVisible(); + await chooseRole(modal(adminPage), 'Assistant'); + await confirmModal(adminPage, 'Save changes'); + + await expect(row(adminPage, user.name)).toContainText('Assistant'); + expect(roleIn('publications', user.id)).toBe('assistant'); + + await rowAction(adminPage, user.name, 'Remove'); + await expect(modal(adminPage).getByRole('heading', { name: `Remove ${user.name} from the department` })).toBeVisible(); + await confirmModal(adminPage, 'Remove'); + await expectNotification(adminPage, 'Member removed'); + + await expect(adminPage.locator('.fi-ta-row').filter({ hasText: user.name })).toHaveCount(0); + expect(roleIn('publications', user.id)).toBeNull(); + }); + + test('the administrator adds several members at once and removes them in bulk', async ({ adminPage }) => { + const first = createUser(); + const second = createUser(); + + await visit(adminPage, `/app/departments/${departmentId('public_witnessing')}`); + await addMembers(adminPage, [first, second], 'Assistant'); + await expectNotification(adminPage, 'Members added'); + + await expect(row(adminPage, first.name)).toContainText('Assistant'); + await expect(row(adminPage, second.name)).toContainText('Assistant'); + + // `bulkAction()` looks for a button, the actions of the group are menu items + for (const user of [first, second]) { + await row(adminPage, user.name).getByRole('checkbox').check(); + } + await adminPage.getByRole('button', { name: 'Bulk actions' }).click(); + await adminPage.getByRole('menu', { name: 'Bulk actions' }).getByRole('menuitem', { name: 'Remove' }).click(); + await expect(modal(adminPage).getByRole('heading', { name: 'Detach selected Members' })).toBeVisible(); + await confirmModal(adminPage, 'Detach'); + + await expect(adminPage.locator('.fi-ta-row').filter({ hasText: first.name })).toHaveCount(0); + await expect(adminPage.locator('.fi-ta-row').filter({ hasText: second.name })).toHaveCount(0); + expect(roleIn('public_witnessing', first.id)).toBeNull(); + expect(roleIn('public_witnessing', second.id)).toBeNull(); + }); + + test('an overseer adds assistants to their department, but neither appoints nor removes the overseers', async ({ servantPage }) => { + const user = createUser(); + + await visit(servantPage, `/app/departments/${departmentId('territories')}`); + + // The servant cannot change their own role of overseer + const overseer = row(servantPage, 'servant@e2e.test'); + await expect(overseer).toContainText('Overseer'); + await expect(overseer.getByRole('button', { name: 'Change role' })).toHaveCount(0); + await expect(overseer.getByRole('button', { name: 'Remove' })).toHaveCount(0); + + await servantPage.getByRole('button', { name: 'Add members' }).click(); + const dialog = modal(servantPage); + await pickOption(servantPage, dialog, 'Brothers', user.firstName); + await expect(dialog.getByRole('radio', { name: 'Overseer' })).toBeDisabled(); + await chooseRole(dialog, 'Assistant'); + await confirmModal(servantPage, 'Add'); + await expectNotification(servantPage, 'Members added'); + + await expect(row(servantPage, user.name)).toContainText('Assistant'); + expect(roleIn('territories', user.id)).toBe('assistant'); + + // They manage the assistants + await rowAction(servantPage, user.name, 'Remove'); + await confirmModal(servantPage, 'Remove'); + await expectNotification(servantPage, 'Member removed'); + expect(roleIn('territories', user.id)).toBeNull(); + }); +}); diff --git a/tests/e2e/developer.spec.ts b/tests/e2e/developer.spec.ts new file mode 100644 index 00000000..f6d08d66 --- /dev/null +++ b/tests/e2e/developer.spec.ts @@ -0,0 +1,141 @@ +import { test, expect, pageAs, uniqueName, users } from './support/fixtures'; +import { php } from './support/artisan'; +import { confirmModal, expectNotification, field, modal, row, rowAction, searchTable, visit } from './support/filament'; +import type { Role } from './support/users'; + +/** + * A throwaway user, who has not chosen their password yet (so that they can be sent an invitation). + */ +function createInvitedUser(): { id: number; email: string; name: string } { + const name = uniqueName('Mailed'); + const email = `${name.toLowerCase().replaceAll(' ', '-')}@e2e.test`; + const id = php(` + return \\App\\Models\\User::factory()->create([ + 'first_name' => ${JSON.stringify(name)}, + 'last_name' => 'Developer', + 'email' => ${JSON.stringify(email)}, + 'password' => null, + 'locale' => 'en', + ])->assignRole('publisher')->id; + `); + + return { id, email, name }; +} + +test.describe('Log Viewer', () => { + test('the administrator opens the log viewer, with a tab per level', async ({ adminPage }) => { + await visit(adminPage, '/app/logs'); + + await expect(adminPage.getByRole('heading', { name: 'Log Table', level: 1 })).toBeVisible(); + + const tabs = adminPage.getByRole('navigation', { name: 'Tabs' }); + for (const level of ['All Logs', 'Error', 'Warning', 'Info', 'Debug']) { + await expect(tabs.getByRole('button', { name: level })).toBeVisible(); + } + + await tabs.getByRole('button', { name: 'Error' }).click(); + await expect(adminPage.getByRole('table', { name: 'logs' })).toBeVisible(); + await expect(adminPage.getByRole('button', { name: 'Clear Logs' })).toBeVisible(); + }); + + // BUG (achyutn/filament-log-viewer): its parser reads the entries as `[date] env.LEVEL: message` with `\w+` for the + // environment, so that no entry of an environment with a hyphen (`e2e-app`, `e2e-setup` here, but also e.g. + // `pr-123` previews) is ever listed: the viewer shows "No logs" while `laravel.log` has thousands of them. + test.fixme('the log viewer lists the entries of the log', async ({ adminPage }) => { + await visit(adminPage, '/app/logs'); + + await expect(adminPage.getByRole('table', { name: 'logs' }).locator('.fi-ta-row').first()).toBeVisible(); + }); +}); + +test.describe('Mail Logs', () => { + test('list a mail sent by resending an invitation, and show its body', async ({ adminPage }) => { + const user = createInvitedUser(); + + await visit(adminPage, `/app/users/${user.id}`); + await adminPage.locator('.fi-header').getByRole('button', { name: 'Resend invitation' }).click(); + await expect(modal(adminPage)).toContainText(user.email); + await confirmModal(adminPage, 'Resend invitation'); + await expectNotification(adminPage, `An invitation to choose the password has been sent to ${user.email}.`); + + await visit(adminPage, '/app/mail-logs'); + await searchTable(adminPage, user.email); + + const mail = row(adminPage, user.email); + await expect(mail).toContainText('Your OCH E2E account'); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + + await rowAction(adminPage, user.email, 'View'); + const details = modal(adminPage); + await expect(details.getByRole('heading', { name: 'View Mail Log' })).toBeVisible(); + await expect(details).toContainText(user.email); + await expect(details).toContainText('OCH E2E '); + + const body = details.frameLocator('iframe').first(); + await expect(body.getByText('An account has been created for you on OCH E2E.')).toBeVisible(); + await expect(body.getByRole('link', { name: 'Choose password' }).first()).toHaveAttribute('href', /\/app\/password-reset\/reset\?/); + }); +}); + +test.describe('Activity Logs', () => { + test('show the creation of a zone by the administrator, with its changes', async ({ adminPage }) => { + const zoneName = uniqueName('Logged Zone'); + + await visit(adminPage, '/app/territory-zones/create'); + await field(adminPage, 'Name').fill(zoneName); + await adminPage.getByRole('button', { name: 'Create', exact: true }).click(); + await expectNotification(adminPage, 'Created'); + + const { zoneId, activityId } = php<{ zoneId: number; activityId: number }>(` + $zone = \\App\\Models\\TerritoryZone::where('name', ${JSON.stringify(zoneName)})->firstOrFail(); + + return [ + 'zoneId' => $zone->id, + 'activityId' => \\Spatie\\Activitylog\\Models\\Activity::query() + ->where('subject_type', $zone->getMorphClass()) + ->where('subject_id', $zone->id) + ->where('event', 'created') + ->value('id'), + ]; + `); + expect(activityId).toBeTruthy(); + + await visit(adminPage, '/app/activitylogs'); + // The changes are searched too + await searchTable(adminPage, zoneName); + const activity = adminPage.locator('.fi-ta-row').filter({ has: adminPage.locator(`a[href$="/app/activitylogs/${activityId}"]`) }); + await expect(activity).toContainText(`Territory Zone # ${zoneId}`); + await expect(activity).toContainText('Created'); + await expect(activity).toContainText(users.admin.name); + + await activity.getByRole('link').first().click(); + await expect(adminPage.getByRole('heading', { name: 'View Activity Log', level: 1 })).toBeVisible(); + await expect(field(adminPage, 'Subject')).toHaveValue(`Territory Zone # ${zoneId}`); + await expect(field(adminPage, 'Description')).toHaveValue('created'); + await expect(adminPage.getByRole('region', { name: 'Changes' }).getByRole('textbox', { name: 'Value' }).first()).toHaveValue(zoneName); + }); +}); + +test.describe('Developer pages for the other users', () => { + // Only the super administrators see the logs (the `view-logs` gate), even the service overseer who has the + // Activity permissions + for (const role of ['servant', 'overseer', 'publisher'] as Role[]) { + test(`${role} has no Developer pages and is forbidden them`, async ({ browser }) => { + const page = await pageAs(browser, role); + await visit(page, '/app'); + + const sidebar = page.getByRole('navigation', { name: 'Sidebar navigation' }); + await expect(sidebar.getByRole('link', { name: 'Dashboard' })).toBeVisible(); + for (const item of ['Mail Logs', 'Activity Logs', 'Log Viewer']) { + await expect(sidebar.getByRole('link', { name: item })).toHaveCount(0); + } + + for (const url of ['/app/logs', '/app/mail-logs', '/app/activitylogs', '/app/activitylogs/1']) { + const response = await page.context().request.get(url, { maxRedirects: 0 }); + expect(response.status(), url).toBe(403); + } + + await page.context().close(); + }); + } +}); diff --git a/tests/e2e/fixtures/posters-import.csv b/tests/e2e/fixtures/posters-import.csv new file mode 100644 index 00000000..6eeea964 --- /dev/null +++ b/tests/e2e/fixtures/posters-import.csv @@ -0,0 +1,3 @@ +Code,Title,"Storage place",Copies,Notes +imp-{suffix},"Imported poster {suffix}","Imported place {suffix} A",2,"Imported note {suffix}" +imp-{suffix},"Imported poster {suffix}","Imported place {suffix} B",5, diff --git a/tests/e2e/fixtures/publications-import.csv b/tests/e2e/fixtures/publications-import.csv new file mode 100644 index 00000000..56165014 --- /dev/null +++ b/tests/e2e/fixtures/publications-import.csv @@ -0,0 +1,3 @@ +"Name (English)",Code,Category,"Renews every (months)",Offered,"Name (Italiano)","Name (Español)" +"Imported Book {suffix}",imp-book-{suffix},Books,,yes,"Libro importato {suffix}", +"Imported Monthly {suffix}",imp-monthly-{suffix},Watchtower,1,no,,"Mensual importado {suffix}" diff --git a/tests/e2e/fixtures/storage-locations-import.csv b/tests/e2e/fixtures/storage-locations-import.csv new file mode 100644 index 00000000..3f4c14ae --- /dev/null +++ b/tests/e2e/fixtures/storage-locations-import.csv @@ -0,0 +1,2 @@ +Name,Notes +"Imported storage {suffix}","Imported note {suffix}" diff --git a/tests/e2e/fixtures/territories-import.csv b/tests/e2e/fixtures/territories-import.csv new file mode 100644 index 00000000..4fb0a375 --- /dev/null +++ b/tests/e2e/fixtures/territories-import.csv @@ -0,0 +1,3 @@ +name,description,notes,is_commercial,territoryZone +{prefix} North,Imported residential territory,Ring twice,false,{zone} +{prefix} Market,Imported commercial territory,Shops only,true,{zone} diff --git a/tests/e2e/fixtures/territory.png b/tests/e2e/fixtures/territory.png new file mode 100644 index 00000000..4bfd85c4 Binary files /dev/null and b/tests/e2e/fixtures/territory.png differ diff --git a/tests/e2e/global-state/security.spec.ts b/tests/e2e/global-state/security.spec.ts new file mode 100644 index 00000000..379c1b71 --- /dev/null +++ b/tests/e2e/global-state/security.spec.ts @@ -0,0 +1,174 @@ +import { type Page } from '@playwright/test'; +import { php } from '../support/artisan'; +import { expect, logIn, test, uniqueName } from '../support/fixtures'; +import { field, settle, visit } from '../support/filament'; +import { linkInLastMailTo } from '../support/mail'; +import { totp } from '../support/totp'; + +/** + * The account requirements and the AI assistants of the Security settings, which apply to every user: these tests + * run alone (see the `global-state` project), and turn them off again after each test. + */ +test.afterEach(() => { + php(` + $settings = app(\\App\\Settings\\SecuritySettings::class); + $settings->require_two_factor = false; + $settings->require_email_verification = false; + $settings->ai_assistants_enabled = false; + $settings->save(); + + // The root user as \`och:install\` creates it (saved quietly: its account is protected outside production) + \\App\\Models\\User::rootUser()->forceFill([ + 'email_verified_at' => null, + 'app_authentication_secret' => null, + 'app_authentication_recovery_codes' => null, + ])->saveQuietly(); + + return true; + `); +}); + +/** + * Make the root user meet a requirement, which it must before the requirement can be turned on. + */ +function rootUserMeets(requirement: 'two-factor' | 'email'): void { + php(` + \\App\\Models\\User::rootUser()->forceFill(${requirement === 'email' + ? "['email_verified_at' => now()]" + : "['app_authentication_secret' => 'JBSWY3DPEHPK3PXP']"})->saveQuietly(); + + return true; + `); +} + +/** + * A publisher who can log in, with the password `password`. + */ +function createUser(attributes: { verified?: boolean } = {}): string { + const email = `${uniqueName('security').replaceAll(' ', '-').toLowerCase()}@e2e.test`; + + php(` + \\App\\Models\\User::factory()->create([ + 'email' => ${JSON.stringify(email)}, + 'password' => 'password', + 'can_login' => true, + 'locale' => 'en', + 'email_verified_at' => ${attributes.verified === false ? 'null' : 'now()'}, + ])->assignRole('publisher'); + + return true; + `); + + return email; +} + +async function turnOn(page: Page, requirement: string): Promise { + await visit(page, '/app/settings/security'); + const toggle = page.getByRole('switch', { name: requirement }); + await toggle.click(); + await expect(toggle).toBeChecked(); + await page.getByRole('button', { name: 'Save changes' }).click(); + await settle(page); +} + +async function typeCode(page: Page, code: string): Promise { + await page.getByRole('textbox', { name: /Enter the 6-digit code/ }).first().click(); + await page.keyboard.type(code); +} + +test('two-factor authentication can be required only once the root user has it', async ({ adminPage }) => { + await turnOn(adminPage, 'Require two-factor authentication'); + + await expect(adminPage.getByText('Set up two-factor authentication for the root user first, so that it cannot be locked out.')).toBeVisible(); + expect(php('return app(\\App\\Settings\\SecuritySettings::class)->require_two_factor;')).toBe(false); +}); + +test('the users must set up two-factor authentication when it is required', async ({ adminPage, page }) => { + rootUserMeets('two-factor'); + await turnOn(adminPage, 'Require two-factor authentication'); + expect(php('return app(\\App\\Settings\\SecuritySettings::class)->require_two_factor;')).toBe(true); + + const email = createUser(); + await logIn(page, email, 'password'); + + // Every page leads to the set-up until it is done + await expect(page).toHaveURL(/\/multi-factor-authentication\/set-up/); + await page.goto('/app/territories'); + await expect(page).toHaveURL(/\/multi-factor-authentication\/set-up/); + await expect(page.getByRole('heading', { name: 'Set up two-factor authentication' })).toBeVisible(); + + await page.getByRole('button', { name: 'Set up' }).click(); + const dialog = page.getByRole('dialog', { name: 'Set up authenticator app' }); + const secret = (await dialog.getByRole('button', { name: /^[A-Z2-7]{16,}$/ }).innerText()).trim(); + + await typeCode(page, totp(secret)); + await field(dialog, 'Current password').fill('password'); + await dialog.getByRole('button', { name: 'Next' }).click(); + await settle(page); + + // The recovery codes are shown once, before enabling it + await expect(dialog.getByText(/save the following recovery codes/)).toBeVisible(); + await expect(dialog.getByRole('listitem')).toHaveCount(8); + await dialog.getByRole('button', { name: 'Enable authenticator app' }).click(); + await expect(dialog).toBeHidden(); + await expect(page.getByText('Authenticator app Enabled')).toBeVisible(); + + // Then the page asked for at first opens + await page.getByRole('button', { name: 'Continue' }).click(); + await expect(page).toHaveURL(/\/app\/territories$/); + await expect(page.getByRole('heading', { name: 'Territories', level: 1 })).toBeVisible(); + expect(php(`return \\App\\Models\\User::where('email', ${JSON.stringify(email)})->sole()->hasTwoFactorAuthentication();`)).toBe(true); +}); + +test('the email confirmation can be required only once the root user has confirmed its own', async ({ adminPage }) => { + await turnOn(adminPage, 'Require email confirmation'); + + await expect(adminPage.getByText('Confirm the email address of the root user first, so that it cannot be locked out.')).toBeVisible(); + expect(php('return app(\\App\\Settings\\SecuritySettings::class)->require_email_verification;')).toBe(false); +}); + +test('the users must confirm their email address when it is required', async ({ adminPage, page }) => { + rootUserMeets('email'); + await turnOn(adminPage, 'Require email confirmation'); + expect(php('return app(\\App\\Settings\\SecuritySettings::class)->require_email_verification;')).toBe(true); + + const email = createUser({ verified: false }); + await logIn(page, email, 'password'); + + await expect(page).toHaveURL(/\/email-verification\/prompt/); + await expect(page.getByRole('heading', { name: 'Verify your email address' })).toBeVisible(); + + await page.getByRole('button', { name: 'Resend it.' }).click(); + await settle(page); + + await page.goto(linkInLastMailTo(email, /verify/)); + await expect(page).toHaveURL(/\/app\/?$/); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + expect(php(`return \\App\\Models\\User::where('email', ${JSON.stringify(email)})->sole()->hasVerifiedEmail();`)).toBe(true); +}); + +test('the unconfirmed users can use the app while the confirmation is not required', async ({ page }) => { + const email = createUser({ verified: false }); + await logIn(page, email, 'password'); + + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); +}); + +test('allowing the AI assistants opens the MCP server and the profile section', async ({ adminPage, request }) => { + const callServer = async (): Promise => + (await request.post('/mcp', { headers: { Accept: 'application/json' }, maxRedirects: 0 })).status(); + + expect(await callServer()).toBe(404); + + await visit(adminPage, '/app/edit-profile'); + await expect(adminPage.getByRole('heading', { name: 'AI assistants' })).toHaveCount(0); + + await turnOn(adminPage, 'Allow AI assistants'); + expect(php('return app(\\App\\Settings\\SecuritySettings::class)->ai_assistants_enabled;')).toBe(true); + + // The MCP server now asks the assistants to authenticate + expect(await callServer()).toBe(401); + + await visit(adminPage, '/app/edit-profile'); + await expect(adminPage.getByRole('heading', { name: 'AI assistants' })).toBeVisible(); +}); diff --git a/tests/e2e/global-state/settings.spec.ts b/tests/e2e/global-state/settings.spec.ts new file mode 100644 index 00000000..d26e7913 --- /dev/null +++ b/tests/e2e/global-state/settings.spec.ts @@ -0,0 +1,255 @@ +import { type Browser, type Page } from '@playwright/test'; +import { php } from '../support/artisan'; +import { expect, pageAs, test, uniqueName } from '../support/fixtures'; +import { confirmModal, field, modal, searchTableUntilApplied, settle, visit } from '../support/filament'; + +/** + * The settings of the application (Administration > Settings), which change what every user sees: these tests run + * alone (see the `global-state` project), and put the defaults back after each test. + */ +test.afterEach(() => { + php(` + $general = app(\\App\\Settings\\GeneralSettings::class); + $general->app_name = null; + $general->kingdom_hall_address = null; + $general->save(); + + $territories = app(\\App\\Settings\\TerritorySettings::class); + $territories->map_default_center = null; + $territories->sharing_enabled = true; + $territories->shared_pii = null; + $territories->guest_returns = null; + $territories->stale_after_days = 60; + $territories->dead_after_days = 150; + $territories->save(); + + $campaigns = app(\\App\\Settings\\CampaignSettings::class); + $campaigns->expiring_days = 7; + $campaigns->almost_expired_days = 3; + $campaigns->save(); + + return true; + `); +}); + +/** + * Save the settings, waiting until they are saved (unless the form is expected to be refused). + */ +async function save(page: Page, { refused = false }: { refused?: boolean } = {}): Promise { + await page.getByRole('button', { name: 'Save changes' }).click(); + + if (!refused) { + await expect(page.locator('.fi-no-notification').filter({ hasText: 'Saved' }).last()).toBeVisible(); + } + + await settle(page); +} + +/** + * A territory assigned to the publisher, shared through a public link. + */ +function sharedAssignment(): { id: number; url: string } { + return php(` + $territory = \\App\\Models\\Territory::factory()->withMap()->create([ + 'name' => ${JSON.stringify(uniqueName('Shared'))}, + 'notes' => 'Ring twice', + 'territory_zone_id' => \\App\\Models\\TerritoryZone::where('name', 'E2E Zone')->value('id'), + ]); + $assignment = \\App\\Models\\TerritoryAssignment::factory()->create([ + 'territory_id' => $territory->id, + 'assignee_id' => \\App\\Models\\User::where('email', 'publisher@e2e.test')->value('id'), + 'campaign_id' => null, + 'started_at' => now()->subDay(), + 'ended_at' => null, + ]); + + return ['id' => $assignment->id, 'url' => $assignment->share()->getShareableUrl()]; + `); +} + +async function openAsGuest(browser: Browser, url: string): Promise { + const page = await (await browser.newContext()).newPage(); + await page.goto(url); + await settle(page); + + return page; +} + +test.describe('general settings', () => { + test('the name of the congregation is shown in the whole app', async ({ adminPage, browser }) => { + const name = uniqueName('Congregation'); + + await visit(adminPage, '/app/settings/general'); + await field(adminPage, 'Name of the app').fill(name); + await field(adminPage, 'Kingdom Hall address').fill('1 Main Street, Springfield'); + await save(adminPage); + + await expect(adminPage.locator('.fi-no-notification').filter({ hasText: 'Saved' })).toBeVisible(); + + // Another user sees it in the top bar and the title of the pages + const publisher = await pageAs(browser, 'publisher'); + await visit(publisher, '/app'); + await expect(publisher.getByRole('link', { name }).first()).toBeVisible(); + await expect(publisher).toHaveTitle(new RegExp(name)); + await publisher.context().close(); + + await visit(adminPage, '/app/settings/general'); + await expect(field(adminPage, 'Kingdom Hall address')).toHaveValue('1 Main Street, Springfield'); + }); + + test('the name of the congregation is required', async ({ adminPage }) => { + await visit(adminPage, '/app/settings/general'); + const name = field(adminPage, 'Name of the app'); + await name.fill(''); + await save(adminPage, { refused: true }); + + // The browser refuses to submit the form, and the name is kept + expect(await name.evaluate((input: HTMLInputElement) => input.validity.valueMissing)).toBe(true); + expect(php('return app(\\App\\Settings\\GeneralSettings::class)->app_name;')).toBeNull(); + }); +}); + +test.describe('territory settings', () => { + test('the default map centre is saved and validated', async ({ adminPage }) => { + await visit(adminPage, '/app/settings/territories'); + const centre = field(adminPage, 'Default map centre'); + + await centre.fill('not a position'); + await save(adminPage, { refused: true }); + await expect(adminPage.locator('.fi-fo-field-wrp-error-message, [data-validation-error]').first()).toBeVisible(); + + await centre.fill('45.464211, 9.191383'); + await save(adminPage); + await adminPage.reload(); + await settle(adminPage); + await expect(field(adminPage, 'Default map centre')).toHaveValue('45.464211, 9.191383'); + }); + + test('disabling sharing deletes the shared links and hides the share action', async ({ adminPage, browser }) => { + const assignment = sharedAssignment(); + + await visit(adminPage, '/app/settings/territories'); + await adminPage.getByRole('switch', { name: 'Share assignments' }).click(); + + // Turning it off asks first, since saving deletes the links + await expect(modal(adminPage)).toContainText('Disable sharing?'); + await expect(modal(adminPage)).toContainText(/existing shared link/); + await confirmModal(adminPage, 'Disable sharing'); + await settle(adminPage); + await expect(adminPage.getByRole('switch', { name: 'Share assignments' })).not.toBeChecked(); + await save(adminPage); + + expect(php('return \\App\\Models\\SharedUrl::count();')).toBe(0); + + const guest = await openAsGuest(browser, assignment.url); + await expect(guest.getByText(/404|not found/i).first()).toBeVisible(); + await guest.context().close(); + + await visit(adminPage, `/app/territory-assignments/${assignment.id}`); + await expect(adminPage.getByRole('button', { name: 'Share' })).toHaveCount(0); + }); + + test('hiding the personal data removes the assignee from the shared pages', async ({ browser, adminPage }) => { + const assignment = sharedAssignment(); + + const before = await openAsGuest(browser, assignment.url); + await expect(before.getByText('Paul Publisher')).toBeVisible(); + await before.context().close(); + + await visit(adminPage, '/app/settings/territories'); + await adminPage.getByRole('radio', { name: /Hide personal data/ }).check(); + await save(adminPage); + + const after = await openAsGuest(browser, assignment.url); + await expect(after.getByText('Paul Publisher')).toHaveCount(0); + await expect(after.getByText('Ring twice')).toHaveCount(0); + await after.context().close(); + }); + + test('showing the personal data asks for a confirmation', async ({ adminPage }) => { + php(` + $settings = app(\\App\\Settings\\TerritorySettings::class); + $settings->shared_pii = false; + $settings->save(); + + return true; + `); + + await visit(adminPage, '/app/settings/territories'); + await adminPage.getByRole('radio', { name: /Show personal data/ }).check(); + + const confirmation = modal(adminPage); + await expect(confirmation).toContainText('Show personal data on shared pages?'); + + // The confirmation needs the box ticked + await confirmModal(adminPage, 'Show personal data'); + await expect(confirmation.getByText('Confirm that you understand what showing the personal data means.')).toBeVisible(); + + await confirmation.getByRole('checkbox').check(); + await confirmModal(adminPage, 'Show personal data'); + await settle(adminPage); + await expect(adminPage.getByRole('radio', { name: /Show personal data/ })).toBeChecked(); + await save(adminPage); + + expect(php('return app(\\App\\Settings\\TerritorySettings::class)->shared_pii;')).toBe(true); + }); + + test('the shared pages can stop offering to return the territory', async ({ browser, adminPage }) => { + const assignment = sharedAssignment(); + + const before = await openAsGuest(browser, assignment.url); + await expect(before.getByRole('button', { name: 'Ask to return' })).toBeVisible(); + await before.context().close(); + + await visit(adminPage, '/app/settings/territories'); + await adminPage.getByRole('switch', { name: 'Ask to return from shared pages' }).click(); + await save(adminPage); + + const after = await openAsGuest(browser, assignment.url); + await expect(after.getByRole('heading').first()).toBeVisible(); + await expect(after.getByRole('button', { name: 'Ask to return' })).toHaveCount(0); + await after.context().close(); + }); + + test('the days of the assignments out for too long are saved', async ({ adminPage }) => { + await visit(adminPage, '/app/settings/territories'); + await field(adminPage, 'Out for too long').fill('45'); + await field(adminPage, 'Lost').fill('120'); + await save(adminPage); + + expect(php(` + $settings = app(\\App\\Settings\\TerritorySettings::class); + + return [$settings->stale_after_days, $settings->dead_after_days]; + `)).toEqual([45, 120]); + }); +}); + +test.describe('campaign settings', () => { + test('the expiry days change the status of the campaigns', async ({ adminPage }) => { + const name = uniqueName('Expiring campaign'); + php(` + \\App\\Models\\Campaign::factory()->create([ + 'name' => ${JSON.stringify(name)}, + 'valid_from' => now()->subWeek(), + 'valid_until' => now()->addDays(5)->endOfDay(), + ]); + + return true; + `); + + // Searched for, since the other tests may have added enough campaigns to push it to another page + await visit(adminPage, '/app/campaigns'); + await searchTableUntilApplied(adminPage, name); + await expect(adminPage.locator('.fi-ta-row').filter({ hasText: name })).toContainText('Expiring'); + + await visit(adminPage, '/app/settings/campaigns'); + await field(adminPage, 'Expiring').fill('4'); + await field(adminPage, 'Almost Expired').fill('2'); + await save(adminPage); + + await visit(adminPage, '/app/campaigns'); + await searchTableUntilApplied(adminPage, name); + await expect(adminPage.locator('.fi-ta-row').filter({ hasText: name })).toContainText('Active'); + }); +}); diff --git a/tests/e2e/knowledge-base.spec.ts b/tests/e2e/knowledge-base.spec.ts new file mode 100644 index 00000000..84c6aa1a --- /dev/null +++ b/tests/e2e/knowledge-base.spec.ts @@ -0,0 +1,127 @@ +import { type Page } from '@playwright/test'; +import { test, expect } from './support/fixtures'; +import { modal, settle, visit } from './support/filament'; + +/** + * The sidebar of the knowledge base, with the sections (groups) and the articles of `docs/user-documentation`. + */ +const sidebar = (page: Page) => page.getByRole('navigation', { name: 'Sidebar navigation' }); + +/** + * The title of the article shown. + */ +const articleTitle = (page: Page) => page.getByRole('main').getByRole('heading', { level: 1 }).first(); + +test.describe('Knowledge base', () => { + test('opens on the getting started article, without signing in @mobile', async ({ page }) => { + await visit(page, '/knowledge-base'); + + await expect(page).toHaveURL(/\/knowledge-base\/getting-started$/); + await expect(articleTitle(page)).toHaveText('Getting started'); + await expect(page.getByRole('main').getByRole('article')).toContainText('Open Source'); + }); + + test('lists the sections and their articles, and opens them from the sidebar', async ({ page }) => { + await visit(page, '/knowledge-base'); + + for (const section of ['Basics', 'Territories', 'Assignments', 'Public Witnessing', 'Publications', 'Administration', 'Guides']) { + await expect(sidebar(page).getByRole('button', { name: section, exact: true })).toBeVisible(); + } + + await sidebar(page).getByRole('link', { name: 'Zones', exact: true }).click(); + await expect(page).toHaveURL(/\/knowledge-base\/territories\/zones$/); + await expect(articleTitle(page)).toHaveText('Zones'); + + await sidebar(page).getByRole('link', { name: 'Assigning and returning' }).click(); + await expect(page).toHaveURL(/\/knowledge-base\/assignments\/assigning$/); + await expect(articleTitle(page)).toHaveText('Assigning and returning'); + await expect(page.getByRole('main').getByRole('navigation', { name: 'Breadcrumb' })).toContainText('Assigning and returning'); + }); + + test('collapses a section of the sidebar', async ({ page }) => { + await visit(page, '/knowledge-base'); + + const section = sidebar(page).getByRole('button', { name: 'Guides', exact: true }); + const article = sidebar(page).getByRole('link', { name: 'Running a campaign' }); + await expect(section).toHaveAttribute('aria-expanded', 'true'); + await expect(article).toBeVisible(); + + await section.click(); + await expect(section).toHaveAttribute('aria-expanded', 'false'); + await expect(article).toBeHidden(); + }); + + test('follows the links between articles', async ({ page }) => { + await visit(page, '/knowledge-base/territories/introduction'); + + await page.getByRole('main').getByRole('article').getByRole('link', { name: 'Importing territories' }).click(); + + await expect(page).toHaveURL(/\/knowledge-base\/territories\/importing$/); + await expect(articleTitle(page)).toHaveText('Importing territories'); + }); + + test('finds articles with the search', async ({ page }) => { + await visit(page, '/knowledge-base'); + + await page.getByRole('searchbox', { name: 'Global search' }).fill('campaign'); + const results = page.getByRole('region', { name: 'Global search results' }); + await expect(results.getByRole('link', { name: 'Running a campaign' })).toBeVisible(); + + await results.getByRole('link', { name: 'Running a campaign' }).click(); + await expect(page).toHaveURL(/\/knowledge-base\/guides\/running-a-campaign$/); + await expect(articleTitle(page)).toHaveText('Running a campaign'); + }); + + test('switches to the Italian documentation', async ({ page }) => { + await visit(page, '/knowledge-base/territories/zones'); + await expect(articleTitle(page)).toHaveText('Zones'); + + await page.getByRole('button', { name: 'English' }).click(); + await page.getByRole('menuitem', { name: /Italian/ }).click(); + await settle(page); + + await expect(page.getByRole('button', { name: 'Italiano' }).or(page.getByRole('button', { name: 'Italian' }))).toBeVisible(); + await expect(sidebar(page).getByRole('button', { name: 'Territori', exact: true })).toBeVisible(); + await expect(sidebar(page).getByRole('link', { name: 'Introduzione' })).toBeVisible(); + + await visit(page, '/knowledge-base/territories/zones'); + await expect(articleTitle(page)).toHaveText('Zone'); + }); + + test('leads guests back to the welcome page', async ({ page }) => { + await visit(page, '/knowledge-base/getting-started'); + + await page.getByRole('link', { name: 'Back' }).click(); + await expect(page).toHaveURL(/127\.0\.0\.1:\d+\/$/); + }); +}); + +test.describe('Documentation from the app', () => { + test('opens the knowledge base from the sidebar, and goes back to the app', async ({ adminPage }) => { + await visit(adminPage, '/app'); + + await adminPage.locator('.fi-sidebar').getByRole('link', { name: 'Documentation', exact: true }).click(); + await expect(adminPage).toHaveURL(/\/knowledge-base/); + await expect(articleTitle(adminPage)).toHaveText('Getting started'); + + await adminPage.getByRole('link', { name: 'Back' }).click(); + await expect(adminPage).toHaveURL(/\/app$/); + }); + + test('previews the documentation of a page in a slide-over from the help menu', async ({ adminPage }) => { + await visit(adminPage, '/app/territories'); + + await adminPage.getByRole('navigation', { name: 'Topbar' }).getByRole('button', { name: 'Help' }).click(); + + const preview = modal(adminPage); + await expect(preview).toBeVisible(); + await expect(adminPage.locator('.fi-modal.fi-modal-open')).toHaveClass(/fi-modal-slide-over/); + await expect(preview.getByRole('navigation', { name: 'Breadcrumb' })).toContainText('Territories list'); + await expect(preview.getByRole('article')).toContainText('Territories are the backbone of this project'); + // The page behind stays where it was + await expect(adminPage).toHaveURL(/\/app\/territories$/); + + await preview.getByRole('button', { name: 'Close' }).first().click(); + await expect(adminPage.locator('.fi-modal.fi-modal-open')).toHaveCount(0); + }); +}); diff --git a/tests/e2e/posters.spec.ts b/tests/e2e/posters.spec.ts new file mode 100644 index 00000000..87f06c2e --- /dev/null +++ b/tests/e2e/posters.spec.ts @@ -0,0 +1,336 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +import type { Locator, Page, TestInfo } from '@playwright/test'; +import { php } from './support/artisan'; +import { + applyTableFilters, + chooseOption, + confirmModal, + downloadExport, + field, + modal, + row, + rowAction, + searchTableUntilApplied, + settle, + uploadImport, + visit, +} from './support/filament'; +import { expect, test, uniqueName } from './support/fixtures'; + +/** + * The posters of public witnessing and the places where they are kept (`app/Filament/Resources/Posters`, + * `StorageLocations`). + * + * Every test works on posters and storage places of its own, so that the tests running in parallel never see each + * other's: the seeded ones are only read. + */ + +type Stock = { location: string; quantity: number }; + +/** + * The PHP code deleting the records created by the test running, run after it (even when it fails), so that they don't + * pile up over the runs. + */ +let cleanups: string[] = []; + +/** + * Delete records after the test, with PHP code (errors are ignored: the record may be gone already). + */ +const cleanUp = (code: string): void => { + cleanups.push(`try { ${code} } catch (\\Throwable $exception) {}`); +}; + +test.afterEach(() => { + if (cleanups.length > 0) { + php(`${cleanups.join('\n')} return true;`); + cleanups = []; + } +}); + +/** + * Create a storage place, returning its id. + */ +function createLocation(name: string): number { + deleteLocationsLike(name); + + return php(`return \\App\\Models\\StorageLocation::factory()->create(['name' => ${JSON.stringify(name)}])->id;`); +} + +/** + * Delete after the test the storage places whose name starts with the text (with the copies kept there). + */ +const deleteLocationsLike = (name: string): void => + cleanUp(`\\App\\Models\\StorageLocation::where('name', 'like', ${JSON.stringify(`${name}%`)})->get()->each->delete();`); + +/** + * Delete after the test the posters whose code starts with the text. + */ +const deletePostersCoded = (code: string): void => + cleanUp(`\\App\\Models\\Poster::where('code', 'like', ${JSON.stringify(`${code}%`)})->get()->each->delete();`); + +/** + * Create a poster with its copies in storage places (created before), returning its id. + */ +function createPoster(title: string, stocks: Stock[] = [], code: string | null = null): number { + const id = php(` + $poster = \\App\\Models\\Poster::factory()->create(['title' => ['en' => ${JSON.stringify(title)}], 'code' => ${JSON.stringify(code)}]); + + foreach (json_decode(${JSON.stringify(JSON.stringify(stocks))}, true) as $stock) { + $poster->stocks()->create([ + 'storage_location_id' => \\App\\Models\\StorageLocation::where('name', $stock['location'])->sole()->id, + 'quantity' => $stock['quantity'], + ]); + } + + return $poster->id; + `); + cleanUp(`\\App\\Models\\Poster::find(${id})?->delete();`); + + return id; +} + +/** + * The copies of a poster in each storage place, by name. + */ +const stocksOf = (posterId: number): Record => php(` + return \\App\\Models\\PosterStock::where('poster_id', ${posterId})->with('storageLocation')->get() + ->mapWithKeys(fn ($stock) => [$stock->storageLocation->name => $stock->quantity])->sortKeys()->all(); +`); + +/** + * A code nobody else uses. + */ +const uniqueCode = (prefix: string): string => uniqueName(prefix).replace(' ', '-').toLowerCase(); + +/** + * A copy of a fixture CSV file of `tests/e2e/fixtures`, with `{suffix}` replaced, so that each run imports records of + * its own. + */ +function fixtureCopy(testInfo: TestInfo, fixture: string, suffix: string): string { + const file = testInfo.outputPath(fixture); + writeFileSync(file, readFileSync(`tests/e2e/fixtures/${fixture}`, 'utf8').replaceAll('{suffix}', suffix)); + + return file; +} + +/** + * Expect a notification (toast) with the text, waiting longer than `expect()` does: saving can be slow while the other + * tests run. + */ +const expectNotification = (page: Page, text: string | RegExp): Promise => + expect(page.locator('.fi-no-notification').filter({ hasText: text }).first()).toBeVisible({ timeout: 30_000 }); + +/** + * The rows of the quantities of the poster form, one for each storage place. + */ +const stockRows = (page: Page): Locator => + modal(page).getByRole('group', { name: 'Stocks' }).getByRole('row').filter({ has: page.getByRole('spinbutton') }); + +test.describe('Storage places', () => { + test('creates, renames and deletes a storage place @mobile', async ({ adminPage: page }) => { + const name = uniqueName('Storage room'); + deleteLocationsLike(name); + const renamed = `${name} renamed`; + + await visit(page, '/app/storage-locations'); + await page.getByRole('button', { name: 'New Storage place' }).click(); + await field(modal(page), 'Name').fill(name); + await field(modal(page), 'Notes').fill('Behind the stage'); + await confirmModal(page, 'Create'); + await expectNotification(page, 'Created'); + + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText('Behind the stage'); + expect(php(`return \\App\\Models\\StorageLocation::where('name', ${JSON.stringify(name)})->value('notes');`)).toBe('Behind the stage'); + + await rowAction(page, name, 'Edit'); + await field(modal(page), 'Name').fill(renamed); + await confirmModal(page, 'Save changes'); + await expectNotification(page, 'Saved'); + await expect(row(page, renamed)).toBeVisible(); + + await rowAction(page, renamed, 'Delete'); + await expect(modal(page)).toContainText('The quantities of the posters kept here will be deleted too.'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + + await expect(row(page, renamed)).toHaveCount(0); + expect(php(`return \\App\\Models\\StorageLocation::where('name', 'like', ${JSON.stringify(`${name}%`)})->exists();`)).toBe(false); + }); + + test('refuses a storage place with the name of another one', async ({ adminPage: page }) => { + const name = uniqueName('Taken place'); + createLocation(name); + + await visit(page, '/app/storage-locations'); + await page.getByRole('button', { name: 'New Storage place' }).click(); + await field(modal(page), 'Name').fill(name); + await confirmModal(page, 'Create'); + + await expect(modal(page)).toContainText('has already been taken'); + expect(php(`return \\App\\Models\\StorageLocation::where('name', ${JSON.stringify(name)})->count();`)).toBe(1); + }); + + test('exports the storage places as a CSV file', async ({ adminPage: page }) => { + const name = uniqueName('Exported place'); + deleteLocationsLike(name); + php(`return \\App\\Models\\StorageLocation::factory()->create(['name' => ${JSON.stringify(name)}, 'notes' => 'Exported note'])->id;`); + + await visit(page, '/app/storage-locations'); + const { fileName, lines: [header, ...lines] } = await downloadExport(page, 'Export Storage'); + + expect(fileName).toMatch(/^export-\d+-.+\.csv$/); + expect(header).toBe('Name,Notes'); + expect(lines).toContain(`"${name}","Exported note"`); + expect(lines).toContainEqual(expect.stringMatching(/^"Kingdom Hall",/)); + }); + + test('imports storage places from a CSV file', async ({ adminPage: page }, testInfo) => { + const suffix = uniqueCode('s'); + deleteLocationsLike(`Imported storage ${suffix}`); + + await visit(page, '/app/storage-locations'); + await uploadImport(page, 'Import Storage', fixtureCopy(testInfo, 'storage-locations-import.csv', suffix)); + + await expect.poll(() => php(`return \\App\\Models\\StorageLocation::where('name', ${JSON.stringify(`Imported storage ${suffix}`)})->value('notes');`)) + .toBe(`Imported note ${suffix}`); + + await visit(page, '/app/storage-locations'); + await searchTableUntilApplied(page, suffix); + await expect(row(page, `Imported storage ${suffix}`)).toBeVisible(); + }); +}); + +test.describe('Posters', () => { + test('creates a poster with its copies in each storage place, edits and deletes it', async ({ adminPage: page }) => { + const prefix = uniqueName('Poster place'); + const [first, second] = [`${prefix} A`, `${prefix} B`]; + createLocation(first); + createLocation(second); + const title = uniqueName('Poster'); + const code = uniqueCode('ps'); + deletePostersCoded(code); + + await visit(page, '/app/posters'); + await page.getByRole('button', { name: 'New Poster' }).click(); + await field(modal(page), 'Code').fill(code); + await field(modal(page), 'English').fill(title); + await expect(stockRows(page)).toHaveCount(1); + await stockRows(page).nth(0).getByRole('combobox').selectOption({ label: first }); + await stockRows(page).nth(0).getByRole('spinbutton').fill('3'); + await modal(page).getByRole('button', { name: 'Add storage place' }).click(); + await expect(stockRows(page)).toHaveCount(2); + await stockRows(page).nth(1).getByRole('combobox').selectOption({ label: second }); + await stockRows(page).nth(1).getByRole('spinbutton').fill('4'); + await confirmModal(page, 'Create'); + await expectNotification(page, 'Created'); + + const posterId = php(`return \\App\\Models\\Poster::where('code', ${JSON.stringify(code)})->value('id');`); + expect(stocksOf(posterId)).toEqual({ [first]: 3, [second]: 4 }); + + await searchTableUntilApplied(page, title); + await expect(row(page, title)).toContainText(code); + await expect(row(page, title).locator('.fi-badge').filter({ visible: true, hasText: /^\s*7\s*$/ })).toBeVisible(); + + await rowAction(page, title, 'Edit'); + await expect(stockRows(page)).toHaveCount(2); + await stockRows(page).nth(0).getByRole('spinbutton').fill('0'); + await field(modal(page), 'Notes').fill('Torn corner'); + await confirmModal(page, 'Save changes'); + await expectNotification(page, 'Saved'); + + expect(stocksOf(posterId)).toEqual({ [first]: 0, [second]: 4 }); + await expect(row(page, title)).toContainText('Torn corner'); + await expect(row(page, title).locator('.fi-badge').filter({ visible: true, hasText: /^\s*4\s*$/ })).toBeVisible(); + + await rowAction(page, title, 'Delete'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + + await expect(row(page, title)).toHaveCount(0); + expect(php(`return [\\App\\Models\\Poster::whereKey(${posterId})->exists(), \\App\\Models\\PosterStock::where('poster_id', ${posterId})->count()];`)).toEqual([false, 0]); + }); + + test('opens the storage places from the header', async ({ adminPage: page }) => { + const place = uniqueName('Header place'); + createLocation(place); + + await visit(page, '/app/posters'); + await page.locator('.fi-header').getByRole('link', { name: 'Storage' }).click(); + + await expect(page).toHaveURL(/\/app\/storage-locations$/); + await expect(page.getByRole('heading', { name: 'Storage', level: 1 })).toBeVisible(); + await searchTableUntilApplied(page, place); + await expect(row(page, place)).toBeVisible(); + }); + + test('filters the posters by availability and by storage place', async ({ adminPage: page }) => { + const prefix = uniqueName('Filtered poster'); + const [kept, elsewhere] = [`${prefix} place`, `${prefix} other place`]; + createLocation(kept); + createLocation(elsewhere); + const [inKept, outOfStock, inElsewhere] = [`${prefix} kept`, `${prefix} out of stock`, `${prefix} elsewhere`]; + createPoster(inKept, [{ location: kept, quantity: 3 }]); + createPoster(outOfStock, [{ location: kept, quantity: 0 }]); + createPoster(inElsewhere, [{ location: elsewhere, quantity: 2 }]); + const shown = page.locator('.fi-ta-row').filter({ has: page.getByRole('checkbox', { name: /^Select\/deselect item/ }) }).filter({ hasText: prefix }); + + await visit(page, '/app/posters'); + await searchTableUntilApplied(page, prefix); + await expect(shown).toHaveCount(3); + + await applyTableFilters(page, (panel) => chooseOption(panel, 'Availability', 'Out of stock')); + await expect(shown).toHaveCount(1); + await expect(row(page, outOfStock)).toBeVisible(); + + await applyTableFilters(page, (panel) => chooseOption(panel, 'Availability', 'Available')); + await expect(shown).toHaveCount(2); + await expect(row(page, outOfStock)).toHaveCount(0); + + // Only the posters with copies there + await applyTableFilters(page, async (panel) => { + await chooseOption(panel, 'Availability', '-'); + await chooseOption(panel, 'Kept in', kept); + }); + await expect(shown).toHaveCount(1); + await expect(row(page, inKept)).toBeVisible(); + }); + + test('exports the posters with a row for each storage place', async ({ adminPage: page }) => { + const place = uniqueName('Export place'); + createLocation(place); + const title = uniqueName('Exported poster'); + const code = uniqueCode('ex'); + createPoster(title, [{ location: place, quantity: 6 }], code); + + await visit(page, '/app/posters'); + const { fileName, lines: [header, ...lines] } = await downloadExport(page, 'Export Posters'); + + expect(fileName).toMatch(/^export-\d+-posters\.csv$/); + expect(header).toBe('Code,Title,"Storage place",Copies,Notes'); + expect(lines).toContainEqual(expect.stringMatching(new RegExp(`^${code},"${title}","${place}",6,`))); + expect(lines).toContainEqual(expect.stringMatching(/^demo-01,"Demo poster 1","Kingdom Hall",2,/)); + }); + + test('imports the posters, creating the missing storage places', async ({ adminPage: page }, testInfo) => { + const suffix = uniqueCode('p'); + deletePostersCoded(`imp-${suffix}`); + deleteLocationsLike(`Imported place ${suffix}`); + + await visit(page, '/app/posters'); + await uploadImport(page, 'Import Posters', fixtureCopy(testInfo, 'posters-import.csv', suffix)); + + await expect.poll(() => php(` + $poster = \\App\\Models\\Poster::where('code', ${JSON.stringify(`imp-${suffix}`)})->first(); + + return $poster ? ['title' => $poster->getTranslations('title'), 'notes' => $poster->notes] : null; + `)).toEqual({ title: { en: `Imported poster ${suffix}` }, notes: `Imported note ${suffix}` }); + + const posterId = php(`return \\App\\Models\\Poster::where('code', ${JSON.stringify(`imp-${suffix}`)})->value('id');`); + expect(stocksOf(posterId)).toEqual({ [`Imported place ${suffix} A`]: 2, [`Imported place ${suffix} B`]: 5 }); + + await visit(page, '/app/posters'); + await searchTableUntilApplied(page, `Imported poster ${suffix}`); + await expect(row(page, `Imported poster ${suffix}`).locator('.fi-badge').filter({ visible: true, hasText: /^\s*7\s*$/ })).toBeVisible(); + }); +}); diff --git a/tests/e2e/profile.spec.ts b/tests/e2e/profile.spec.ts new file mode 100644 index 00000000..8ed2db5d --- /dev/null +++ b/tests/e2e/profile.spec.ts @@ -0,0 +1,315 @@ +import { type Browser, type Page } from '@playwright/test'; +import { test, expect, logIn, uniqueName } from './support/fixtures'; +import { php } from './support/artisan'; +import { choose, expectNotification, field, modal, settle, visit } from './support/filament'; + +type ThrowawayUser = { id: number; email: string; firstName: string; lastName: string }; + +/** + * A user of its own for a test that changes it, with the password `password`, English as language and a verified email. + */ +function createThrowawayUser(): ThrowawayUser { + const lastName = uniqueName('Profile').slice('Profile '.length); + const email = `profile-${lastName}@e2e.test`; + const id = php(` + $user = \\App\\Models\\User::factory()->create([ + 'first_name' => 'Pat', + 'last_name' => ${JSON.stringify(lastName)}, + 'email' => ${JSON.stringify(email)}, + 'email_verified_at' => now(), + 'locale' => 'en', + ]); + $user->assignRole('publisher'); + + return $user->id; + `); + + return { id, email, firstName: 'Pat', lastName }; +} + +/** + * Sign in with a new throwaway user in a browser context of its own, on the profile page. + */ +async function signInAsThrowawayUser(browser: Browser, user: ThrowawayUser = createThrowawayUser()): Promise<{ page: Page; user: ThrowawayUser }> { + const context = await browser.newContext(); + const page = await context.newPage(); + await logIn(page, user.email, 'password'); + await expect(page).toHaveURL(/\/app$/); + await visit(page, '/app/edit-profile'); + + return { page, user }; +} + +/** + * A section of the profile page, by its heading. + */ +const section = (page: Page, heading: string) => + page.locator('.fi-section, [class*="grid"]').filter({ has: page.getByRole('heading', { level: 2, name: heading, exact: true }) }).last(); + +/** + * Open an item of the user menu. + */ +async function openUserMenuItem(page: Page, item: string): Promise { + await page.getByRole('button', { name: 'User menu' }).click(); + await page.getByRole('menuitem', { name: item }).click(); +} + +test.describe('Profile information', () => { + test('updates the name and the email', async ({ browser }) => { + const { page, user } = await signInAsThrowawayUser(browser); + const email = `changed-${user.email}`; + const information = section(page, 'Profile information'); + + await field(information, 'First name').fill('Renamed'); + await field(information, 'Email').fill(email); + await information.getByRole('button', { name: 'Save' }).click(); + + await expectNotification(page, 'Saved.'); + expect(php(`$user = \\App\\Models\\User::find(${user.id}); return [$user->first_name, $user->email];`)).toEqual(['Renamed', email]); + + await visit(page, '/app/edit-profile'); + await expect(page.getByRole('button', { name: 'User menu' }).getByRole('img')).toHaveAccessibleName(`Avatar of Renamed ${user.lastName}`); + await page.context().close(); + }); + + test('refuses an email already used by someone else', async ({ browser }) => { + const { page, user } = await signInAsThrowawayUser(browser); + const information = section(page, 'Profile information'); + + await field(information, 'Email').fill('admin@e2e.test'); + await information.getByRole('button', { name: 'Save' }).click(); + + await expect(information.getByText(/already been taken/)).toBeVisible(); + expect(php(`return \\App\\Models\\User::find(${user.id})->email;`)).toBe(user.email); + await page.context().close(); + }); +}); + +test.describe('Contacts', () => { + test('adds, edits and deletes a contact', async ({ browser }) => { + const { page, user } = await signInAsThrowawayUser(browser); + const contacts = section(page, 'Contact information'); + await expect(contacts.getByText('No contacts added.')).toBeVisible(); + + await contacts.getByRole('button', { name: 'Add contact' }).first().click(); + let dialog = modal(page); + await choose(dialog, 'Type', 'Emergency'); + await field(dialog, 'Name').fill('Mario Rossi'); + await field(dialog, 'Phone number').fill('+39 333 1234567'); + await dialog.getByRole('button', { name: 'Submit' }).click(); + + await expectNotification(page, 'Contact saved.'); + await expect(contacts.getByRole('row', { name: /Mario Rossi/ })).toBeVisible(); + expect(php(`return \\App\\Models\\User::find(${user.id})->contacts()->pluck('phone_number', 'name');`)).toEqual({ 'Mario Rossi': '+39 333 1234567' }); + + await contacts.getByRole('row', { name: /Mario Rossi/ }).getByRole('button', { name: 'Edit' }).click(); + dialog = modal(page); + await field(dialog, 'Name').fill('Maria Rossi'); + await dialog.getByRole('button', { name: /^(Submit|Save|Save changes|Update)$/ }).first().click(); + await expect(contacts.getByRole('row', { name: /Maria Rossi/ })).toBeVisible(); + + await contacts.getByRole('row', { name: /Maria Rossi/ }).getByRole('button', { name: 'Delete' }).click(); + await modal(page).getByRole('button', { name: /^(Delete|Confirm)$/ }).first().click(); + + await expectNotification(page, 'Contact deleted.'); + await expect(contacts.getByText('No contacts added.')).toBeVisible(); + expect(php(`return \\App\\Models\\User::find(${user.id})->contacts()->count();`)).toBe(0); + await page.context().close(); + }); + + test('needs a phone number or an address', async ({ browser }) => { + const { page, user } = await signInAsThrowawayUser(browser); + const contacts = section(page, 'Contact information'); + + await contacts.getByRole('button', { name: 'Add contact' }).first().click(); + const dialog = modal(page); + await choose(dialog, 'Type', 'Personal'); + await field(dialog, 'Name').fill('Nobody'); + await dialog.getByRole('button', { name: 'Submit' }).click(); + + await expect(dialog.getByText(/phone number field is required/i)).toBeVisible(); + expect(php(`return \\App\\Models\\User::find(${user.id})->contacts()->count();`)).toBe(0); + await page.context().close(); + }); +}); + +test.describe('Password and sessions', () => { + test('changes the password and signs in with the new one', async ({ browser }) => { + const { page, user } = await signInAsThrowawayUser(browser); + const newPassword = 'E2e-Profile-Passw0rd!'; + const password = section(page, 'Update password'); + + await field(password, 'Current password').fill('password'); + await field(password, 'New password').fill(newPassword); + await field(password, 'Confirm password').fill(newPassword); + await password.getByRole('button', { name: 'Save' }).click(); + await expectNotification(page, 'Saved.'); + + await openUserMenuItem(page, 'Sign out'); + await expect(page).toHaveURL(/\/app\/login$/); + + await logIn(page, user.email, 'password'); + await expect(page.getByText('These credentials do not match our records.')).toBeVisible(); + + await logIn(page, user.email, newPassword); + await expect(page).toHaveURL(/\/app$/); + await page.context().close(); + }); + + test('refuses a wrong current password', async ({ browser }) => { + const { page } = await signInAsThrowawayUser(browser); + const password = section(page, 'Update password'); + + await field(password, 'Current password').fill('not-the-password'); + await field(password, 'New password').fill('E2e-Profile-Passw0rd!'); + await field(password, 'Confirm password').fill('E2e-Profile-Passw0rd!'); + await password.getByRole('button', { name: 'Save' }).click(); + + await expect(password.getByText(/does not match your current password/i)).toBeVisible(); + await page.context().close(); + }); + + test('logs out the other browser sessions', async ({ browser }) => { + // Jetstream lists and logs out the other sessions only with the `database` session driver (the default one), + // while `serve.sh` serves the end-to-end tests with the `file` driver: the button then does nothing + test.skip(php(`return config('session.driver');`) !== 'database', 'Needs the database session driver'); + + const { page, user } = await signInAsThrowawayUser(browser); + const { page: otherPage } = await signInAsThrowawayUser(browser, user); + + await section(page, 'Browser sessions').getByRole('button', { name: 'Log out other browser sessions' }).click(); + const dialog = modal(page); + await dialog.getByRole('textbox', { name: /password/i }).fill('password'); + await dialog.getByRole('button', { name: 'Log out other browser sessions' }).click(); + await expectNotification(page, 'Logged out of your other browser sessions.'); + + // This session goes on, the other one has been signed out + await visit(page, '/app/edit-profile'); + await expect(page).toHaveURL(/\/app\/edit-profile$/); + await visit(otherPage, '/app/edit-profile'); + await expect(otherPage).toHaveURL(/\/app\/login$/); + + await otherPage.context().close(); + await page.context().close(); + }); + + test('deletes the own account', async ({ browser }) => { + const { page, user } = await signInAsThrowawayUser(browser); + + await section(page, 'Delete account').getByRole('button', { name: 'Delete account' }).click(); + const dialog = modal(page); + await dialog.getByRole('textbox', { name: /password/i }).fill('password'); + await dialog.getByRole('button', { name: 'Delete account' }).click(); + + await expect(page).not.toHaveURL(/edit-profile/); + await expect.poll(() => php(`return \\App\\Models\\User::find(${user.id}) === null;`)).toBe(true); + + await logIn(page, user.email, 'password'); + await expect(page.getByText('These credentials do not match our records.')).toBeVisible(); + await page.context().close(); + }); +}); + +test.describe('User menu', () => { + test('switches the theme from the UI preferences', async ({ browser }) => { + const { page } = await signInAsThrowawayUser(browser); + const html = page.locator('html'); + await expect(html).not.toHaveClass(/\bdark\b/); + + await openUserMenuItem(page, 'Settings'); + await page.getByRole('menuitemradio', { name: 'Enable dark theme' }).click(); + await expect(html).toHaveClass(/\bdark\b/); + + // Kept by the browser on the next pages + await visit(page, '/app'); + await expect(html).toHaveClass(/\bdark\b/); + + await openUserMenuItem(page, 'Settings'); + await page.getByRole('menuitemradio', { name: 'Enable light theme' }).click(); + await expect(html).not.toHaveClass(/\bdark\b/); + await page.context().close(); + }); + + test('changes the layout and the primary color from the UI preferences', async ({ browser }) => { + const { page } = await signInAsThrowawayUser(browser); + const body = page.locator('body'); + // The page reloads after each choice: the color is read once it has loaded again + const primaryColor = () => page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--primary-500').trim()).catch(() => ''); + const initialColor = await primaryColor(); + await expect(body).not.toHaveClass(/fi-body-has-top-navigation/); + + await openUserMenuItem(page, 'Settings'); + await Promise.all([ + page.waitForEvent('load'), + page.getByRole('button', { name: 'Topbar', exact: true }).click(), + ]); + await settle(page); + await expect(body).toHaveClass(/fi-body-has-top-navigation/); + + await openUserMenuItem(page, 'Settings'); + // The colors have no name: the green one + await Promise.all([ + page.waitForEvent('load'), + page.locator('[wire\\:click="setColor(\'#10b981\')"]').filter({ visible: true }).click(), + ]); + await settle(page); + await expect.poll(primaryColor).not.toBe(initialColor); + + // Kept on the next pages + await visit(page, '/app'); + await expect(body).toHaveClass(/fi-body-has-top-navigation/); + expect(await primaryColor()).not.toBe(initialColor); + await page.context().close(); + }); + + test('shows the versions, with a link to report a bug', async ({ adminPage }) => { + await visit(adminPage, '/app'); + + await openUserMenuItem(adminPage, 'About'); + + const dialog = modal(adminPage); + await expect(dialog.getByRole('heading', { name: 'Version information' })).toBeVisible(); + for (const term of ['Laravel', 'Filament', 'PHP', 'App']) { + await expect(dialog.getByRole('term').filter({ hasText: new RegExp(`^\\s*${term}\\s*$`) })).toBeVisible(); + } + + const report = dialog.getByRole('link', { name: 'Report a bug' }); + await expect(report).toHaveAttribute('target', '_blank'); + const url = new URL((await report.getAttribute('href'))!); + expect(url.pathname).toMatch(/\/issues\/new$/); + expect(url.searchParams.get('template')).toBeTruthy(); + expect(url.searchParams.get('instance')).toBe(new URL(adminPage.url()).origin); + expect(url.searchParams.get('version')).toBeTruthy(); + }); +}); + +test.describe('Language', () => { + test('switches the interface to Italian from the top bar', async ({ browser }) => { + const { page } = await signInAsThrowawayUser(browser); + await expect(page.getByRole('heading', { level: 1, name: 'Profile' })).toBeVisible(); + + await page.getByRole('navigation', { name: 'Topbar' }).getByRole('button', { name: 'English' }).click(); + await page.getByRole('menuitem', { name: /Italian/ }).click(); + await settle(page); + + await expect(page.getByRole('heading', { level: 1, name: 'Profilo' })).toBeVisible(); + await visit(page, '/app/edit-profile'); + await expect(page.getByRole('heading', { level: 1, name: 'Profilo' })).toBeVisible(); + + await page.getByRole('navigation', { name: 'Topbar' }).getByRole('button', { name: /Italian|Italiano/ }).click(); + await page.getByRole('menuitem', { name: /English|Inglese/ }).click(); + await settle(page); + await expect(page.getByRole('heading', { level: 1, name: 'Profile' })).toBeVisible(); + await page.context().close(); + }); + + test('saves the preferred language of the user', async ({ browser }) => { + const { page, user } = await signInAsThrowawayUser(browser); + const information = section(page, 'Profile information'); + + await field(information, 'Preferred language').selectOption({ label: 'Italiano (it)' }); + await information.getByRole('button', { name: 'Save' }).click(); + await expect.poll(() => php(`return \\App\\Models\\User::find(${user.id})->locale;`)).toBe('it'); + await page.context().close(); + }); +}); diff --git a/tests/e2e/public.spec.ts b/tests/e2e/public.spec.ts new file mode 100644 index 00000000..c9dc21ad --- /dev/null +++ b/tests/e2e/public.spec.ts @@ -0,0 +1,129 @@ +import { test, expect } from './support/fixtures'; + +/** + * The public pages, reachable without signing in: the welcome page, the redirects of the old routes, the files of the + * Progressive Web App and the error pages. + */ +test.describe('Welcome page', () => { + test('invites guests to log in and links to the knowledge base @mobile', async ({ page }) => { + await page.goto('/'); + + await expect(page.getByRole('heading', { level: 1, name: 'The territory register, organized and always at hand.' })).toBeVisible(); + await expect(page.getByRole('heading', { name: 'Current features' })).toBeVisible(); + await expect(page.getByRole('main').getByRole('link', { name: 'Log in' })).toHaveAttribute('href', /\/app\/login$/); + await expect(page.getByRole('main').getByRole('link', { name: 'Open the app' })).toHaveCount(0); + + await page.getByRole('link', { name: 'Read the guide' }).click(); + await expect(page).toHaveURL(/\/knowledge-base/); + }); + + test('leads guests to the login page', async ({ page }) => { + await page.goto('/'); + await page.getByRole('main').getByRole('link', { name: 'Log in' }).click(); + + await expect(page).toHaveURL(/\/app\/login$/); + await expect(page.getByRole('button', { name: 'Sign in' })).toBeVisible(); + }); + + test('links signed-in users to the dashboard', async ({ adminPage }) => { + await adminPage.goto('/'); + + const openApp = adminPage.getByRole('main').getByRole('link', { name: 'Open the app' }); + await expect(openApp).toHaveAttribute('href', /\/app$/); + await expect(adminPage.getByRole('link', { name: 'Log in' })).toHaveCount(0); + + await openApp.click(); + await expect(adminPage).toHaveURL(/\/app$/); + await expect(adminPage.getByRole('heading', { level: 1, name: 'Dashboard' })).toBeVisible(); + }); +}); + +test.describe('Redirects', () => { + test('sends /login to the login page of the panel', async ({ page }) => { + await page.goto('/login'); + + await expect(page).toHaveURL(/\/app\/login$/); + }); + + test('sends /dashboard to the panel, and guests on to the login page', async ({ page }) => { + const response = await page.request.get('/dashboard', { maxRedirects: 0 }); + expect(response.status()).toBe(302); + expect(response.headers().location).toMatch(/\/app$/); + + await page.goto('/dashboard'); + await expect(page).toHaveURL(/\/app\/login$/); + }); + + test('sends signed-in users from /dashboard to the dashboard', async ({ adminPage }) => { + await adminPage.goto('/dashboard'); + + await expect(adminPage).toHaveURL(/\/app$/); + await expect(adminPage.getByRole('heading', { level: 1, name: 'Dashboard' })).toBeVisible(); + }); + + test('sends /user/profile to the profile page', async ({ adminPage }) => { + await adminPage.goto('/user/profile'); + + await expect(adminPage).toHaveURL(/\/app\/edit-profile$/); + }); +}); + +test.describe('Progressive Web App', () => { + test('serves the web app manifest with the icons', async ({ request }) => { + const response = await request.get('/manifest.webmanifest'); + + expect(response.ok()).toBe(true); + expect(response.headers()['content-type']).toContain('application/manifest+json'); + + const manifest = await response.json(); + expect(manifest.name).toBeTruthy(); + expect(manifest.start_url).toBe('/app'); + expect(manifest.display).toBe('standalone'); + + const sizes = manifest.icons.map((icon: { sizes: string }) => icon.sizes); + expect(sizes).toEqual(expect.arrayContaining(['192x192', '512x512'])); + + const icon = await request.get(manifest.icons.find((each: { sizes: string }) => each.sizes === '192x192').src); + expect(icon.ok()).toBe(true); + expect(icon.headers()['content-type']).toContain('image/png'); + }); + + test('links the manifest from the pages', async ({ page }) => { + await page.goto('/app/login'); + + await expect(page.locator('link[rel="manifest"]')).toHaveAttribute('href', /\/manifest\.webmanifest$/); + }); + + test('serves the offline page', async ({ page }) => { + await page.goto('/offline'); + + await expect(page.getByRole('heading', { name: 'You are offline' })).toBeVisible(); + await expect(page.getByRole('button', { name: 'Try again' })).toBeVisible(); + }); +}); + +test.describe('Error pages and headers', () => { + test('answers 404 to unknown pages', async ({ page }) => { + const response = await page.goto('/this-page-does-not-exist'); + + expect(response?.status()).toBe(404); + await expect(page.getByText(/not found/i).first()).toBeVisible(); + }); + + for (const [description, url] of [ + ['web pages', '/app/login'], + ['redirects', '/dashboard'], + ['error pages', '/this-page-does-not-exist'], + ['the API', '/api/artisan/list'], + ] as const) { + test(`sends the security headers on ${description}`, async ({ request }) => { + const response = await request.get(url, { maxRedirects: 0, headers: { Accept: url.startsWith('/api') ? 'application/json' : 'text/html' } }); + const headers = response.headers(); + + expect(headers['x-frame-options']).toBe('DENY'); + expect(headers['x-content-type-options']).toBe('nosniff'); + expect(headers['referrer-policy']).toBe('strict-origin-when-cross-origin'); + expect(headers['x-powered-by']).toBeUndefined(); + }); + } +}); diff --git a/tests/e2e/publications.spec.ts b/tests/e2e/publications.spec.ts new file mode 100644 index 00000000..20a79cd7 --- /dev/null +++ b/tests/e2e/publications.spec.ts @@ -0,0 +1,509 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +import type { Locator, Page } from '@playwright/test'; +import { php } from './support/artisan'; +import { + applyTableFilters, + bulkMenuAction, + chooseOption, + confirmModal, + downloadExport, + field, + labelled, + modal, + row, + rowAction, + rowMenuAction, + searchTableUntilApplied, + settle, + uploadImport, + visit, +} from './support/filament'; +import { expect, test, uniqueName } from './support/fixtures'; + +/** + * The publications department (`app/Filament/Resources/Publications`, `PublicationRequests`, `PublicationSubscribers`): + * the publication list, the requests and the regular publications. + * + * Every test works on publications, publishers and requests of its own, so that the tests running in parallel never + * see each other's: the seeded ones are only read. + */ + +type Publisher = { id: number; name: string }; + +type PublicationAttributes = { name: string; code?: string; category?: string; renewal_months?: number | null; is_active?: boolean }; + +type RequestAttributes = { user_id: number; publication_id: number; quantity?: number; requested_at?: string; ordered_at?: string | null; delivered_at?: string | null }; + +/** + * The PHP code deleting the records created by the test running, run after it (even when it fails), so that they don't + * pile up over the runs. + */ +let cleanups: string[] = []; + +/** + * Delete records after the test, with PHP code (errors are ignored: the record may be gone already). + */ +const cleanUp = (code: string): void => { + cleanups.push(`try { ${code} } catch (\\Throwable $exception) {}`); +}; + +test.afterEach(() => { + if (cleanups.length > 0) { + php(`${cleanups.join('\n')} return true;`); + cleanups = []; + } +}); + +/** + * A code nobody else uses, for a publication. + */ +const uniqueCode = (prefix: string): string => uniqueName(prefix).replace(' ', '-').toLowerCase(); + +/** + * Create a publisher of their own (with a unique first name), returning their id and full name. + */ +function createPublisher(prefix: string = 'Pubtest'): Publisher { + return php(` + $user = \\App\\Models\\User::factory()->create(['first_name' => ${JSON.stringify(uniqueName(prefix))}, 'last_name' => 'Etoe']); + $user->assignRole('publisher'); + + return ['id' => $user->id, 'name' => $user->getFullName()]; + `); +} + +/** + * Create a publication (a book, offered, by default), returning its id. + */ +function createPublication(attributes: PublicationAttributes): number { + const id = php(` + $attributes = json_decode(${JSON.stringify(JSON.stringify({ code: uniqueCode('pub'), ...attributes }))}, true); + + return \\App\\Models\\Publication::factory()->create([ + 'name' => ['en' => $attributes['name']], + 'code' => $attributes['code'], + 'category' => $attributes['category'] ?? 'books', + 'renewal_months' => $attributes['renewal_months'] ?? null, + 'is_active' => $attributes['is_active'] ?? true, + ])->id; + `); + // With its requests and the copies received + cleanUp(`\\App\\Models\\Publication::find(${id})?->delete();`); + + return id; +} + +/** + * Create a request of a publication (requested today, by default), returning its id. + */ +function createRequest(attributes: RequestAttributes): number { + return php(` + $attributes = json_decode(${JSON.stringify(JSON.stringify(attributes))}, true); + + return \\App\\Models\\PublicationRequest::factory()->create([ + 'quantity' => 1, + 'requested_at' => today()->toDateString(), + ...$attributes, + ])->id; + `); +} + +/** + * The id of a seeded publication, by its code. + */ +const publicationIdOf = (code: string): number => + php(`return \\App\\Models\\Publication::where('code', ${JSON.stringify(code)})->value('id');`); + +/** + * Pick an option of a searchable select that has no label of its own (e.g. in the rows of a repeater). + */ +async function pickOption(page: Page, trigger: Locator, option: string): Promise { + await trigger.click(); + const search = page.locator('.fi-select-input-search-ctn input').filter({ visible: true }).first(); + + if (await search.count()) { + await search.fill(option); + } + + await page.getByRole('option', { name: option }).filter({ visible: true }).first().click(); +} + +/** + * Choose a publisher in a select: the options are searched by first or last name, not by full name. + */ +async function choosePublisher(scope: Locator, label: string, publisher: Publisher): Promise { + const page = scope.page(); + await scope.getByRole('button', { name: labelled(label) }).or(scope.getByRole('combobox', { name: labelled(label) })).first().click(); + await page.locator('.fi-select-input-search-ctn input').filter({ visible: true }).first().fill(publisher.name.split(' ').slice(0, 2).join(' ')); + await page.getByRole('listbox').filter({ visible: true }).getByRole('option', { name: publisher.name, exact: true }).first().click(); +} + +/** + * The requests page on a tab, showing only the requests of a publisher. + */ +const requestsOf = (publisher: Publisher, tab: 'to_order' | 'ordered' | 'delivered' | 'all'): string => + `/app/publication-requests?tab=${tab}&filters[user][value]=${publisher.id}`; + +/** + * Expect a notification (toast) with the text, waiting longer than `expect()` does: saving can be slow while the other + * tests run. + */ +const expectNotification = (page: Page, text: string | RegExp): Promise => + expect(page.locator('.fi-no-notification').filter({ hasText: text }).first()).toBeVisible({ timeout: 30_000 }); + +test.describe('Publication list', () => { + test('creates a publication, edits it into a regular one and deletes it', async ({ adminPage: page }) => { + const name = uniqueName('Brochure'); + const code = uniqueCode('br'); + cleanUp(`\\App\\Models\\Publication::where('code', ${JSON.stringify(code)})->get()->each->delete();`); + + await visit(page, '/app/publications'); + await page.getByRole('button', { name: 'New Publication' }).click(); + await field(modal(page), 'English').fill(name); + await chooseOption(modal(page), 'Category', 'Brochures and Booklets'); + await field(modal(page), 'Code').fill(code); + await confirmModal(page, 'Create'); + await expectNotification(page, 'Created'); + + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText(code); + await expect(row(page, name)).toContainText('Once'); + expect(php(`return \\App\\Models\\Publication::where('code', ${JSON.stringify(code)})->first()?->only(['category', 'renewal_months', 'is_active']);`)) + .toEqual({ category: 'brochures_and_booklets', renewal_months: null, is_active: true }); + + await rowMenuAction(page, name, 'Edit'); + await field(modal(page), 'Italiano').fill(`${name} IT`); + await modal(page).getByRole('switch', { name: 'Received regularly' }).click(); + await field(modal(page), 'Renews every').fill('2'); + await confirmModal(page, 'Save changes'); + await expectNotification(page, 'Saved'); + + await expect(row(page, name)).toContainText('every 2 months'); + expect(php(`$publication = \\App\\Models\\Publication::where('code', ${JSON.stringify(code)})->first(); return [$publication->renewal_months, $publication->getTranslation('name', 'it', false)];`)) + .toEqual([2, `${name} IT`]); + + await rowMenuAction(page, name, 'Delete'); + await expect(modal(page)).toContainText('The copies received regularly and the requests of this publication will be deleted too'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + + await expect(row(page, name)).toHaveCount(0); + expect(php(`return \\App\\Models\\Publication::where('code', ${JSON.stringify(code)})->exists();`)).toBe(false); + }); + + test('filters the publications by category', async ({ adminPage: page }) => { + const prefix = uniqueName('Catfilter'); + const tract = `${prefix} tract`; + const book = `${prefix} book`; + createPublication({ name: tract, category: 'tracts' }); + createPublication({ name: book, category: 'books' }); + + await visit(page, '/app/publications'); + await searchTableUntilApplied(page, prefix); + await expect(row(page, tract)).toBeVisible(); + await expect(row(page, book)).toBeVisible(); + + await applyTableFilters(page, (panel) => chooseOption(panel, 'Category', 'Tracts')); + + await expect(row(page, tract)).toBeVisible(); + await expect(row(page, book)).toHaveCount(0); + await expect(page.getByRole('heading', { name: 'Tracts', level: 2 })).toBeVisible(); + }); + + test('opens the requests of a publication', async ({ adminPage: page }) => { + const name = uniqueName('Requested book'); + const publicationId = createPublication({ name }); + const publisher = createPublisher(); + createRequest({ user_id: publisher.id, publication_id: publicationId, quantity: 4 }); + + await visit(page, '/app/publications'); + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText('1'); + await rowAction(page, name, 'Requests'); + + await expect(page).toHaveURL(new RegExp(`/app/publication-requests\\?.*tab=all.*publication.*=${publicationId}`)); + await expect(page.getByRole('heading', { name: 'Requests', level: 1 })).toBeVisible(); + await expect(row(page, publisher.name)).toContainText(name); + await expect(row(page, publisher.name)).toContainText('4'); + await expect(page.locator('.fi-ta-row').filter({ has: page.getByRole('checkbox') })).toHaveCount(1); + }); + + test('stops offering the selected publications, then offers them again', async ({ adminPage: page }) => { + const prefix = uniqueName('Offer'); + const names = [`${prefix} one`, `${prefix} two`]; + const ids = names.map((name) => createPublication({ name })); + const offered = (): boolean[] => php(`return \\App\\Models\\Publication::whereIn('id', ${JSON.stringify(ids)})->orderBy('id')->pluck('is_active')->all();`); + + await visit(page, '/app/publications'); + await searchTableUntilApplied(page, prefix); + + await bulkMenuAction(page, names, 'Stop offering'); + await expect(modal(page)).toContainText('it can no longer be chosen in the regular publications'); + await confirmModal(page, 'Confirm'); + await expectNotification(page, 'No longer offered'); + await expect(row(page, names[0]).getByRole('switch', { name: 'Offered' })).not.toBeChecked(); + await expect(row(page, names[1]).getByRole('switch', { name: 'Offered' })).not.toBeChecked(); + expect(offered()).toEqual([false, false]); + + await bulkMenuAction(page, names, 'Offer'); + await confirmModal(page, 'Confirm'); + await expectNotification(page, 'Offered'); + await expect(row(page, names[0]).getByRole('switch', { name: 'Offered' })).toBeChecked(); + expect(offered()).toEqual([true, true]); + }); + + test('exports the publication list as a CSV file', async ({ adminPage: page }) => { + const name = uniqueName('Exported book'); + const code = uniqueCode('exp'); + createPublication({ name, code }); + + await visit(page, '/app/publications'); + const { fileName, lines: [header, ...lines] } = await downloadExport(page, 'Export Publications'); + + expect(fileName).toMatch(/^export-\d+-publications\.csv$/); + expect(header).toBe('"Name (English)",Code,Category,"Renews every (months)",Offered,"Name (Italiano)","Name (Español)"'); + expect(lines.find((line) => line.includes(`,${code},`))).toMatch(new RegExp(`^"${name}",${code},[^,]+,,yes,`)); + expect(lines).toContainEqual(expect.stringMatching(/^"The Watchtower",w,/)); + }); + + test('imports publications from a CSV file', async ({ adminPage: page }, testInfo) => { + const suffix = uniqueCode('i'); + cleanUp(`\\App\\Models\\Publication::where('code', 'like', ${JSON.stringify(`imp-%-${suffix}`)})->get()->each->delete();`); + const file = testInfo.outputPath('publications.csv'); + writeFileSync(file, readFileSync('tests/e2e/fixtures/publications-import.csv', 'utf8').replaceAll('{suffix}', suffix)); + + await visit(page, '/app/publications'); + await uploadImport(page, 'Import Publications', file); + + await expect.poll(() => php(` + return \\App\\Models\\Publication::where('code', 'like', ${JSON.stringify(`imp-%-${suffix}`)})->orderBy('code')->get() + ->map(fn ($publication) => [ + 'code' => $publication->code, + 'category' => $publication->category->value, + 'renewal_months' => $publication->renewal_months, + 'is_active' => $publication->is_active, + 'name' => $publication->getTranslations('name'), + ])->all(); + `)).toEqual([ + { code: `imp-book-${suffix}`, category: 'books', renewal_months: null, is_active: true, name: { en: `Imported Book ${suffix}`, it: `Libro importato ${suffix}` } }, + { code: `imp-monthly-${suffix}`, category: 'watchtower', renewal_months: 1, is_active: false, name: { en: `Imported Monthly ${suffix}`, es: `Mensual importado ${suffix}` } }, + ]); + + await visit(page, '/app/publications'); + await searchTableUntilApplied(page, suffix); + await expect(row(page, `Imported Book ${suffix}`)).toBeVisible(); + await expect(row(page, `Imported Monthly ${suffix}`)).toContainText('every month'); + }); +}); + +test.describe('Publication requests', () => { + test('a new request moves from "to order" to "ordered" to "delivered"', async ({ adminPage: page }) => { + const publisher = createPublisher(); + const publication = uniqueName('Ordered book'); + createPublication({ name: publication }); + + await visit(page, '/app/publication-requests'); + await page.getByRole('button', { name: 'New request' }).click(); + await choosePublisher(modal(page), 'Publisher', publisher); + await chooseOption(modal(page), 'Publication', publication); + await field(modal(page), 'Copies').fill('3'); + await confirmModal(page, 'Create'); + await expectNotification(page, 'Created'); + + const statusOf = (): Record | null => php(`return \\App\\Models\\PublicationRequest::where('user_id', ${publisher.id})->first()?->only(['quantity', 'ordered_at', 'delivered_at']);`); + expect(statusOf()).toEqual({ quantity: 3, ordered_at: null, delivered_at: null }); + + await visit(page, requestsOf(publisher, 'to_order')); + await expect(row(page, publication)).toContainText('Requested'); + await rowAction(page, publication, 'Ordered'); + await expect(field(modal(page), 'Ordered on')).toHaveValue(/^\d{4}-\d{2}-\d{2}$/); + await confirmModal(page, 'Submit'); + await expectNotification(page, 'Marked as ordered'); + await expect(row(page, publication)).toHaveCount(0); + + await visit(page, requestsOf(publisher, 'ordered')); + await expect(row(page, publication)).toContainText('Ordered'); + expect(statusOf()?.ordered_at).not.toBeNull(); + await rowAction(page, publication, 'Delivered'); + await confirmModal(page, 'Submit'); + await expectNotification(page, 'Marked as delivered'); + await expect(row(page, publication)).toHaveCount(0); + + await visit(page, requestsOf(publisher, 'delivered')); + await expect(row(page, publication)).toContainText('Delivered'); + expect(statusOf()?.delivered_at).not.toBeNull(); + + await visit(page, requestsOf(publisher, 'all')); + await expect(row(page, publication)).toContainText('Delivered'); + }); + + test('marks the selected requests as ordered, then as delivered', async ({ adminPage: page }) => { + const publisher = createPublisher(); + const prefix = uniqueName('Bulk book'); + const publications = [`${prefix} A`, `${prefix} B`]; + const ids = publications.map((name) => createRequest({ user_id: publisher.id, publication_id: createPublication({ name }) })); + const steps = (): { ordered: boolean; delivered: boolean }[] => php(` + return \\App\\Models\\PublicationRequest::whereIn('id', ${JSON.stringify(ids)})->orderBy('id')->get() + ->map(fn ($request) => ['ordered' => $request->ordered_at !== null, 'delivered' => $request->delivered_at !== null])->all(); + `); + + await visit(page, requestsOf(publisher, 'to_order')); + await bulkMenuAction(page, publications, 'Ordered'); + await confirmModal(page, 'Submit'); + await expectNotification(page, 'Marked as ordered'); + await expect(page.getByText('No requests')).toBeVisible(); + expect(steps()).toEqual([{ ordered: true, delivered: false }, { ordered: true, delivered: false }]); + + await visit(page, requestsOf(publisher, 'ordered')); + await bulkMenuAction(page, publications, 'Delivered'); + await confirmModal(page, 'Submit'); + await expectNotification(page, 'Marked as delivered'); + await expect(page.getByText('No requests')).toBeVisible(); + expect(steps()).toEqual([{ ordered: true, delivered: true }, { ordered: true, delivered: true }]); + + await visit(page, requestsOf(publisher, 'delivered')); + await expect(row(page, publications[0])).toContainText('Delivered'); + await expect(row(page, publications[1])).toContainText('Delivered'); + }); + + test('filters the requests by publisher, publication and date', async ({ adminPage: page }) => { + const [first, second] = [createPublisher(), createPublisher()]; + const prefix = uniqueName('Filtered book'); + const [bookA, bookB] = [`${prefix} A`, `${prefix} B`]; + const [bookAId, bookBId] = [createPublication({ name: bookA }), createPublication({ name: bookB })]; + createRequest({ user_id: first.id, publication_id: bookAId, requested_at: '2025-03-15' }); + createRequest({ user_id: first.id, publication_id: bookBId }); + createRequest({ user_id: second.id, publication_id: bookAId }); + + await visit(page, '/app/publication-requests?tab=all'); + await searchTableUntilApplied(page, prefix); + await expect(page.locator('.fi-ta-row').filter({ hasText: prefix })).toHaveCount(3); + + await applyTableFilters(page, (panel) => choosePublisher(panel, 'Publisher', first)); + await expect(page.locator('.fi-ta-row').filter({ hasText: prefix })).toHaveCount(2); + await expect(row(page, second.name)).toHaveCount(0); + + await applyTableFilters(page, async (panel) => { + await field(panel, 'Requested from').fill('2025-03-01'); + await field(panel, 'Requested until').fill('2025-03-31'); + }); + await expect(page.locator('.fi-ta-row').filter({ hasText: prefix })).toHaveCount(1); + await expect(row(page, prefix)).toContainText(bookA); + await expect(row(page, prefix)).toContainText('15 Mar 2025'); + + await page.getByRole('button', { name: 'Filter', exact: true }).click(); + await page.locator('.fi-dropdown-panel').filter({ visible: true }).getByRole('button', { name: 'Reset' }).click(); + await settle(page); + await page.keyboard.press('Escape'); + await expect(page.locator('.fi-ta-row').filter({ hasText: prefix })).toHaveCount(3); + + await applyTableFilters(page, (panel) => chooseOption(panel, 'Publication', bookB)); + await expect(page.locator('.fi-ta-row').filter({ hasText: prefix })).toHaveCount(1); + await expect(row(page, prefix)).toContainText(first.name); + await expect(row(page, prefix)).toContainText(bookB); + }); + + test('shows the totals and the chart of the requests @mobile', async ({ adminPage: page }) => { + const toOrder = php('return \\App\\Models\\PublicationRequest::query()->toOrder()->count();'); + + await visit(page, '/app/publication-requests'); + + const stats = page.locator('.fi-wi-stats-overview-stat'); + await expect(stats).toHaveCount(3); + await expect(stats.nth(0)).toContainText('To order or retrieve'); + // Other tests may add requests meanwhile: at least the ones counted before opening the page + expect(Number((await stats.nth(0).locator('.fi-wi-stats-overview-stat-value').textContent())?.trim())).toBeGreaterThanOrEqual(toOrder); + await expect(stats.nth(0)).toContainText(/\d+ cop(y|ies)/); + await expect(stats.nth(1)).toContainText('Ordered'); + await expect(stats.nth(2)).toContainText('Delivered this month'); + await expect(page.getByRole('heading', { name: 'Requests over time' })).toBeVisible(); + await expect(page.getByRole('combobox', { name: 'Filter chart data' })).toHaveValue('all'); + await expect(page.locator('.fi-wi-chart canvas')).toBeVisible(); + }); +}); + +test.describe('Regular publications', () => { + test('adds a publisher receiving copies, reflected by the totals', async ({ adminPage: page }) => { + const publisher = createPublisher('Subscriber'); + const watchtowerId = publicationIdOf('w'); + + await visit(page, '/app/publication-subscribers'); + await page.getByRole('button', { name: 'Add publisher' }).click(); + await choosePublisher(modal(page), 'Publisher', publisher); + await modal(page).getByRole('button', { name: 'Add publication' }).click(); + const item = modal(page).getByRole('group', { name: 'Copies received' }).getByRole('row').filter({ has: page.getByRole('spinbutton') }); + await pickOption(page, item.locator('.fi-select-input-btn'), 'The Watchtower'); + await item.getByRole('spinbutton').fill('3'); + await confirmModal(page, 'Create'); + await expectNotification(page, 'Created'); + + expect(php(`return \\App\\Models\\PublicationSubscriber::where('user_id', ${publisher.id})->sole()->activeSubscriptions()->get(['publication_id', 'quantity'])->toArray();`)) + .toEqual([{ publication_id: watchtowerId, quantity: 3 }]); + + // The totals count the publishers shown by the table: only this one, once searched + await searchTableUntilApplied(page, publisher.name.split(' ').slice(0, 2).join(' ')); + await expect(page.locator('.fi-ta-row').filter({ has: page.getByRole('checkbox') })).toHaveCount(1); + await expect(row(page, publisher.name)).toContainText('3'); + const stats = page.locator('.fi-wi-stats-overview-stat'); + await expect(stats).toHaveCount(1); + await expect(stats.first()).toContainText('The Watchtower'); + await expect(stats.first().locator('.fi-wi-stats-overview-stat-value')).toHaveText('3'); + await expect(stats.first()).toContainText('1 publisher'); + }); + + test('opens the requests of a publisher', async ({ adminPage: page }) => { + const publisher = createPublisher('Subscriber'); + const watchtowerId = publicationIdOf('w'); + php(`\\App\\Models\\PublicationSubscriber::factory()->receiving(\\App\\Models\\Publication::find(${watchtowerId}), 2)->create(['user_id' => ${publisher.id}]); return true;`); + const book = uniqueName('Subscriber book'); + createRequest({ user_id: publisher.id, publication_id: createPublication({ name: book }), quantity: 2 }); + + await visit(page, '/app/publication-subscribers'); + await searchTableUntilApplied(page, publisher.name.split(' ').slice(0, 2).join(' ')); + await rowAction(page, publisher.name, 'Requests'); + + await expect(page).toHaveURL(new RegExp(`/app/publication-requests\\?.*tab=all.*user.*=${publisher.id}`)); + await expect(row(page, book)).toContainText(publisher.name); + }); + + test('removes a publisher from the list, keeping their history', async ({ adminPage: page }) => { + const publisher = createPublisher('Subscriber'); + const watchtowerId = publicationIdOf('w'); + php(`\\App\\Models\\PublicationSubscriber::factory()->receiving(\\App\\Models\\Publication::find(${watchtowerId}), 2)->create(['user_id' => ${publisher.id}]); return true;`); + + await visit(page, '/app/publication-subscribers'); + await searchTableUntilApplied(page, publisher.name.split(' ').slice(0, 2).join(' ')); + await rowAction(page, publisher.name, 'Remove'); + await expect(modal(page).getByRole('heading', { name: `Remove ${publisher.name} from the list` })).toBeVisible(); + await confirmModal(page, 'Confirm'); + await expectNotification(page, 'Removed from the list'); + + await expect(row(page, publisher.name)).toHaveCount(0); + expect(php(` + $subscriber = \\App\\Models\\PublicationSubscriber::where('user_id', ${publisher.id})->sole(); + + return [$subscriber->activeSubscriptions()->count(), $subscriber->subscriptions()->count()]; + `)).toEqual([0, 1]); + }); + + test('removes the selected publishers from the list', async ({ adminPage: page }) => { + const prefix = uniqueName('Bulksub'); + const publishers = [createPublisher(`${prefix} one`), createPublisher(`${prefix} two`)]; + const watchtowerId = publicationIdOf('w'); + + for (const publisher of publishers) { + php(`\\App\\Models\\PublicationSubscriber::factory()->receiving(\\App\\Models\\Publication::find(${watchtowerId}), 1)->create(['user_id' => ${publisher.id}]); return true;`); + } + + await visit(page, '/app/publication-subscribers'); + await searchTableUntilApplied(page, prefix); + await expect(page.locator('.fi-ta-row').filter({ hasText: prefix })).toHaveCount(2); + await expect(page.locator('.fi-wi-stats-overview-stat-value').first()).toHaveText('2'); + + await bulkMenuAction(page, publishers.map((publisher) => publisher.name), 'Remove'); + await confirmModal(page, 'Confirm'); + await expectNotification(page, 'Removed from the list'); + + await expect(page.locator('.fi-ta-row').filter({ hasText: prefix })).toHaveCount(0); + expect(php(`return \\App\\Models\\PublicationSubscription::query()->active()->whereHas('subscriber', fn ($query) => $query->whereIn('user_id', ${JSON.stringify(publishers.map((publisher) => publisher.id))}))->count();`)).toBe(0); + }); +}); diff --git a/tests/e2e/roles.spec.ts b/tests/e2e/roles.spec.ts new file mode 100644 index 00000000..6a3150d3 --- /dev/null +++ b/tests/e2e/roles.spec.ts @@ -0,0 +1,199 @@ +import type { Browser, Locator, Page } from '@playwright/test'; +import { appURL } from '../../playwright.config'; +import { test, expect, logIn, uniqueName } from './support/fixtures'; +import { php } from './support/artisan'; +import { confirmModal, expectNotification, field, labelled, modal, row, rowAction, searchTable, settle, visit } from './support/filament'; + +/** + * A name of role nobody else uses, in the `snake_case` of the seeded ones (shown as a headline, e.g. "E2e Reader Abc"). + */ +const uniqueRoleName = (): string => uniqueName('e2e reader').toLowerCase().replaceAll(' ', '_'); + +/** + * A throwaway user who can log in (with the password `password`), without a role. + */ +function createUser(): { id: number; email: string; firstName: string } { + const firstName = uniqueName('Roled'); + const email = `${firstName.toLowerCase().replaceAll(' ', '-')}@e2e.test`; + const id = php(` + return \\App\\Models\\User::factory()->verified()->create([ + 'first_name' => ${JSON.stringify(firstName)}, + 'last_name' => 'Tester', + 'email' => ${JSON.stringify(email)}, + 'locale' => 'en', + ])->id; + `); + + return { id, email, firstName }; +} + +/** + * Create a role with the permissions, in the database. + */ +function createRole(name: string, permissions: string[]): number { + return php(` + $role = \\Spatie\\Permission\\Models\\Role::create(['name' => ${JSON.stringify(name)}, 'guard_name' => 'web']); + $role->syncPermissions(${JSON.stringify(permissions)}); + + return $role->id; + `); +} + +/** + * The permissions of a role, sorted; `null` when the role does not exist. + */ +const permissionsOf = (name: string): string[] | null => php(` + $role = \\Spatie\\Permission\\Models\\Role::where('name', ${JSON.stringify(name)})->first(); + + return $role?->permissions->pluck('name')->sort()->values()->all(); +`); + +/** + * The group of checkboxes of the permissions of a resource, in the role form. + */ +const permissionsOfResource = (page: Page, resource: string): Locator => + page.getByRole('region', { name: resource, exact: true }).getByRole('group'); + +/** + * Sign in as the user in a browser context of their own. + */ +async function pageOf(browser: Browser, email: string): Promise { + const page = await (await browser.newContext({ baseURL: appURL })).newPage(); + await logIn(page, email, 'password'); + await expect(page).not.toHaveURL(/\/login/); + + return page; +} + +/** + * The HTTP status of a page for the user of the page (without following the redirects). + */ +async function statusOf(page: Page, url: string): Promise { + return (await page.context().request.get(url, { maxRedirects: 0 })).status(); +} + +const sidebarLink = (page: Page, name: string): Locator => + page.getByRole('navigation', { name: 'Sidebar navigation' }).getByRole('link', { name: new RegExp(`^${name}(\\s+\\d+)?$`) }); + +test.describe('Roles', () => { + test('create a role reading the territories, give it to a user, who sees only the territories', async ({ adminPage, browser }) => { + const roleName = uniqueRoleName(); + const user = createUser(); + + await visit(adminPage, '/app/shield/roles'); + await adminPage.getByRole('link', { name: 'New Role' }).click(); + await expect(adminPage.getByRole('heading', { name: 'Create Role', level: 1 })).toBeVisible(); + + await field(adminPage, 'Name').fill(roleName); + const territory = permissionsOfResource(adminPage, 'Territory'); + await territory.getByRole('checkbox', { name: 'View Any', exact: true }).check(); + await territory.getByRole('checkbox', { name: 'View', exact: true }).check(); + await adminPage.getByRole('button', { name: 'Create', exact: true }).click(); + await expectNotification(adminPage, 'Created'); + + expect(permissionsOf(roleName)).toEqual(['View:Territory', 'ViewAny:Territory']); + + await visit(adminPage, '/app/shield/roles'); + await searchTable(adminPage, roleName); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + await expect(adminPage.locator('.fi-ta-row').first()).toContainText('2'); + + // Give the role to the user from their page + await visit(adminPage, `/app/users/${user.id}/edit`); + await adminPage.locator('.fi-fo-field').filter({ has: adminPage.locator('label', { hasText: labelled('Roles') }) }).locator('.fi-select-input-btn').click(); + await adminPage.locator('.fi-select-input-search-ctn input').filter({ visible: true }).first().fill(roleName); + await adminPage.getByRole('option', { name: roleName }).filter({ visible: true }).first().click(); + await adminPage.keyboard.press('Escape'); + await adminPage.getByRole('button', { name: 'Save changes' }).click(); + await expectNotification(adminPage, 'Saved'); + expect(php(`return \\App\\Models\\User::find(${user.id})->getRoleNames()->all();`)).toEqual([roleName]); + + const userPage = await pageOf(browser, user.email); + await visit(userPage, '/app'); + await expect(sidebarLink(userPage, 'Territories')).toBeVisible(); + for (const item of ['Users', 'Zones', 'Campaigns', 'Assignments', 'Roles']) { + await expect(sidebarLink(userPage, item), item).toHaveCount(0); + } + + await visit(userPage, '/app/territories'); + await expect(userPage.getByRole('heading', { name: 'Territories', level: 1 })).toBeVisible(); + await expect(userPage.locator('.fi-header').getByRole('link', { name: 'New territory' })).toHaveCount(0); + + expect(await statusOf(userPage, '/app/users')).toBe(403); + expect(await statusOf(userPage, '/app/territories/create')).toBe(403); + + await userPage.context().close(); + }); + + test('editing the permissions of a role changes what its users reach', async ({ adminPage, browser }) => { + const roleName = uniqueRoleName(); + const roleId = createRole(roleName, ['ViewAny:Territory', 'View:Territory']); + const user = createUser(); + php(`\\App\\Models\\User::find(${user.id})->assignRole(${JSON.stringify(roleName)}); return null;`); + + const userPage = await pageOf(browser, user.email); + expect(await statusOf(userPage, '/app/users')).toBe(403); + + await visit(adminPage, `/app/shield/roles/${roleId}/edit`); + const territory = permissionsOfResource(adminPage, 'Territory'); + await expect(territory.getByRole('checkbox', { name: 'View Any', exact: true })).toBeChecked(); + await expect(territory.getByRole('checkbox', { name: 'Create', exact: true })).not.toBeChecked(); + + // Read the users, no longer the territories + const users = permissionsOfResource(adminPage, 'User'); + await users.getByRole('checkbox', { name: 'View Any', exact: true }).check(); + await users.getByRole('checkbox', { name: 'View', exact: true }).check(); + await territory.getByRole('checkbox', { name: 'View Any', exact: true }).uncheck(); + await territory.getByRole('checkbox', { name: 'View', exact: true }).uncheck(); + await adminPage.getByRole('button', { name: 'Save changes' }).click(); + await expectNotification(adminPage, 'Saved'); + + expect(permissionsOf(roleName)).toEqual(['View:User', 'ViewAny:User']); + + await visit(userPage, '/app'); + await expect(sidebarLink(userPage, 'Users')).toBeVisible(); + await expect(sidebarLink(userPage, 'Territories')).toHaveCount(0); + expect(await statusOf(userPage, '/app/users')).toBe(200); + expect(await statusOf(userPage, '/app/territories')).toBe(403); + + await userPage.context().close(); + }); + + test('delete a role, whose users lose its permissions', async ({ adminPage, browser }) => { + const roleName = uniqueRoleName(); + createRole(roleName, ['ViewAny:Territory', 'View:Territory']); + const user = createUser(); + php(`\\App\\Models\\User::find(${user.id})->assignRole(${JSON.stringify(roleName)}); return null;`); + + await visit(adminPage, '/app/shield/roles'); + await searchTable(adminPage, roleName); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + const roleRow = (await adminPage.locator('.fi-ta-row').first().innerText()).split('\n')[0].trim(); + await rowAction(adminPage, roleRow, 'Delete'); + await confirmModal(adminPage, 'Delete'); + await expectNotification(adminPage, 'Deleted'); + await settle(adminPage); + + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(0); + expect(permissionsOf(roleName)).toBeNull(); + expect(php(`return \\App\\Models\\User::find(${user.id})->getRoleNames()->all();`)).toEqual([]); + + const userPage = await pageOf(browser, user.email); + expect(await statusOf(userPage, '/app/territories')).toBe(403); + await userPage.context().close(); + }); + + test('the super admin role cannot be deleted', async ({ adminPage }) => { + await visit(adminPage, '/app/shield/roles'); + + const superAdmin = row(adminPage, 'Super Admin'); + await expect(superAdmin.getByRole('link', { name: 'Edit' })).toBeVisible(); + await expect(superAdmin.getByRole('button', { name: 'Delete' })).toHaveCount(0); + await expect(superAdmin.getByRole('checkbox')).toHaveCount(0); + + await superAdmin.getByRole('link', { name: 'Edit' }).click(); + await expect(adminPage.getByRole('heading', { name: /^Edit/, level: 1 })).toBeVisible(); + await expect(adminPage.locator('.fi-header').getByRole('button', { name: 'Delete' })).toHaveCount(0); + await expect(modal(adminPage)).toHaveCount(0); + }); +}); diff --git a/tests/e2e/root-user.spec.ts b/tests/e2e/root-user.spec.ts new file mode 100644 index 00000000..89486a72 --- /dev/null +++ b/tests/e2e/root-user.spec.ts @@ -0,0 +1,60 @@ +import { php } from './support/artisan'; +import { expect, pageAs, test, users } from './support/fixtures'; +import { visit } from './support/filament'; + +/** + * The root user (the first one, created by `och:install`), whose account is protected outside production, so that the + * demos and the previews always keep a way in. Nothing is changed here: the handover of the role is possible only in + * production (see `RootUserTransferTest`). + */ +const adminId = (): number => php(`return \\App\\Models\\User::where('email', '${users.admin.email}')->value('id');`); + +test.describe('root user', () => { + test('the other administrators cannot edit the root user', async ({ adminPage }) => { + await visit(adminPage, '/app/users/1'); + await expect(adminPage.getByRole('heading', { name: `View ${users.root.name}` })).toBeVisible(); + + // The edit button is there, disabled, and the edit page is refused + await expect(adminPage.getByRole('link', { name: 'Edit' })).toHaveCount(0); + await expect(adminPage.locator('.fi-header').getByText('Edit')).toBeVisible(); + await expect(adminPage.getByRole('button', { name: 'Impersonate' })).toHaveCount(0); + await expect(adminPage.getByRole('button', { name: 'Delete' })).toHaveCount(0); + + const response = await adminPage.goto('/app/users/1/edit'); + expect(response?.status()).toBe(403); + }); + + test('the root user can edit itself, but not its protected fields', async ({ browser }) => { + const root = await pageAs(browser, 'root'); + + await visit(root, '/app/users/1'); + await root.locator('.fi-header').getByRole('link', { name: 'Edit' }).click(); + await expect(root).toHaveURL(/\/app\/users\/1\/edit$/); + + await visit(root, '/app/edit-profile'); + await expect(root.getByText('Password changes are not allowed for the root user in non-production environments.')).toBeVisible(); + await expect(root.getByText('The root user cannot be deleted under any circumstances.')).toBeVisible(); + + await root.context().close(); + }); + + test('the role of root user can be handed over only in production', async ({ browser }) => { + const root = await pageAs(browser, 'root'); + + await visit(root, `/app/users/${adminId()}`); + const handOver = root.getByRole('button', { name: 'Make root user' }); + await expect(handOver).toBeDisabled(); + + await handOver.hover({ force: true }); + await expect(root.getByText('The root user can be changed only in production: on demos and previews it stays the first user.')).toBeVisible(); + + await root.context().close(); + }); + + test('only the root user is offered to hand the role over', async ({ adminPage }) => { + await visit(adminPage, `/app/users/${php(`return \\App\\Models\\User::where('email', '${users.servant.email}')->value('id');`)}`); + + await expect(adminPage.getByRole('heading', { name: `View ${users.servant.name}` })).toBeVisible(); + await expect(adminPage.getByRole('button', { name: 'Make root user' })).toHaveCount(0); + }); +}); diff --git a/tests/e2e/setup-wizard.spec.ts b/tests/e2e/setup-wizard.spec.ts new file mode 100644 index 00000000..65ead4be --- /dev/null +++ b/tests/e2e/setup-wizard.spec.ts @@ -0,0 +1,178 @@ +import path from 'node:path'; +import { expect, type Page, test } from '@playwright/test'; +import { artisan, php } from './support/artisan'; +import { useOwnAddress } from './support/fixtures'; +import { choose, field, settle } from './support/filament'; + +/** + * The setup wizard, on the `setup` instance: an empty installation (without a database configured) that the wizard + * installs, with the database of the run (`E2E_DB_CONNECTION`, see `serve.sh`). + * + * The installation can only be done once: the tests run in order, and the last ones check the installed application. + */ +test.describe.configure({ mode: 'serial' }); + +const token = 'e2e-setup-token'; +const root = { firstName: 'Wizard', lastName: 'Root', email: 'wizard-root@e2e.test', password: 'WizardPassword123' }; +const administrator = { firstName: 'Second', lastName: 'Admin', email: 'second-admin@e2e.test' }; +const congregation = 'E2E Wizard Congregation'; + +const connection = process.env.E2E_DB_CONNECTION ?? 'sqlite'; +const connectionNames: Record = { sqlite: 'SQLite', mysql: 'MySQL', mariadb: 'MariaDB', pgsql: 'PostgreSQL' }; + +/** + * The database the wizard configures: the one of the instance (see `serve.sh`). + */ +const database = connection === 'sqlite' + ? { database: path.resolve('storage/e2e/setup/database.sqlite') } + : { + database: 'e2e_setup', + host: process.env.E2E_DB_HOST ?? '127.0.0.1', + port: process.env.E2E_DB_PORT ?? (connection === 'pgsql' ? '5432' : '3306'), + username: process.env.E2E_DB_USERNAME ?? 'root', + password: process.env.E2E_DB_PASSWORD ?? '', + }; + +const step = (page: Page, name: string) => page.getByRole('group', { name: new RegExp(`^${name} Step`) }); + +async function next(page: Page): Promise { + await page.getByRole('button', { name: 'Next', exact: true }).filter({ visible: true }).click(); + await settle(page); +} + +async function unlock(page: Page, value: string = token): Promise { + await page.goto('/setup'); + await settle(page); + await field(page, 'Setup token').fill(value); + await page.getByRole('button', { name: 'Continue' }).click(); + await settle(page); +} + +test.beforeEach(async ({ page }) => { + // The token is rate limited by address + await useOwnAddress(page); +}); + +test('every page opens the wizard while the app is not installed', async ({ page }) => { + for (const url of ['/', '/app', '/app/login', '/app/territories']) { + await page.goto(url); + await expect(page, url).toHaveURL(/\/setup$/); + } + + await expect(page.getByRole('heading', { name: 'Install the app' })).toBeVisible(); +}); + +test('the wizard stays locked with a wrong token', async ({ page }) => { + await unlock(page, 'not-the-token'); + + await expect(field(page, 'Setup token')).toBeVisible(); + await expect(page.getByText('The setup token is not correct.')).toBeVisible(); + await expect(page.getByRole('button', { name: /Step 1 of 9/ })).toHaveCount(0); +}); + +test('the wizard installs the app step by step', async ({ page }) => { + await unlock(page); + + // 1. Requirements + await expect(step(page, 'Server')).toContainText('PHP version'); + await next(page); + + // 2. Configuration: the database is the only missing part of `.env` + const configuration = step(page, 'Configuration'); + await expect(configuration).toBeVisible(); + await choose(configuration, 'DB_CONNECTION', connectionNames[connection]); + await settle(page); + await field(configuration, 'DB_DATABASE').fill(database.database); + + if (connection !== 'sqlite') { + await field(configuration, 'DB_HOST').fill(database.host!); + await field(configuration, 'DB_PORT').fill(database.port!); + await field(configuration, 'DB_USERNAME').fill(database.username!); + await field(configuration, 'DB_PASSWORD').fill(database.password!); + } + + await next(page); + + // 3. Background tasks + await expect(step(page, 'Background tasks')).toBeVisible(); + await next(page); + + // 4. Database: the tables are created + await expect(step(page, 'Database')).toBeVisible(); + await next(page); + + // 5. Root user + const rootStep = step(page, 'Root user'); + await field(rootStep, 'First Name').fill(root.firstName); + await field(rootStep, 'Last Name').fill(root.lastName); + await field(rootStep, 'Email').fill(root.email); + await field(rootStep, 'Password').fill(root.password); + await field(rootStep, 'Confirm the password').fill(root.password); + await next(page); + + // 6. Congregation + const congregationStep = step(page, 'Congregation'); + await expect(congregationStep).toBeVisible(); + await congregationStep.getByRole('textbox').first().fill(congregation); + await next(page); + + // 7. Administrators + const administratorsStep = step(page, 'Administrators'); + await expect(administratorsStep).toBeVisible(); + await administratorsStep.getByRole('button', { name: /add/i }).first().click(); + await field(administratorsStep, 'First Name').fill(administrator.firstName); + await field(administratorsStep, 'Last Name').fill(administrator.lastName); + await field(administratorsStep, 'Email').fill(administrator.email); + await next(page); + + // 8. Features + await expect(step(page, 'Features')).toBeVisible(); + await next(page); + + // 9. Review, then install + const review = step(page, 'Review'); + await expect(review).toContainText(root.email); + await expect(review).toContainText(congregation); + await page.getByRole('button', { name: 'Install', exact: true }).filter({ visible: true }).click(); + await settle(page); + + await expect(page.getByRole('heading', { name: 'The app is installed' })).toBeVisible({ timeout: 60_000 }); + await expect(page.getByText(`Root user created: ${root.email}`)).toBeVisible(); +}); + +test('the installed app has the root user, the congregation and the administrator', async () => { + const installed = php<{ root: string | null; superAdmin: boolean; name: string | null; admins: string[] }>(` + $root = \\App\\Models\\User::rootUser(); + + return [ + 'root' => $root?->email, + 'superAdmin' => (bool) $root?->hasRole('super_admin'), + 'name' => app(\\App\\Settings\\GeneralSettings::class)->app_name, + 'admins' => \\App\\Models\\User::role('super_admin')->pluck('email')->all(), + ]; + `, 'setup'); + + expect(installed.root).toBe(root.email); + expect(installed.superAdmin).toBe(true); + expect(installed.name).toBe(congregation); + expect(installed.admins).toContain(administrator.email); + expect(artisan(['migrate:status'], 'setup')).not.toContain('Pending'); +}); + +test('the root user logs in to the installed app', async ({ page }) => { + await page.goto('/app/login'); + await settle(page); + await field(page, 'Email address').fill(root.email); + await field(page, 'Password').fill(root.password); + await page.getByRole('button', { name: 'Sign in' }).click(); + + await expect(page).toHaveURL(/\/app\/?$/); + await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); + await expect(page.getByRole('link', { name: congregation }).first()).toBeVisible(); +}); + +test('the wizard is no longer available once installed', async ({ page }) => { + const response = await page.goto('/setup'); + + expect(response?.status()).toBe(403); +}); diff --git a/tests/e2e/sharing.spec.ts b/tests/e2e/sharing.spec.ts new file mode 100644 index 00000000..edbccdf6 --- /dev/null +++ b/tests/e2e/sharing.spec.ts @@ -0,0 +1,156 @@ +import type { Browser, Page } from '@playwright/test'; +import { appURL } from '../../playwright.config'; +import { php } from './support/artisan'; +import { confirmModal, expectNotification, headerMenuAction, modal, visit } from './support/filament'; +import { expect, test, uniqueName, users } from './support/fixtures'; + +/** + * Sharing an assignment through a public link (the `share` action of the assignment page), and the guest pages that + * the link opens (`app/Filament/Guest/Pages`). The e2e environment shares the personal data and lets the guests ask to + * return the territory (`ENABLE_SHARED_PII`, `GUEST_ALLOW_RETURNING_ASSIGNMENT`): the settings are never changed here. + */ + +test.describe.configure({ mode: 'parallel' }); + +/** + * Create a territory with a map, assigned to the publisher, returning the ids of the territory and of its assignment. + */ +function createAssignment(name: string): { territoryId: number; assignmentId: number } { + return php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(`${name} zone`)}, 'color' => '#3366cc']); + $territory = \\App\\Models\\Territory::factory()->withMap()->for($zone)->create(['name' => ${JSON.stringify(name)}, 'notes' => 'Shared notes']); + $assignment = $territory->assignments()->create([ + 'assignee_id' => \\App\\Models\\User::where('email', ${JSON.stringify(users.publisher.email)})->sole()->id, + 'started_at' => now()->subDays(2), + ]); + + return ['territoryId' => $territory->id, 'assignmentId' => $assignment->id]; + `); +} + +/** + * Share the assignment from its page, returning the URL of the link. + */ +async function shareAssignment(page: Page, assignmentId: number): Promise { + await visit(page, `/app/territory-assignments/${assignmentId}`); + await headerMenuAction(page, 'Actions', 'Share'); + + const shareModal = modal(page); + await expect(shareModal.getByRole('heading', { name: 'Share Assignment' })).toBeVisible(); + await expect(shareModal.getByText('This assignment is not shared yet')).toBeVisible(); + await shareModal.getByRole('button', { name: 'Create link' }).click(); + + const url = shareModal.getByRole('textbox', { name: 'Sharing URL' }); + await expect(url).toHaveValue(/\/share\/[0-9a-f-]{36}$/); + + return url.inputValue(); +} + +/** + * Open a page in a browser context of its own, signed in as nobody, on the device of the project (e.g. a phone). + */ +async function guestPage(browser: Browser): Promise { + const { viewport, userAgent, isMobile, hasTouch, deviceScaleFactor } = test.info().project.use; + const context = await browser.newContext({ baseURL: appURL, viewport, userAgent, isMobile, hasTouch, deviceScaleFactor }); + + return context.newPage(); +} + +const sharedUrlOf = (assignmentId: number): string | null => php(` + return \\App\\Models\\TerritoryAssignment::find(${assignmentId})->shared?->uid; +`); + +test.describe('Sharing an assignment', () => { + test('creates a link, copies it, and opens the shared page for guests', async ({ adminPage: page, browser }) => { + const name = uniqueName('Shared Territory'); + const { assignmentId } = createAssignment(name); + await page.context().grantPermissions(['clipboard-read', 'clipboard-write']); + + const url = await shareAssignment(page, assignmentId); + const uid = url.split('/share/')[1]; + expect(sharedUrlOf(assignmentId)).toBe(uid); + + await modal(page).getByRole('button', { name: 'Copy URL' }).click(); + await expectNotification(page, 'URL copied to clipboard'); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(url); + + const guest = await guestPage(browser); + await guest.goto(url); + await expect(guest).toHaveURL(new RegExp(`/guest/shared-assignment/${uid}$`)); + await expect(guest.getByRole('heading', { level: 1, name: `Assignment: ${name}` })).toBeVisible(); + await expect(guest.getByText(`${name} zone`)).toBeVisible(); + await expect(guest.getByText(users.publisher.name)).toBeVisible(); + await expect(guest.getByText('Shared notes')).toBeVisible(); + await expect(guest.locator('.leaflet-overlay-pane path').first()).toBeVisible(); + await guest.context().close(); + }); + + test('lets the guests ask to return the territory', async ({ adminPage: page, browser }) => { + const name = uniqueName('Returned Territory'); + const { assignmentId } = createAssignment(name); + const url = await shareAssignment(page, assignmentId); + + const guest = await guestPage(browser); + await guest.goto(url); + await guest.getByRole('button', { name: 'Ask to return' }).click(); + await expect(modal(guest).getByRole('heading', { name: 'Ask to return the territory?' })).toBeVisible(); + await confirmModal(guest, 'Ask to return'); + + await expectNotification(guest, 'Return requested'); + await expect(guest.getByRole('heading', { name: /Return requested on / })).toBeVisible(); + expect(php(`return \\App\\Models\\TerritoryAssignment::find(${assignmentId})->return_requested_at !== null;`)).toBe(true); + await guest.context().close(); + }); + + test('stops sharing: the link no longer opens', async ({ adminPage: page, browser }) => { + const name = uniqueName('Unshared Territory'); + const { assignmentId } = createAssignment(name); + const url = await shareAssignment(page, assignmentId); + const uid = url.split('/share/')[1]; + + // The modal shows the existing link when opened again + await visit(page, `/app/territory-assignments/${assignmentId}`); + await headerMenuAction(page, 'Actions', 'Share'); + await expect(modal(page).getByRole('textbox', { name: 'Sharing URL' })).toHaveValue(url); + await modal(page).getByRole('button', { name: 'Stop Sharing' }).click(); + await expect(modal(page).getByRole('heading', { name: 'Confirm Stop Sharing' })).toBeVisible(); + await confirmModal(page, 'Confirm'); + + await expectNotification(page, 'Sharing stopped successfully'); + expect(sharedUrlOf(assignmentId)).toBeNull(); + + const guest = await guestPage(browser); + expect((await guest.request.get(url, { maxRedirects: 0 })).status()).toBe(404); + expect((await guest.request.get(`/guest/shared-assignment/${uid}`)).status()).toBe(404); + await guest.context().close(); + }); + + test('shows the shared assignment on the generic shared resource page too', async ({ adminPage: page, browser }) => { + const name = uniqueName('Resource Territory'); + const { assignmentId } = createAssignment(name); + const uid = (await shareAssignment(page, assignmentId)).split('/share/')[1]; + + const guest = await guestPage(browser); + await guest.goto(`/guest/shared-resource/${uid}`); + await expect(guest.getByRole('heading', { level: 1, name: `Assignment: ${name}` })).toBeVisible(); + await expect(guest.getByText(users.publisher.name)).toBeVisible(); + await guest.context().close(); + }); + + test('opens the shared link of an assignment on a phone @mobile', async ({ adminPage: page, browser }) => { + const name = uniqueName('Phone Territory'); + const { assignmentId } = createAssignment(name); + const url = await shareAssignment(page, assignmentId); + await modal(page).getByRole('button', { name: 'Close' }).first().click(); + + await expect(page.getByText(name).first()).toBeVisible(); + await expect(page.getByText(users.publisher.name).first()).toBeVisible(); + + const guest = await guestPage(browser); + await guest.goto(url); + await expect(guest.getByRole('heading', { level: 1, name: `Assignment: ${name}` })).toBeVisible(); + await expect(guest.locator('.leaflet-overlay-pane path').first()).toBeVisible(); + await expect(guest.getByRole('button', { name: 'Ask to return' })).toBeVisible(); + await guest.context().close(); + }); +}); diff --git a/tests/e2e/support/artisan.ts b/tests/e2e/support/artisan.ts new file mode 100644 index 00000000..c5687c0a --- /dev/null +++ b/tests/e2e/support/artisan.ts @@ -0,0 +1,55 @@ +import { execFileSync } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('../../..', import.meta.url)); + +/** + * The environment of an instance served by `serve.sh`, so that the commands use its `.env`, storage and database. + */ +type Instance = 'app' | 'setup'; + +/** + * The directory name of an instance (the seeded one can be renamed with `E2E_APP_INSTANCE`, see `playwright.config.ts`). + */ +const nameOf = (instance: Instance): string => (instance === 'app' ? (process.env.E2E_APP_INSTANCE ?? 'app') : instance); + +const environmentOf = (instance: Instance): NodeJS.ProcessEnv => ({ + ...process.env, + APP_ENV: `e2e-${nameOf(instance)}`, + LARAVEL_STORAGE_PATH: path.join(root, 'storage', 'e2e', nameOf(instance)), + // Its own caches, as in `serve.sh`: a cached development configuration would skip its `.env` + APP_CONFIG_CACHE: path.join(root, 'storage', 'e2e', nameOf(instance), 'framework', 'cache', 'config.php'), + APP_ROUTES_CACHE: path.join(root, 'storage', 'e2e', nameOf(instance), 'framework', 'cache', 'routes.php'), + APP_EVENTS_CACHE: path.join(root, 'storage', 'e2e', nameOf(instance), 'framework', 'cache', 'events.php'), +}); + +/** + * Run an Artisan command on an instance of the application, returning its output. + */ +export function artisan(args: string[], instance: Instance = 'app'): string { + try { + return execFileSync('php', ['artisan', ...args, '--no-interaction'], { + cwd: root, + env: environmentOf(instance), + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + } catch (error) { + const { stdout, stderr } = error as { stdout?: string; stderr?: string }; + + throw new Error(`php artisan ${args[0]} failed:\n${[stdout, stderr].filter(Boolean).join('\n').trim()}`); + } +} + +/** + * Run PHP code in the application (through Tinker) and return what it prints as JSON: e.g. to arrange data, or to + * read what the pages don't show (a link sent by email). + */ +export function php(code: string, instance: Instance = 'app'): T { + const marker = '__E2E_RESULT__'; + const output = artisan(['tinker', '--execute', `echo '${marker}'.json_encode((function () { ${code} })());`], instance); + const json = output.slice(output.lastIndexOf(marker) + marker.length).trim(); + + return JSON.parse(json) as T; +} diff --git a/tests/e2e/support/filament.ts b/tests/e2e/support/filament.ts new file mode 100644 index 00000000..e3678b15 --- /dev/null +++ b/tests/e2e/support/filament.ts @@ -0,0 +1,307 @@ +import { expect, type Locator, type Page } from '@playwright/test'; + +const escapeRegExp = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** + * The accessible name of a Filament field: its label, followed by `*` when it is required. + */ +export const labelled = (label: string): RegExp => new RegExp(`^\\s*${escapeRegExp(label)}\\s*\\*?\\s*$`); + +/** + * A field of a form, found by its exact label. + */ +export const field = (scope: Page | Locator, label: string): Locator => scope.getByLabel(labelled(label)); + +/** + * Wait until Livewire has handled the requests in progress (e.g. after typing in a live field). + */ +export async function settle(page: Page): Promise { + await page.waitForLoadState('networkidle'); +} + +/** + * Choose an option of a Filament select, either native or searchable (Choices.js style). + */ +export async function choose(scope: Page | Locator, label: string, option: string): Promise { + const page = 'page' in scope ? scope.page() : scope; + const select = field(scope, label); + + if ((await select.evaluate((element) => element.tagName)) === 'SELECT') { + await select.selectOption({ label: option }); + + return; + } + + await select.click(); + + const search = page.locator('.fi-select-input-search-ctn input, .choices__input--cloned').filter({ visible: true }).first(); + + if (await search.count()) { + await search.fill(option); + } + + await page.getByRole('option', { name: option, exact: false }).filter({ visible: true }).first().click(); +} + +/** + * The modal currently open. + */ +export const modal = (page: Page): Locator => page.locator('.fi-modal-window').filter({ visible: true }).last(); + +/** + * The row of the table that contains the text. + */ +export const row = (page: Page, text: string): Locator => + page.locator('.fi-ta-row').filter({ hasText: text }).first(); + +/** + * Search a Filament table. + */ +export async function searchTable(page: Page, text: string): Promise { + const search = page.getByRole('searchbox', { name: /search/i }).filter({ visible: true }).last(); + await search.fill(text); + await settle(page); +} + +/** + * Click an action of a table row: a visible button or link, or one hidden in the row's action group. + */ +export async function rowAction(page: Page, rowText: string, action: string | RegExp): Promise { + const tableRow = row(page, rowText); + const name = typeof action === 'string' ? new RegExp(`^\\s*${escapeRegExp(action)}\\s*$`, 'i') : action; + const direct = tableRow.getByRole('button', { name }).or(tableRow.getByRole('link', { name })).first(); + + if (await direct.isVisible()) { + await direct.click(); + + return; + } + + await tableRow.getByRole('button', { name: /actions/i }).last().click(); + await page.locator('.fi-dropdown-panel').filter({ visible: true }).getByRole('button', { name }).or( + page.locator('.fi-dropdown-panel').filter({ visible: true }).getByRole('link', { name }), + ).first().click(); +} + +/** + * Click a header action of the page, opening the action group of the header when it is hidden there. + */ +export async function headerAction(page: Page, action: string | RegExp): Promise { + const name = typeof action === 'string' ? new RegExp(`^\\s*${escapeRegExp(action)}\\s*$`, 'i') : action; + const header = page.locator('.fi-header'); + const direct = header.getByRole('button', { name }).or(header.getByRole('link', { name })).first(); + + if (await direct.isVisible()) { + await direct.click(); + + return; + } + + await header.getByRole('button', { name: /actions/i }).last().click(); + const panel = page.locator('.fi-dropdown-panel').filter({ visible: true }); + await panel.getByRole('button', { name }).or(panel.getByRole('link', { name })).first().click(); +} + +/** + * Select the rows of a table, then run one of its bulk actions. + */ +export async function bulkAction(page: Page, rowTexts: string[], action: string | RegExp): Promise { + for (const text of rowTexts) { + await row(page, text).getByRole('checkbox').first().check(); + } + + const name = typeof action === 'string' ? new RegExp(`^\\s*${escapeRegExp(action)}\\s*$`, 'i') : action; + const toolbar = page.locator('.fi-ta-header-toolbar, .fi-ta-selection-indicator'); + const direct = toolbar.getByRole('button', { name }).first(); + + if (await direct.isVisible()) { + await direct.click(); + + return; + } + + await page.getByRole('button', { name: /bulk actions/i }).filter({ visible: true }).first().click(); + await page.locator('.fi-dropdown-panel').filter({ visible: true }).getByRole('button', { name }).first().click(); +} + +/** + * Submit the open modal with its primary (or the named) button. + */ +export async function confirmModal(page: Page, button: string | RegExp = /confirm|submit|save|create|delete|yes|send/i): Promise { + const name = typeof button === 'string' ? new RegExp(`^\\s*${escapeRegExp(button)}\\s*$`, 'i') : button; + await modal(page).locator('.fi-modal-footer').getByRole('button', { name }).first().click(); +} + +/** + * Expect a notification (toast) with the text. + */ +export async function expectNotification(page: Page, text: string | RegExp): Promise { + await expect(page.locator('.fi-no-notification').filter({ hasText: text }).first()).toBeVisible(); +} + +/** + * Open a page and wait for Livewire to load it. + */ +export async function visit(page: Page, url: string): Promise { + await page.goto(url); + await settle(page); +} + +/** + * An item of the dropdown menu open on the page (an action group, the bulk actions): Filament renders them as menu + * items, not as buttons. + */ +export const menuItem = (page: Page, name: string | RegExp): Locator => { + const pattern = typeof name === 'string' ? new RegExp(`^\\s*${escapeRegExp(name)}\\s*$`, 'i') : name; + const panel = page.locator('.fi-dropdown-panel').filter({ visible: true }); + + return panel.getByRole('menuitem', { name: pattern }) + .or(panel.getByRole('button', { name: pattern })) + .or(panel.getByRole('link', { name: pattern })) + .first(); +}; + +/** + * Click an action of the action group ("Actions" menu) of a table row. + */ +export async function rowMenuAction(page: Page, rowText: string, action: string | RegExp): Promise { + await row(page, rowText).getByRole('button', { name: /^\s*actions\s*$/i }).last().click(); + await menuItem(page, action).click(); +} + +/** + * Click an action of a named action group of the page header (e.g. "Import / Export"). + */ +export async function headerMenuAction(page: Page, group: string | RegExp, action: string | RegExp): Promise { + const name = typeof group === 'string' ? new RegExp(`^\\s*${escapeRegExp(group)}\\s*$`, 'i') : group; + await page.locator('.fi-header').getByRole('button', { name }).first().click(); + await menuItem(page, action).click(); +} + +/** + * Select the rows of a table, then run one of the actions of its "Bulk actions" menu. + */ +export async function bulkMenuAction(page: Page, rowTexts: string[], action: string | RegExp): Promise { + for (const text of rowTexts) { + await row(page, text).getByRole('checkbox').first().check(); + } + + await page.getByRole('button', { name: /^\s*bulk actions\s*$/i }).filter({ visible: true }).first().click(); + await menuItem(page, action).click(); +} + +/** + * Choose an option of a Filament select by its exact label: a native select, or a searchable one, whose label also + * names its list of options (which makes `choose()` find two elements). The options are searched first, since a + * preloaded list may not hold them all: by the whole label, else by its first word. + */ +export async function chooseOption(scope: Page | Locator, label: string, option: string): Promise { + const page = 'page' in scope ? scope.page() : scope; + const trigger = scope.getByRole('combobox', { name: labelled(label) }) + .or(scope.getByRole('button', { name: labelled(label) })) + .first(); + + if ((await trigger.evaluate((element) => element.tagName)) === 'SELECT') { + await trigger.selectOption({ label: option }); + + return; + } + + await trigger.click(); + + const search = page.locator('.fi-select-input-search-ctn input').filter({ visible: true }).first(); + const choice = page.getByRole('listbox').filter({ visible: true }).getByRole('option', { name: option, exact: true }).first(); + + if (await search.count()) { + await search.fill(option); + + // A select searching each column apart (e.g. first and last name) finds nothing for the whole label + const found = await choice.waitFor({ state: 'visible', timeout: 5_000 }).then(() => true, () => false); + + if (!found) { + await search.fill(option.split(/\s+/)[0]); + } + } + + await choice.click(); +} + +/** + * Run an export from the "Import / Export" menu of the page header (e.g. "Export Posters") with the default options, + * then download the CSV file linked by the notification (the queue is synchronous): its name and its rows (without the + * byte order mark). + */ +export async function downloadExport(page: Page, action: string): Promise<{ fileName: string; lines: string[] }> { + await headerMenuAction(page, 'Import / Export', action); + await expect(modal(page).getByRole('heading', { name: action })).toBeVisible(); + await confirmModal(page, 'Export'); + + const link = page.locator('.fi-no-notification').getByRole('link', { name: /\.csv/ }).first(); + const [download] = await Promise.all([page.waitForEvent('download'), link.click()]); + const { readFile } = await import('node:fs/promises'); + const csv = (await readFile(await download.path(), 'utf8')).replace(/^/, ''); + + return { fileName: download.suggestedFilename(), lines: csv.trim().split(/\r?\n/) }; +} + +/** + * Run an import from the "Import / Export" menu of the page header (e.g. "Import Posters") with a CSV file, its columns + * matched by their headers. The queue is synchronous: the rows are imported once this returns, or soon after. + */ +export async function uploadImport(page: Page, action: string, file: string): Promise { + await headerMenuAction(page, 'Import / Export', action); + await expect(modal(page).getByRole('heading', { name: action })).toBeVisible(); + await expect(modal(page).getByText('Upload a CSV file')).toBeVisible(); + await modal(page).locator('input[type=file]').setInputFiles(file); + + // Enabled once the file is uploaded and its columns are matched + const button = modal(page).locator('.fi-modal-footer').getByRole('button', { name: 'Import', exact: true }); + await expect(modal(page).getByRole('group', { name: 'Columns' })).toBeVisible({ timeout: 30_000 }); + await expect(button).toBeEnabled({ timeout: 30_000 }); + await button.click(); + await expect(modal(page).getByRole('heading', { name: action })).toBeHidden(); + await settle(page); +} + +/** + * Open the filters of the table, set them with the callback, apply them and close the panel. Choosing an option of a + * searchable select, whose list is outside the panel, may close the panel and apply them already. + */ +export async function applyTableFilters(page: Page, setFilters: (panel: Locator) => Promise): Promise { + const panel = page.locator('.fi-dropdown-panel').filter({ visible: true }).filter({ has: page.locator('.fi-ta-filters-heading') }).first(); + + await page.getByRole('button', { name: 'Filter', exact: true }).click(); + await expect(panel).toBeVisible(); + await setFilters(panel); + await settle(page); + + if (await panel.isVisible()) { + // The list of a multiple select stays open over the button + if (await panel.getByRole('listbox').filter({ visible: true }).count()) { + await panel.locator('.fi-ta-filters-heading').click(); + } + + await panel.getByRole('button', { name: 'Apply filters' }).click(); + } + + await settle(page); + + // Closed, so that the next call opens it again + if (await panel.isVisible()) { + await page.keyboard.press('Escape'); + } + + await expect(panel).toBeHidden(); +} + +/** + * Search a Filament table and wait until the search is applied (shown among its active filters): typed while the + * page is still loading, a search can be lost, and the rows of before can look like its results. + */ +export async function searchTableUntilApplied(page: Page, text: string): Promise { + await expect(async () => { + await searchTable(page, text); + await expect(page.getByText(`Search: ${text}`, { exact: true }).first()).toBeVisible({ timeout: 3_000 }); + }).toPass({ timeout: 30_000 }); + await settle(page); +} diff --git a/tests/e2e/support/fixtures.ts b/tests/e2e/support/fixtures.ts new file mode 100644 index 00000000..f6519dbb --- /dev/null +++ b/tests/e2e/support/fixtures.ts @@ -0,0 +1,74 @@ +import { test as base, expect, type Browser, type Page } from '@playwright/test'; +import { appURL } from '../../../playwright.config'; +import { field } from './filament'; +import { type Role, storageStateOf, users } from './users'; + +let counter = 0; + +/** + * A name nobody else uses, so that the tests running in parallel on the same database never see each other's + * records. + */ +export const uniqueName = (prefix: string): string => + `${prefix} ${Date.now().toString(36)}${(counter++).toString(36)}${Math.floor(Math.random() * 1296).toString(36)}`; + +/** + * Open a page signed in as a user of a role (in a browser context of its own). + */ +export async function pageAs(browser: Browser, role: Role): Promise { + const context = await browser.newContext({ baseURL: appURL, storageState: storageStateOf(role) }); + + return context.newPage(); +} + +/** + * Make the requests of the page come from an address of their own (the application trusts the forwarded headers of + * the tests, see `serve.sh`): the sign-ins are rate limited by address, and every test signs in from 127.0.0.1. + */ +export async function useOwnAddress(page: Page, address?: string): Promise { + const ip = address ?? `10.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${1 + Math.floor(Math.random() * 254)}`; + await page.context().setExtraHTTPHeaders({ 'X-Forwarded-For': ip }); + + return ip; +} + +/** + * Sign in through the login form. + */ +export async function logIn(page: Page, email: string, password: string): Promise { + await useOwnAddress(page); + await page.goto('/app/login'); + await page.waitForLoadState('networkidle'); + await field(page, 'Email address').fill(email); + await field(page, 'Password').fill(password); + await page.getByRole('button', { name: 'Sign in' }).click(); +} + +type Fixtures = { + /** The page of a signed-in super administrator (not the root user). */ + adminPage: Page; + /** The page of the territory servant. */ + servantPage: Page; + /** The page of a publisher. */ + publisherPage: Page; +}; + +export const test = base.extend({ + adminPage: async ({ browser }, use) => { + const page = await pageAs(browser, 'admin'); + await use(page); + await page.context().close(); + }, + servantPage: async ({ browser }, use) => { + const page = await pageAs(browser, 'servant'); + await use(page); + await page.context().close(); + }, + publisherPage: async ({ browser }, use) => { + const page = await pageAs(browser, 'publisher'); + await use(page); + await page.context().close(); + }, +}); + +export { expect, users }; diff --git a/tests/e2e/support/mail.ts b/tests/e2e/support/mail.ts new file mode 100644 index 00000000..2ec5fde3 --- /dev/null +++ b/tests/e2e/support/mail.ts @@ -0,0 +1,65 @@ +import { php } from './artisan'; + +/** + * The last email sent to an address (kept by the mail log of the application), with the links it contains; only among + * the emails with the subject when given one, since other emails may reach the address meanwhile (e.g. the + * announcement of a campaign created by another test). + */ +export function lastMailTo(email: string, subject?: string): { subject: string; body: string; links: string[] } | null { + const mail = php<{ subject: string; body: string } | null>(` + $log = \\Tapp\\FilamentMailLog\\Models\\MailLog::query() + ->where('to', 'like', '%' . ${JSON.stringify(email)} . '%') + ${subject === undefined ? '' : `->where('subject', ${JSON.stringify(subject)})`} + ->latest('id') + ->first(); + + return $log ? ['subject' => $log->subject, 'body' => (string) $log->body] : null; + `); + + if (mail === null) { + return null; + } + + const links = [...mail.body.matchAll(/href="([^"]+)"/g)].map((match) => match[1].replaceAll('&', '&')); + + return { ...mail, links: [...new Set(links)] }; +} + +/** + * The link matching the pattern in the newest email sent to an address that has one (see `linkInMailsTo()`). + */ +export function linkInLastMailTo(email: string, pattern: RegExp): string { + const link = linkInMailsTo(email, pattern); + + if (!link) { + throw new Error(`No link matching ${pattern} in the emails sent to ${email}.`); + } + + return link; +} + +/** + * The link matching the pattern in the newest email sent to an address that has one, or `null`: other emails may + * have reached the address since (e.g. the announcement of a campaign created by another test). + */ +export function linkInMailsTo(email: string, pattern: RegExp): string | null { + const bodies = php(` + return \\Tapp\\FilamentMailLog\\Models\\MailLog::query() + ->where('to', 'like', '%' . ${JSON.stringify(email)} . '%') + ->latest('id') + ->limit(20) + ->pluck('body') + ->map(fn ($body) => (string) $body) + ->all(); + `); + + for (const body of bodies) { + const link = [...body.matchAll(/href="([^"]+)"/g)].map((match) => match[1].replaceAll('&', '&')).find((url) => pattern.test(url)); + + if (link) { + return link; + } + } + + return null; +} diff --git a/tests/e2e/support/serve.sh b/tests/e2e/support/serve.sh new file mode 100755 index 00000000..ee5176f9 --- /dev/null +++ b/tests/e2e/support/serve.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# +# Prepare an isolated instance of the application and serve it, for the end-to-end tests (see `playwright.config.ts`). +# +# tests/e2e/support/serve.sh +# +# `setup` is left empty, for the setup wizard; any other instance (`app`) is installed and seeded with `E2eSeeder`. Each +# instance has its own `.env.e2e-` (picked by `APP_ENV`), storage directory and database, so that it never +# touches the `.env`, storage and database of development. +# +# The database comes from `E2E_DB_CONNECTION` (`sqlite`, the default, `mysql`, `mariadb` or `pgsql`) and, except for +# SQLite, `E2E_DB_HOST`, `E2E_DB_PORT`, `E2E_DB_USERNAME` and `E2E_DB_PASSWORD`: the database `e2e_` is +# created when missing. + +set -euo pipefail + +instance="${1:?Usage: serve.sh }" +port="${2:?Usage: serve.sh }" + +cd "$(dirname "$0")/../../.." + +export APP_ENV="e2e-${instance}" +export LARAVEL_STORAGE_PATH="${PWD}/storage/e2e/${instance}" +# The caches of the configuration, routes and events of the instance, in its storage (emptied below): a cache of the +# development one (`php artisan config:cache` or `optimize`) would make Laravel skip `.env.e2e-`, and reach +# the development database +export APP_CONFIG_CACHE="${LARAVEL_STORAGE_PATH}/framework/cache/config.php" +export APP_ROUTES_CACHE="${LARAVEL_STORAGE_PATH}/framework/cache/routes.php" +export APP_EVENTS_CACHE="${LARAVEL_STORAGE_PATH}/framework/cache/events.php" + +connection="${E2E_DB_CONNECTION:-sqlite}" +env_file=".env.${APP_ENV}" + +rm -rf "${LARAVEL_STORAGE_PATH}" +mkdir -p "${LARAVEL_STORAGE_PATH}"/{app/public,framework/{cache/data,sessions,testing,views},logs} + +if [[ "${connection}" == "sqlite" ]]; then + database="${LARAVEL_STORAGE_PATH}/database.sqlite" + touch "${database}" + # Many requests write at once (parallel tests, several server workers): they wait for each other + db_variables="DB_CONNECTION=sqlite +DB_DATABASE=\"${database}\" +DB_BUSY_TIMEOUT=15000 +DB_JOURNAL_MODE=wal" +else + database="e2e_${instance}" + db_variables="DB_CONNECTION=${connection} +DB_HOST=${E2E_DB_HOST:-127.0.0.1} +DB_PORT=${E2E_DB_PORT:-$([[ "${connection}" == "pgsql" ]] && echo 5432 || echo 3306)} +DB_DATABASE=${database} +DB_USERNAME=${E2E_DB_USERNAME:-root} +DB_PASSWORD=\"${E2E_DB_PASSWORD:-}\"" +fi + +# The setup wizard asks for the database itself: its instance starts without one +if [[ "${instance}" == "setup" ]]; then + db_variables="" +fi + +cat > "${env_file}" < /dev/null + +if [[ "${connection}" != "sqlite" ]]; then + # A database of its own, emptied at every start + php -r ' + [$driver, $host, $port, $user, $password, $name] = array_slice($argv, 1); + $pdo = new PDO($driver === "pgsql" ? "pgsql:host=$host;port=$port;dbname=postgres" : "mysql:host=$host;port=$port", $user, $password); + $pdo->exec("DROP DATABASE IF EXISTS $name"); + $pdo->exec("CREATE DATABASE $name"); + ' "${connection}" "${E2E_DB_HOST:-127.0.0.1}" "${E2E_DB_PORT:-$([[ "${connection}" == "pgsql" ]] && echo 5432 || echo 3306)}" \ + "${E2E_DB_USERNAME:-root}" "${E2E_DB_PASSWORD:-}" "${database}" +fi + +if [[ "${instance}" != "setup" ]]; then + php artisan migrate:fresh --force --no-interaction > /dev/null + php artisan och:install --no-interaction > /dev/null + php artisan db:seed --class=E2eSeeder --force --no-interaction > /dev/null + # The scripts and styles of Filament (in `public/`, shared by the instances) + php artisan filament:assets --no-interaction > /dev/null +fi + +# Several workers, so that the parallel tests (and the requests of a page) don't queue up behind each other. The +# server of PHP is started directly, from `public/` (as `php artisan serve` does), to fill `$_ENV`, where Laravel reads +# `LARAVEL_STORAGE_PATH` from. +export PHP_CLI_SERVER_WORKERS="${PHP_CLI_SERVER_WORKERS:-6}" +# +# The JIT of OPcache is turned off (e.g. `shivammathur/setup-php` turns it on, in CI): its workers, which serve many +# requests each, crashed with segmentation faults on PHP 8.2, one after the other, until none was left. +# +# Its log of each connection and request is left out (as `php artisan serve` does), keeping the errors, also written +# to `logs/server.log` of the instance (e.g. a crash of the server, kept with the test results on CI). +# +# The workers write at the same time, so a line can be cut by the line of another worker: its end (e.g. `.3.3.0`, the +# version of a script) is left on a line of its own, without spaces, unlike the errors and their stack traces. +server_log_noise='\[[0-9]{3}\]: [A-Z]+ /|127\.0\.0\.1:[0-9]+ (Accepted|Closing|Closed without sending a request)' +server_log_noise+='|PHP [0-9.]+ Development Server|Failed to poll event|^[^[:space:]]*$' +cd public +exec php -d variables_order=EGPCS -d opcache.jit=disable -S "127.0.0.1:${port}" ../vendor/laravel/framework/src/Illuminate/Foundation/resources/server.php \ + 2> >(grep --line-buffered -vE "${server_log_noise}" | tee -a "${LARAVEL_STORAGE_PATH}/logs/server.log" >&2) diff --git a/tests/e2e/support/totp.ts b/tests/e2e/support/totp.ts new file mode 100644 index 00000000..c38c4cf9 --- /dev/null +++ b/tests/e2e/support/totp.ts @@ -0,0 +1,24 @@ +import { createHmac } from 'node:crypto'; + +/** + * The current code of an authenticator app for a Base32 secret (RFC 6238: 6 digits, 30 seconds, SHA-1). + */ +export function totp(secret: string, timestamp: number = Date.now()): string { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + const bits = secret + .replace(/[\s=]/g, '') + .toUpperCase() + .split('') + .map((character) => alphabet.indexOf(character).toString(2).padStart(5, '0')) + .join(''); + const key = Buffer.from(bits.match(/.{8}/g)!.map((byte) => parseInt(byte, 2))); + + const counter = Buffer.alloc(8); + counter.writeBigUInt64BE(BigInt(Math.floor(timestamp / 1000 / 30))); + + const hmac = createHmac('sha1', key).update(counter).digest(); + const offset = hmac[hmac.length - 1] & 0xf; + const code = (hmac.readUInt32BE(offset) & 0x7fffffff) % 1_000_000; + + return code.toString().padStart(6, '0'); +} diff --git a/tests/e2e/support/users.ts b/tests/e2e/support/users.ts new file mode 100644 index 00000000..da53c0bc --- /dev/null +++ b/tests/e2e/support/users.ts @@ -0,0 +1,22 @@ +/** + * The users seeded by `E2eSeeder` (and the root user of `serve.sh`), by role. + */ +export const users = { + root: { email: 'root@e2e.test', password: 'RootPassword123', name: 'Root User' }, + admin: { email: 'admin@e2e.test', password: 'password', name: 'Adam Admin' }, + servant: { email: 'servant@e2e.test', password: 'password', name: 'Simon Servant' }, + overseer: { email: 'overseer@e2e.test', password: 'password', name: 'Oscar Overseer' }, + group: { email: 'group@e2e.test', password: 'password', name: 'Gino Group' }, + publisher: { email: 'publisher@e2e.test', password: 'password', name: 'Paul Publisher' }, + norole: { email: 'norole@e2e.test', password: 'password', name: 'Nora Norole' }, +} as const; + +export type Role = keyof typeof users; + +export const roles = Object.keys(users) as Role[]; + +/** + * The file of the signed-in browser state of a user (see `auth.setup.ts`). + */ +export const storageStateOf = (role: Role): string => + `tests/e2e/.auth/${process.env.E2E_APP_INSTANCE ?? 'app'}/${role}.json`; diff --git a/tests/e2e/tags.spec.ts b/tests/e2e/tags.spec.ts new file mode 100644 index 00000000..4a5d9848 --- /dev/null +++ b/tests/e2e/tags.spec.ts @@ -0,0 +1,255 @@ +import type { Page } from '@playwright/test'; +import { appURL } from '../../playwright.config'; +import { php } from './support/artisan'; +import { applyTableFilters, chooseOption, confirmModal, field, modal, row, rowAction, searchTableUntilApplied, settle, visit } from './support/filament'; +import { expect, test, uniqueName } from './support/fixtures'; +import { storageStateOf } from './support/users'; + +/** + * The tags of the territories and zones (`app/Filament/Resources/Tags`). + * + * Every test works on tags (and territories) of its own, so that the tests running in parallel never see each other's: + * the seeded ones are only read. + */ + +type TagRecord = { name: Record; slug: Record; type: string | null }; + +/** + * The PHP code deleting the records created by the test running, run after it (even when it fails), so that they don't + * pile up over the runs. + */ +let cleanups: string[] = []; + +/** + * Delete records after the test, with PHP code (errors are ignored: the record may be gone already). + */ +const cleanUp = (code: string): void => { + cleanups.push(`try { ${code} } catch (\\Throwable $exception) {}`); +}; + +test.afterEach(() => { + if (cleanups.length > 0) { + php(`${cleanups.join('\n')} return true;`); + cleanups = []; + } +}); + +/** + * A tag name nobody else uses, in lowercase like the slug made from it. + */ +function uniqueTag(prefix: string): string { + const name = uniqueName(prefix).toLowerCase(); + cleanUp(`\\App\\Models\\Tag::where('name->en', 'like', ${JSON.stringify(`${name}%`)})->get()->each->delete();`); + + return name; +} + +/** + * Create a tag of a type, returning its id. + */ +const createTag = (name: string, type: 'territories' | 'zones' | null = 'territories'): number => + php(`return \\App\\Models\\Tag::findOrCreate(${JSON.stringify(name)}, ${JSON.stringify(type)})->id;`); + +/** + * The tag with the name (in the tags locale), as stored. + */ +const tagNamed = (name: string): TagRecord | null => php(` + $tag = \\App\\Models\\Tag::query()->where('name->en', ${JSON.stringify(name)})->first(); + + return $tag ? ['name' => $tag->getTranslations('name'), 'slug' => $tag->getTranslations('slug'), 'type' => $tag->type] : null; +`); + +/** + * Create a territory of its own zone with the tags, returning its id. + */ +function createTerritory(name: string, tags: string[]): number { + const id = php(` + $territory = \\App\\Models\\Territory::factory() + ->for(\\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(`${name} zone`)}])) + ->create(['name' => ${JSON.stringify(name)}]); + $territory->attachTags(${JSON.stringify(tags)}, 'territories'); + + return $territory->id; +`); + cleanUp(`$territory = \\App\\Models\\Territory::withTrashed()->find(${id}); $zone = $territory?->territory_zone_id; $territory?->forceDelete(); \\App\\Models\\TerritoryZone::whereKey($zone)->delete();`); + + return id; +} + +/** + * Expect a notification (toast) with the text, waiting longer than `expect()` does: saving can be slow while the other + * tests run. + */ +const expectNotification = (page: Page, text: string | RegExp): Promise => + expect(page.locator('.fi-no-notification').filter({ hasText: text }).first()).toBeVisible({ timeout: 30_000 }); + +test.describe('Tags', () => { + test('creates a tag with a slug made from its name, edits and deletes it @mobile', async ({ adminPage: page }) => { + const name = uniqueTag('Gated community'); + const slug = name.replace(/ /g, '-'); + + await visit(page, '/app/tags'); + await page.getByRole('button', { name: 'New Tag' }).click(); + await field(modal(page), 'Name').fill(name); + await field(modal(page), 'Name').blur(); + await expect(field(modal(page), 'Slug')).toHaveValue(slug); + await chooseOption(modal(page), 'Type', 'Territories'); + await confirmModal(page, 'Create'); + await expectNotification(page, 'Created'); + + // Stored in the tags locale only, whatever the language of the interface + expect(tagNamed(name)).toEqual({ name: { en: name }, slug: { en: slug }, type: 'territories' }); + + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText(slug); + await expect(row(page, name)).toContainText('Territories'); + + await rowAction(page, name, 'Edit'); + await field(modal(page), 'Name').fill(`${name} edited`); + await field(modal(page), 'Name').blur(); + await settle(page); + // The form fills it in only for a new tag... + await expect(field(modal(page), 'Slug')).toHaveValue(slug); + await confirmModal(page, 'Save changes'); + await expectNotification(page, 'Saved'); + // ...but the tags make it again from the name whenever they are saved (see the test.fixme below) + expect(tagNamed(`${name} edited`)).toEqual({ name: { en: `${name} edited` }, slug: { en: `${slug}-edited` }, type: 'territories' }); + + await rowAction(page, `${name} edited`, 'Delete'); + await expect(modal(page)).toContainText('No territory or zone uses this tag.'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + + await expect(row(page, `${name} edited`)).toHaveCount(0); + expect(tagNamed(`${name} edited`)).toBeNull(); + }); + + test('refuses a slug that is not made of letters, numbers and dashes', async ({ adminPage: page }) => { + const name = uniqueTag('Bad slug'); + + await visit(page, '/app/tags'); + await page.getByRole('button', { name: 'New Tag' }).click(); + await field(modal(page), 'Name').fill(name); + await field(modal(page), 'Name').blur(); + await expect(field(modal(page), 'Slug')).not.toHaveValue(''); + await field(modal(page), 'Slug').fill('not a slug!'); + await confirmModal(page, 'Create'); + + await expect(modal(page)).toContainText('The slug field must only contain letters, numbers, dashes, and underscores.'); + expect(tagNamed(name)).toBeNull(); + }); + + // Bug: the Slug field of the form is never saved. `Spatie\Tags\HasSlug` makes the slug again from the name on every + // save (`static::saving()`), so a slug typed by hand, on a new tag or when editing one, is silently replaced. + test.fixme('keeps the slug typed by hand', async ({ adminPage: page }) => { + const name = uniqueTag('Custom slug'); + + await visit(page, '/app/tags'); + await page.getByRole('button', { name: 'New Tag' }).click(); + await field(modal(page), 'Name').fill(name); + await field(modal(page), 'Name').blur(); + await expect(field(modal(page), 'Slug')).not.toHaveValue(''); + await field(modal(page), 'Slug').fill('my-custom-slug'); + await confirmModal(page, 'Create'); + await expectNotification(page, 'Created'); + + expect(tagNamed(name)?.slug).toEqual({ en: 'my-custom-slug' }); + }); + + test('stores the tags created in another interface language in the tags locale', async ({ browser }) => { + const name = uniqueTag('Condominio'); + // The language preferred by the browser, which the application follows when none was chosen + const context = await browser.newContext({ baseURL: appURL, storageState: storageStateOf('admin'), locale: 'it-IT' }); + const page = await context.newPage(); + + try { + await visit(page, '/app/tags'); + await page.getByRole('button', { name: /^Nuovo/ }).click(); + await field(modal(page), 'Nome').fill(name); + await field(modal(page), 'Nome').blur(); + await expect(field(modal(page), 'Slug')).toHaveValue(name.replace(/ /g, '-')); + await chooseOption(modal(page), 'Tipo', 'Territori'); + await confirmModal(page, 'Salva'); + await expectNotification(page, 'Creato'); + } finally { + await context.close(); + } + + expect(tagNamed(name)).toEqual({ name: { en: name }, slug: { en: name.replace(/ /g, '-') }, type: 'territories' }); + }); + + test('filters the tags by type', async ({ adminPage: page }) => { + const prefix = uniqueTag('Typed'); + const [territoryTag, zoneTag] = [`${prefix} territory`, `${prefix} zone`]; + createTag(territoryTag, 'territories'); + createTag(zoneTag, 'zones'); + const shown = page.locator('.fi-ta-row').filter({ hasText: prefix }); + + await visit(page, '/app/tags'); + await searchTableUntilApplied(page, prefix); + await expect(shown).toHaveCount(2); + + await applyTableFilters(page, (panel) => chooseOption(panel, 'Filter by Type', 'Zones')); + await expect(shown).toHaveCount(1); + await expect(row(page, zoneTag)).toContainText('Zones'); + + await applyTableFilters(page, (panel) => chooseOption(panel, 'Filter by Type', 'Territories')); + await expect(shown).toHaveCount(1); + await expect(row(page, territoryTag)).toContainText('Territories'); + }); + + test('warns how many territories use a tag before deleting it, keeping the territories', async ({ adminPage: page }) => { + const name = uniqueTag('Used tag'); + const kept = uniqueTag('Kept tag'); + const territoryName = uniqueName('Tagged territory'); + const territoryId = createTerritory(territoryName, [name, kept]); + + await visit(page, '/app/tags'); + await searchTableUntilApplied(page, name); + await expect(row(page, name)).toContainText('1'); + + await rowAction(page, name, 'Delete'); + await expect(modal(page)).toContainText('This tag is used by 1 territory and 0 zones: deleting it removes it from them.'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + + await expect(row(page, name)).toHaveCount(0); + expect(tagNamed(name)).toBeNull(); + expect(php(`return \\App\\Models\\Territory::find(${territoryId})?->tags->pluck('name')->all();`)).toEqual([kept]); + }); + + test('filters the territories by a territory tag', async ({ adminPage: page }) => { + const name = uniqueTag('Filter tag'); + const prefix = uniqueName('Tag filter territory'); + const [tagged, untagged] = [`${prefix} tagged`, `${prefix} untagged`]; + createTerritory(tagged, [name]); + createTerritory(untagged, []); + const shown = page.locator('.fi-ta-row').filter({ hasText: prefix }); + + await visit(page, '/app/territories'); + await searchTableUntilApplied(page, prefix); + await expect(shown).toHaveCount(2); + + // Through the URL: the options of the filter may not show the tag (see the test.fixme below) + await visit(page, `/app/territories?filters[tags][values][0]=${encodeURIComponent(name)}`); + await expect(page.getByText(`Tags: ${name}`)).toBeVisible(); + await searchTableUntilApplied(page, prefix); + await expect(shown).toHaveCount(1); + await expect(row(page, tagged)).toBeVisible(); + }); + + // Bug: the Tags filter of the territories (`TerritoryResource`, a multiple select without search) shows only the + // first 50 tags: once there are more, the newest ones can't be chosen at all. + test.fixme('offers every territory tag in the filter of the territories', async ({ adminPage: page }) => { + const name = uniqueTag('Filter tag'); + const prefix = uniqueName('Tag filter territory'); + // More tags than the 50 options shown (`SelectFilter::$optionsLimit`), before the one looked for + php(`foreach (range(1, 60) as $number) { \\App\\Models\\Tag::findOrCreate(${JSON.stringify(name)}." other {$number}", 'territories'); } return true;`); + createTerritory(`${prefix} tagged`, [name]); + + await visit(page, '/app/territories'); + await applyTableFilters(page, (panel) => chooseOption(panel, 'Tags', name)); + await searchTableUntilApplied(page, prefix); + await expect(row(page, `${prefix} tagged`)).toBeVisible(); + }); +}); diff --git a/tests/e2e/territories.spec.ts b/tests/e2e/territories.spec.ts new file mode 100644 index 00000000..d03b89c9 --- /dev/null +++ b/tests/e2e/territories.spec.ts @@ -0,0 +1,416 @@ +import { readFileSync } from 'node:fs'; +import type { Page } from '@playwright/test'; +import { php } from './support/artisan'; +import { bulkMenuAction, chooseOption, confirmModal, expectNotification, field, modal, row, rowMenuAction, searchTableUntilApplied, settle, visit } from './support/filament'; +import { expect, test, uniqueName, users } from './support/fixtures'; + +/** + * The territories (`app/Filament/Resources/Territories`): their list, form, pages and import. + * + * Every test works on territories of a zone of its own, so that the tests running in parallel never see each other's. + */ + +const polygon = JSON.stringify({ + type: 'FeatureCollection', + features: [{ + type: 'Feature', + properties: {}, + geometry: { type: 'Polygon', coordinates: [[[12.40, 41.90], [12.45, 41.90], [12.42, 41.94], [12.40, 41.90]]] }, + }], +}); + +type TerritoryAttributes = { name: string; is_commercial?: boolean; geojson?: string | null; notes?: string; tags?: string[]; assigned?: boolean; deleted?: boolean }; + +/** + * Create a zone with the territories, returning the ids of the zone and of the territories (by name). + */ +function createZoneWith(zoneName: string, territories: TerritoryAttributes[]): { zoneId: number; ids: Record } { + return php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(zoneName)}]); + $publisher = \\App\\Models\\User::where('email', ${JSON.stringify(users.publisher.email)})->sole(); + $ids = []; + + foreach (json_decode(${JSON.stringify(JSON.stringify(territories))}, true) as $attributes) { + $territory = \\App\\Models\\Territory::factory()->for($zone)->create([ + 'name' => $attributes['name'], + 'is_commercial' => $attributes['is_commercial'] ?? false, + 'geojson' => $attributes['geojson'] ?? null, + 'notes' => $attributes['notes'] ?? 'Notes', + ]); + + foreach ($attributes['tags'] ?? [] as $tag) { + $territory->attachTag($tag, \\App\\Enums\\TagType::TERRITORIES->value); + } + + if ($attributes['assigned'] ?? false) { + $territory->assignments()->create(['assignee_id' => $publisher->id, 'started_at' => now()->subDays(3)]); + } + + if ($attributes['deleted'] ?? false) { + $territory->delete(); + } + + $ids[$attributes['name']] = $territory->id; + } + + return ['zoneId' => $zone->id, 'ids' => $ids]; + `); +} + +/** + * Open the territories list, showing only the territories whose name contains the text. + */ +async function listTerritories(page: Page, search: string): Promise { + await visit(page, '/app/territories'); + await searchTableUntilApplied(page, search); +} + +/** + * Set a filter of the territories table and apply it. + */ +async function applyFilter(page: Page, label: string, option: string): Promise { + const apply = page.getByRole('button', { name: 'Apply filters' }); + + // Clicked while the page is still loading, the button may not open the panel yet + await expect(async () => { + if (!(await apply.isVisible())) { + await page.getByRole('button', { name: 'Filter', exact: true }).click(); + } + + await expect(apply).toBeVisible({ timeout: 2_000 }); + }).toPass({ timeout: 20_000 }); + + await chooseOption(page.locator('.fi-dropdown-panel').filter({ visible: true }), label, option); + // Close the list of options of a multiple select, which stays open over the button + await page.getByRole('heading', { name: 'Filters' }).click(); + await page.getByRole('button', { name: 'Apply filters' }).click(); + await expect(page.getByRole('button', { name: 'Apply filters' })).toBeHidden(); + await settle(page); +} + +/** The rows of the records of the table (not the individual search row, nor the group headers). */ +/** + * Submit the form of the page with its button (not the buttons of its fields, e.g. the one creating a zone). + */ +async function submitForm(page: Page, label: string): Promise { + await page.getByRole('button', { name: label, exact: true }).and(page.locator('[type="submit"]')).filter({ visible: true }).first().click(); +} + +const territoryRows = (page: Page) => page.locator('.fi-ta-row:has(.fi-ta-record-checkbox)'); + +test.describe.configure({ mode: 'parallel' }); + +test.describe('Territories list', () => { + test('has tabs for any, residential and commercial territories, with their counts', async ({ adminPage: page }) => { + await visit(page, '/app/territories'); + + const tabs = page.getByRole('group', { name: 'Filter records' }); + const countOf = async (tab: string): Promise => + Number((await tabs.getByRole('button', { name: new RegExp(`^${tab} \\d+$`) }).innerText()).replace(/\D/g, '')); + + const [any, residential, commercial] = [await countOf('Any'), await countOf('Residential'), await countOf('Commercial')]; + expect(residential).toBeGreaterThan(0); + expect(commercial).toBeGreaterThan(0); + expect(any).toBe(residential + commercial); + + await searchTableUntilApplied(page, 'E2E'); + await expect(row(page, 'E2E Commercial')).toBeVisible(); + await expect(row(page, 'E2E Free')).toBeVisible(); + + await tabs.getByRole('button', { name: /^Commercial/ }).click(); + await settle(page); + await expect(row(page, 'E2E Commercial')).toBeVisible(); + await expect(row(page, 'E2E Free')).toHaveCount(0); + + await tabs.getByRole('button', { name: /^Residential/ }).click(); + await settle(page); + await expect(row(page, 'E2E Free')).toBeVisible(); + await expect(row(page, 'E2E Commercial')).toHaveCount(0); + }); + + test('searches the territories by name', async ({ adminPage: page }) => { + const zone = uniqueName('Search Zone'); + createZoneWith(zone, [{ name: `${zone} Alpha` }, { name: `${zone} Beta` }]); + + await listTerritories(page, `${zone} Alpha`); + + await expect(territoryRows(page)).toHaveCount(1); + await expect(row(page, `${zone} Alpha`)).toContainText(zone); + }); + + test('filters the territories by assignment status, map and tags', async ({ adminPage: page }) => { + const zone = uniqueName('Filter Zone'); + const tag = uniqueName('Tag'); + createZoneWith(zone, [ + { name: `${zone} Assigned`, assigned: true }, + { name: `${zone} Mapped`, geojson: polygon, tags: [tag] }, + { name: `${zone} Plain` }, + ]); + + await listTerritories(page, zone); + await expect(territoryRows(page)).toHaveCount(3); + await expect(row(page, `${zone} Assigned`)).toContainText(users.publisher.name); + + await applyFilter(page, 'Assignment Status', 'Assigned'); + await expect(territoryRows(page)).toHaveCount(1); + await expect(row(page, `${zone} Assigned`)).toBeVisible(); + + await applyFilter(page, 'Assignment Status', 'Unassigned'); + await expect(territoryRows(page)).toHaveCount(2); + await expect(row(page, `${zone} Assigned`)).toHaveCount(0); + + await applyFilter(page, 'Map State', 'Available'); + await expect(territoryRows(page)).toHaveCount(1); + await expect(row(page, `${zone} Mapped`)).toBeVisible(); + + await page.getByRole('button', { name: 'Filter', exact: true }).click(); + await page.getByRole('button', { name: 'Reset' }).click(); + await settle(page); + await searchTableUntilApplied(page, zone); + await expect(territoryRows(page)).toHaveCount(3); + + await applyFilter(page, 'Tags', tag); + await expect(territoryRows(page)).toHaveCount(1); + await expect(row(page, `${zone} Mapped`)).toContainText(tag); + }); + + test('shows the deleted territories only with the trashed filter', async ({ adminPage: page }) => { + const zone = uniqueName('Trash Zone'); + createZoneWith(zone, [{ name: `${zone} Kept` }, { name: `${zone} Gone`, deleted: true }]); + + await listTerritories(page, zone); + await expect(territoryRows(page)).toHaveCount(1); + await expect(row(page, `${zone} Gone`)).toHaveCount(0); + + await applyFilter(page, 'Deleted records', 'With deleted records'); + await expect(territoryRows(page)).toHaveCount(2); + + await applyFilter(page, 'Deleted records', 'Only deleted records'); + await expect(territoryRows(page)).toHaveCount(1); + await expect(row(page, `${zone} Gone`)).toBeVisible(); + }); + + test('groups the territories by zone, with the number of territories of each', async ({ adminPage: page }) => { + const zone = uniqueName('Group Zone'); + createZoneWith(zone, [{ name: `${zone} One` }, { name: `${zone} Two` }]); + + await listTerritories(page, zone); + await page.getByRole('combobox', { name: 'Group by' }).selectOption({ label: 'Zone' }); + await settle(page); + + await expect(page.locator('.fi-ta-group-header').filter({ hasText: `${zone} (2)` })).toBeVisible(); + await expect(territoryRows(page)).toHaveCount(2); + }); +}); + +test.describe('Territory form', () => { + test('creates a territory with a map, an image, notes and tags', async ({ adminPage: page }) => { + const zone = uniqueName('Form Zone'); + createZoneWith(zone, []); + const name = uniqueName('Created Territory'); + const tag = uniqueName('Form Tag'); + + await visit(page, '/app/territories/create'); + await field(page, 'Name').fill(name); + await chooseOption(page, 'Zone', zone); + await page.getByRole('switch', { name: 'Commercial?' }).click(); + await field(page, 'Notes').fill('Ring the bell twice'); + await page.getByRole('combobox', { name: 'Tags' }).fill(tag); + await page.getByRole('combobox', { name: 'Tags' }).press('Enter'); + + // Draw a triangle with the polygon tool of the map editor + await page.locator('[title="Draw Polygons"] .leaflet-buttons-control-button').click(); + const map = await page.locator('.leaflet-container').first().boundingBox(); + for (const [x, y] of [[0.3, 0.3], [0.7, 0.3], [0.5, 0.7], [0.3, 0.3]]) { + await page.mouse.click(map!.x + map!.width * x, map!.y + map!.height * y); + } + await expect(field(page, 'Geojson')).toHaveValue(/"Polygon"/); + + await page.getByRole('tab', { name: 'Image' }).click(); + const imageTab = page.getByRole('tabpanel', { name: 'Image' }); + await expect(imageTab.getByText('Drag & Drop your files')).toBeVisible(); + await imageTab.locator('input[type="file"]').setInputFiles('tests/e2e/fixtures/territory.png'); + await expect(imageTab.getByRole('alert')).toContainText('Upload complete'); + await expect(imageTab.getByRole('img', { name })).toBeVisible(); + + await submitForm(page, 'Create'); + await expect(page).toHaveURL(/\/app\/territories\/\d+$/); + await expect(page.getByRole('heading', { level: 1, name: `View ${name}` })).toBeVisible(); + + const saved = php<{ zone: string; is_commercial: boolean; notes: string; tags: string[]; geojson: string; image_path: string }>(` + $territory = \\App\\Models\\Territory::with('territoryZone')->where('name', ${JSON.stringify(name)})->sole(); + + return [ + 'zone' => $territory->territoryZone->name, + 'is_commercial' => $territory->is_commercial, + 'notes' => $territory->notes, + 'tags' => $territory->tags->pluck('name')->all(), + 'geojson' => $territory->geojson, + 'image_path' => $territory->image_path, + ]; + `); + expect(saved).toMatchObject({ zone, is_commercial: true, notes: 'Ring the bell twice', tags: [tag] }); + expect(JSON.parse(saved.geojson).features[0].geometry.type).toBe('Polygon'); + expect(saved.image_path).toMatch(/^territories\/.+\.png$/); + }); + + test('refuses a name already used in the same zone', async ({ adminPage: page }) => { + const zone = uniqueName('Unique Zone'); + createZoneWith(zone, [{ name: `${zone} Taken` }]); + + await visit(page, '/app/territories/create'); + await field(page, 'Name').fill(`${zone} Taken`); + await chooseOption(page, 'Zone', zone); + await submitForm(page, 'Create'); + + await expect(page.getByText('A territory with this name already exists in this zone.')).toBeVisible(); + await expect(page).toHaveURL(/\/create$/); + }); + + test('shows the details and the map of a territory on its page', async ({ adminPage: page }) => { + const zone = uniqueName('View Zone'); + const name = `${zone} Viewed`; + const { ids } = createZoneWith(zone, [{ name, geojson: polygon, notes: 'Beware of the dog', tags: ['Viewed tag'] }]); + + await visit(page, `/app/territories/${ids[name]}`); + + await expect(page.getByRole('heading', { level: 1, name: `View ${name}` })).toBeVisible(); + await expect(field(page, 'Name')).toHaveValue(name); + await expect(page.getByRole('button', { name: 'Zone' })).toHaveText(zone); + await expect(field(page, 'Notes')).toHaveValue('Beware of the dog'); + await expect(page.getByRole('group', { name: 'Tags' })).toContainText('Viewed tag'); + await expect(page.getByText('Never covered yet')).toBeVisible(); + await expect(page.getByRole('tab', { name: 'Map' })).toBeVisible(); + await expect(page.locator('.leaflet-overlay-pane path').first()).toBeVisible(); + }); + + test('edits a territory', async ({ adminPage: page }) => { + const zone = uniqueName('Edit Zone'); + const name = `${zone} Before`; + const { ids } = createZoneWith(zone, [{ name }]); + + await visit(page, `/app/territories/${ids[name]}/edit`); + await field(page, 'Name').fill(`${zone} After`); + await page.getByRole('switch', { name: 'Commercial?' }).click(); + await field(page, 'Notes').fill('Edited notes'); + await page.getByRole('button', { name: 'Save changes' }).click(); + + await expectNotification(page, 'Saved'); + expect(php(`return \\App\\Models\\Territory::find(${ids[name]})->only(['name', 'is_commercial', 'notes']);`)).toEqual({ + name: `${zone} After`, + is_commercial: true, + notes: 'Edited notes', + }); + }); +}); + +test.describe('Territory deletion', () => { + test('refuses to delete a territory that is still assigned', async ({ adminPage: page }) => { + const zone = uniqueName('Guard Zone'); + const name = `${zone} Out`; + const { ids } = createZoneWith(zone, [{ name, assigned: true }]); + + await visit(page, `/app/territories/${ids[name]}/edit`); + await page.locator('.fi-header').getByRole('button', { name: 'Delete' }).click(); + await confirmModal(page, 'Delete'); + + await expectNotification(page, 'Territory not deleted'); + await expectNotification(page, 'This territory is still assigned'); + expect(php(`return \\App\\Models\\Territory::withTrashed()->find(${ids[name]})->trashed();`)).toBe(false); + }); + + test('deletes a territory, restores it, then deletes it permanently', async ({ adminPage: page }) => { + const zone = uniqueName('Delete Zone'); + const name = `${zone} Doomed`; + const { ids } = createZoneWith(zone, [{ name }]); + const isTrashed = (): boolean | null => + php(`return \\App\\Models\\Territory::withTrashed()->find(${ids[name]})?->trashed();`); + + await visit(page, `/app/territories/${ids[name]}/edit`); + await page.locator('.fi-header').getByRole('button', { name: 'Delete' }).click(); + await confirmModal(page, 'Delete'); + await expect(page).toHaveURL(/\/app\/territories$/); + await expectNotification(page, 'Deleted'); + expect(isTrashed()).toBe(true); + + await searchTableUntilApplied(page, zone); + await applyFilter(page, 'Deleted records', 'Only deleted records'); + await rowMenuAction(page, name, 'Restore'); + await confirmModal(page, 'Restore'); + await expectNotification(page, 'Restored'); + expect(isTrashed()).toBe(false); + + await applyFilter(page, 'Deleted records', 'With deleted records'); + await bulkMenuAction(page, [name], 'Delete selected'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + expect(isTrashed()).toBe(true); + + await rowMenuAction(page, name, 'Force delete'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + expect(isTrashed()).toBeNull(); + }); +}); + +test.describe('Territory import', () => { + test('imports the territories of a CSV file', async ({ adminPage: page }) => { + const zone = uniqueName('Import Zone'); + const prefix = uniqueName('Imported'); + const csv = readFileSync('tests/e2e/fixtures/territories-import.csv', 'utf8') + .replaceAll('{prefix}', prefix) + .replaceAll('{zone}', zone); + + await visit(page, '/app/territories'); + await page.getByRole('button', { name: 'Import territories' }).click(); + await expect(modal(page).getByText('Upload a CSV file')).toBeVisible(); + await modal(page).locator('input[type="file"]').setInputFiles({ name: 'territories.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) }); + await expect(modal(page).getByRole('alert')).toContainText('Upload complete'); + await expect(field(modal(page), 'Zone')).toHaveValue('territoryZone'); + await confirmModal(page, 'Import'); + await expectNotification(page, /import/i); + + await expect.poll(() => php(` + return \\App\\Models\\Territory::with('territoryZone')->where('name', 'like', ${JSON.stringify(`${prefix}%`)})->orderBy('name')->get() + ->map(fn ($territory) => [$territory->name, $territory->territoryZone->name, $territory->is_commercial, $territory->notes])->all(); + `)).toEqual([ + [`${prefix} Market`, zone, true, 'Shops only'], + [`${prefix} North`, zone, false, 'Ring twice'], + ]); + + await listTerritories(page, prefix); + await expect(territoryRows(page)).toHaveCount(2); + await expect(row(page, `${prefix} North`)).toContainText(zone); + }); +}); + +test.describe('Territory assignment history', () => { + test('lists the past and current assignments of a territory', async ({ adminPage: page }) => { + const zone = uniqueName('History Zone'); + const name = `${zone} Worked`; + const { ids } = createZoneWith(zone, [{ name }]); + php(` + $territory = \\App\\Models\\Territory::find(${ids[name]}); + $servant = \\App\\Models\\User::where('email', ${JSON.stringify(users.servant.email)})->sole(); + $publisher = \\App\\Models\\User::where('email', ${JSON.stringify(users.publisher.email)})->sole(); + $territory->assignments()->create(['assignee_id' => $servant->id, 'started_at' => now()->subDays(40), 'ended_at' => now()->subDays(20)]); + $territory->assignments()->create(['assignee_id' => $publisher->id, 'started_at' => now()->subDays(5)]); + + return true; + `); + + await visit(page, `/app/territories/${ids[name]}`); + await page.getByRole('navigation', { name: 'Tabs' }).getByRole('link', { name: /Assignment History/ }).click(); + + await expect(page).toHaveURL(new RegExp(`/app/territories/${ids[name]}/assignments$`)); + await expect(page.getByRole('heading', { level: 1, name: `Assignment history of ${name}` })).toBeVisible(); + await expect(page.getByRole('navigation', { name: 'Tabs' }).getByRole('link', { name: /Assignment History/ })).toContainText('2'); + // Only the assignments in progress, by default + await expect(territoryRows(page)).toHaveCount(1); + await expect(row(page, users.publisher.name)).toContainText('(in progress)'); + + await applyFilter(page, 'Assignment Status', 'All statuses'); + await expect(territoryRows(page)).toHaveCount(2); + await expect(row(page, users.servant.name)).not.toContainText('(in progress)'); + }); +}); diff --git a/tests/e2e/territory-zones.spec.ts b/tests/e2e/territory-zones.spec.ts new file mode 100644 index 00000000..facc07b8 --- /dev/null +++ b/tests/e2e/territory-zones.spec.ts @@ -0,0 +1,203 @@ +import type { Page } from '@playwright/test'; +import { php } from './support/artisan'; +import { chooseOption, confirmModal, expectNotification, field, modal, row, rowAction, searchTableUntilApplied, settle, visit } from './support/filament'; +import { expect, test, uniqueName } from './support/fixtures'; + +/** + * The zones of the territories (`app/Filament/Resources/TerritoryZones`), and the territories page of a zone. + */ + +/** + * Create a zone with territories of the given names (and tags of its own), returning the ids of the zone and of the + * territories. + */ +function createZone(name: string, options: { territories?: string[]; tags?: string[] } = {}): { zoneId: number; ids: Record } { + return php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(name)}]); + + foreach (json_decode(${JSON.stringify(JSON.stringify(options.tags ?? []))}, true) as $tag) { + $zone->attachTag($tag, \\App\\Enums\\TagType::ZONES->value); + } + + $ids = []; + foreach (json_decode(${JSON.stringify(JSON.stringify(options.territories ?? []))}, true) as $territory) { + $ids[$territory] = \\App\\Models\\Territory::factory()->for($zone)->create(['name' => $territory])->id; + } + + return ['zoneId' => $zone->id, 'ids' => $ids]; + `); +} + +/** + * Whether a zone is deleted (soft), or null when it is permanently deleted. + */ +const isZoneTrashed = (id: number): boolean | null => + php(`return \\App\\Models\\TerritoryZone::withTrashed()->find(${id})?->trashed();`); + +/** + * Set a filter of the table and apply it. + */ +async function applyFilter(page: Page, label: string, option: string): Promise { + const apply = page.getByRole('button', { name: 'Apply filters' }); + + // Clicked while the page is still loading, the button may not open the panel yet + await expect(async () => { + if (!(await apply.isVisible())) { + await page.getByRole('button', { name: 'Filter', exact: true }).click(); + } + + await expect(apply).toBeVisible({ timeout: 2_000 }); + }).toPass({ timeout: 20_000 }); + + await chooseOption(page.locator('.fi-dropdown-panel').filter({ visible: true }), label, option); + // Close the list of options of a multiple select, which stays open over the button + await page.getByRole('heading', { name: 'Filters' }).click(); + await apply.click(); + await expect(apply).toBeHidden(); + await settle(page); +} + +/** The rows of the records of the table (not the individual search row). */ +const tableRows = (page: Page) => page.locator('.fi-ta-row:has(.fi-ta-record-checkbox)'); + +test.describe.configure({ mode: 'parallel' }); + +test.describe('Zones', () => { + test('creates a zone with a color and tags', async ({ adminPage: page }) => { + const name = uniqueName('Zone'); + const tag = uniqueName('Zone tag'); + + await visit(page, '/app/territory-zones/create'); + await field(page, 'Name').fill(name); + await page.getByRole('combobox', { name: 'Color' }).fill('#aa3300'); + await page.getByRole('combobox', { name: 'Tags' }).fill(tag); + await page.getByRole('combobox', { name: 'Tags' }).press('Enter'); + await page.getByRole('button', { name: 'Create', exact: true }).and(page.locator('[type="submit"]')).click(); + + await expectNotification(page, 'Created'); + await expect(page.getByRole('heading', { level: 1 })).toContainText(name); + expect(php(` + $zone = \\App\\Models\\TerritoryZone::where('name', ${JSON.stringify(name)})->sole(); + + return ['color' => $zone->color, 'tags' => $zone->tags->pluck('name')->all()]; + `)).toEqual({ color: '#aa3300', tags: [tag] }); + }); + + test('lists the zones with their number of territories, and filters them by tag', async ({ adminPage: page }) => { + const prefix = uniqueName('Listed'); + const tag = uniqueName('Zone tag'); + createZone(`${prefix} Tagged`, { tags: [tag], territories: [`${prefix} T1`, `${prefix} T2`] }); + createZone(`${prefix} Untagged`); + + await visit(page, '/app/territory-zones'); + await searchTableUntilApplied(page, prefix); + await expect(tableRows(page)).toHaveCount(2); + await expect(row(page, `${prefix} Tagged`)).toContainText('2'); + await expect(row(page, `${prefix} Tagged`)).toContainText(tag); + + await applyFilter(page, 'Tags', tag); + await expect(tableRows(page)).toHaveCount(1); + await expect(row(page, `${prefix} Tagged`)).toBeVisible(); + }); + + test('edits a zone', async ({ adminPage: page }) => { + const name = uniqueName('Zone'); + const { zoneId } = createZone(name); + + await visit(page, `/app/territory-zones/${zoneId}/edit`); + await field(page, 'Name').fill(`${name} renamed`); + await page.getByRole('button', { name: 'Save changes' }).click(); + + await expectNotification(page, 'Saved'); + expect(php(`return \\App\\Models\\TerritoryZone::find(${zoneId})->name;`)).toBe(`${name} renamed`); + }); + + test('deletes an empty zone, restores it, then deletes it permanently', async ({ adminPage: page }) => { + const name = uniqueName('Empty Zone'); + const { zoneId } = createZone(name); + + await visit(page, `/app/territory-zones/${zoneId}`); + await page.locator('.fi-header').getByRole('button', { name: 'Delete' }).click(); + await confirmModal(page, 'Delete'); + await expect(page).toHaveURL(/\/app\/territory-zones$/); + expect(isZoneTrashed(zoneId)).toBe(true); + + await searchTableUntilApplied(page, name); + await expect(tableRows(page)).toHaveCount(0); + await applyFilter(page, 'Deleted records', 'Only deleted records'); + await expect(tableRows(page)).toHaveCount(1); + await rowAction(page, name, 'Restore'); + await confirmModal(page, 'Restore'); + await expectNotification(page, 'Restored'); + expect(isZoneTrashed(zoneId)).toBe(false); + + // Only a deleted zone can be deleted permanently + php(`\\App\\Models\\TerritoryZone::find(${zoneId})->delete(); return true;`); + await page.reload(); + await settle(page); + await expect(row(page, name).getByRole('button', { name: 'Force delete' })).toBeVisible(); + await rowAction(page, name, 'Force delete'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + expect(isZoneTrashed(zoneId)).toBeNull(); + }); + + test('refuses to delete a zone that still has territories', async ({ adminPage: page }) => { + const name = uniqueName('Full Zone'); + const { zoneId } = createZone(name, { territories: [`${name} T1`] }); + + await visit(page, `/app/territory-zones/${zoneId}`); + await page.locator('.fi-header').getByRole('button', { name: 'Delete' }).click(); + await confirmModal(page, 'Delete'); + + await expectNotification(page, 'Zone not deleted'); + await expectNotification(page, 'This zone still contains territories'); + expect(isZoneTrashed(zoneId)).toBe(false); + }); +}); + +test.describe('Territories of a zone', () => { + test('creates a territory from the territories page of the zone', async ({ adminPage: page }) => { + const zone = uniqueName('Zone'); + const { zoneId } = createZone(zone, { territories: [`${zone} Existing`] }); + const name = `${zone} New`; + + await visit(page, `/app/territory-zones/${zoneId}/territories`); + await expect(page.getByRole('heading', { level: 1, name: `Territories of zone ${zone}` })).toBeVisible(); + await expect(tableRows(page)).toHaveCount(1); + + await page.getByRole('button', { name: 'New territory' }).click(); + await field(modal(page), 'Name').fill(name); + await chooseOption(modal(page), 'Zone', zone); + await field(modal(page), 'Notes').fill('Created from the zone'); + await confirmModal(page, 'Create'); + + await expectNotification(page, 'Created'); + await expect(tableRows(page)).toHaveCount(2); + await expect(row(page, name)).toBeVisible(); + expect(php(`return \\App\\Models\\Territory::where('name', ${JSON.stringify(name)})->sole()->only(['territory_zone_id', 'notes']);`)) + .toEqual({ territory_zone_id: zoneId, notes: 'Created from the zone' }); + }); + + test('deletes a territory of the zone and restores it', async ({ adminPage: page }) => { + const zone = uniqueName('Zone'); + const name = `${zone} Removed`; + const { zoneId, ids } = createZone(zone, { territories: [name] }); + const isTrashed = (): boolean => php(`return \\App\\Models\\Territory::withTrashed()->find(${ids[name]})->trashed();`); + + await visit(page, `/app/territory-zones/${zoneId}/territories`); + await expect(tableRows(page)).toHaveCount(1); + await rowAction(page, name, 'Delete'); + await confirmModal(page, 'Delete'); + await expectNotification(page, 'Deleted'); + await expect(tableRows(page)).toHaveCount(0); + expect(isTrashed()).toBe(true); + + await applyFilter(page, 'Deleted records', 'With deleted records'); + await expect(row(page, name).getByRole('button', { name: 'Restore' })).toBeVisible(); + await rowAction(page, name, 'Restore'); + await confirmModal(page, 'Restore'); + await expectNotification(page, 'Restored'); + expect(isTrashed()).toBe(false); + }); +}); diff --git a/tests/e2e/users.spec.ts b/tests/e2e/users.spec.ts new file mode 100644 index 00000000..d4fe16e2 --- /dev/null +++ b/tests/e2e/users.spec.ts @@ -0,0 +1,501 @@ +import type { Browser, Locator, Page } from '@playwright/test'; +import { appURL } from '../../playwright.config'; +import { test, expect, logIn, uniqueName, users } from './support/fixtures'; +import { php } from './support/artisan'; +import { confirmModal, expectNotification, field, labelled, modal, row, rowAction, searchTable, settle, visit } from './support/filament'; +import { lastMailTo, linkInLastMailTo } from './support/mail'; + +type ThrowawayUser = { id: number; firstName: string; lastName: string; name: string; email: string }; + +/** + * A throwaway user (with the password `password`, verified, a publisher), with the attributes given. + */ +function createUser(attributes: Record = {}, role: string | null = 'publisher', lastName = 'Throwaway'): ThrowawayUser { + const firstName = uniqueName('User'); + const email = `${firstName.toLowerCase().replaceAll(' ', '-')}@e2e.test`; + const id = php(` + $user = \\App\\Models\\User::factory()->verified()->create(array_merge([ + 'first_name' => ${JSON.stringify(firstName)}, + 'last_name' => ${JSON.stringify(lastName)}, + 'email' => ${JSON.stringify(email)}, + 'locale' => 'en', + ], json_decode(${JSON.stringify(JSON.stringify(attributes))}, true))); + ${role ? `$user->assignRole(${JSON.stringify(role)});` : ''} + + return $user->id; + `); + + return { id, firstName, lastName, name: `${firstName} ${lastName}`, email }; +} + +/** + * The attributes of a user in the database, `null` once deleted. + */ +const userInDatabase = (id: number): { first_name: string; last_name: string; can_login: boolean; roles: string[]; departments: string[] } | null => + php(` + $user = \\App\\Models\\User::find(${id}); + + return $user ? [ + 'first_name' => $user->first_name, + 'last_name' => $user->last_name, + 'can_login' => (bool) $user->can_login, + 'roles' => $user->getRoleNames()->sort()->values()->all(), + 'departments' => $user->departments->map(fn ($department) => $department->key->value . ':' . (is_string($department->pivot->role) ? $department->pivot->role : $department->pivot->role->value))->all(), + ] : null; + `); + +/** + * Pick an option of a searchable select of Filament (a button named after its label, then after the options chosen). + */ +async function pickOption(page: Page, scope: Page | Locator, label: string, option: string, close: () => Promise = () => page.keyboard.press('Escape')): Promise { + const search = page.locator('.fi-select-input-search-ctn input').filter({ visible: true }).first(); + + if (!(await search.isVisible())) { + await scope.locator('.fi-fo-field').filter({ has: page.locator('label', { hasText: labelled(label) }) }).locator('.fi-select-input-btn').click(); + } + + // The selects with few options have no search + const choice = page.getByRole('option', { name: option, exact: true }).filter({ visible: true }).first(); + await expect(search.or(choice).first()).toBeVisible(); + + if (await search.isVisible()) { + await search.fill(option); + } + + await choice.click(); + await close(); +} + +/** + * Run a bulk action of the table on the rows: the actions of the group are menu items. + */ +async function bulkMenuAction(page: Page, rowTexts: string[], action: string): Promise { + for (const text of rowTexts) { + await row(page, text).getByRole('checkbox').check(); + } + + await page.getByRole('button', { name: 'Bulk actions' }).click(); + await page.getByRole('menu', { name: 'Bulk actions' }).getByRole('menuitem', { name: action }).click(); +} + +/** + * Open the filters of the table, unless they still are. + */ +async function openFilters(page: Page): Promise { + const panel = page.locator('.fi-dropdown-panel').filter({ visible: true }).filter({ has: page.getByRole('heading', { name: 'Filters' }) }); + + if (!(await panel.isVisible())) { + await page.getByRole('button', { name: 'Filter', exact: true }).click(); + } + + await expect(panel).toBeVisible(); + + return panel; +} + +/** + * Open the filters of the table, set some, and apply them. + */ +async function applyFilters(page: Page, filters: Record): Promise { + const panel = await openFilters(page); + + for (const [label, option] of Object.entries(filters)) { + const select = panel.getByRole('combobox', { name: label, exact: true }); + // By value: the labels have counts, that the tests in parallel change + const value = await select.evaluate( + (element: HTMLSelectElement, prefix: string) => [...element.options].find((choice) => choice.text.trim().startsWith(prefix))?.value ?? null, + option, + ); + expect(value, `${label}: ${option}`).not.toBeNull(); + await select.selectOption(value!); + } + + await panel.getByRole('button', { name: 'Apply filters' }).click(); + await expect(panel).toBeHidden(); + await settle(page); +} + +/** + * Sign in as the super administrator in a session of their own: impersonating changes the session, that the other + * tests share through the saved state of `adminPage`. + */ +async function ownAdminPage(browser: Browser): Promise { + const page = await (await browser.newContext({ baseURL: appURL })).newPage(); + await logIn(page, users.admin.email, users.admin.password); + await expect(page).not.toHaveURL(/\/login/); + + return page; +} + +const sidebarLink = (page: Page, name: string): Locator => + page.getByRole('navigation', { name: 'Sidebar navigation' }).getByRole('link', { name: new RegExp(`^${name}(\\s+\\d+)?$`) }); + +test.describe('Creating users', () => { + test('a new user is invited by email, chooses their password and signs in', async ({ adminPage, browser }) => { + const firstName = uniqueName('Invited'); + const email = `${firstName.toLowerCase().replaceAll(' ', '-')}@e2e.test`; + + await visit(adminPage, '/app/users'); + await adminPage.getByRole('link', { name: 'New user' }).click(); + await expect(adminPage.getByRole('heading', { name: 'Create User', level: 1 })).toBeVisible(); + + await field(adminPage, 'First Name').fill(firstName); + await field(adminPage, 'Last Name').fill('Newcomer'); + await field(adminPage, 'Email').fill(email); + // A live field: checked again if Livewire re-rendered it unchecked (the page was not ready yet) + await expect(async () => { + await adminPage.getByRole('checkbox', { name: 'Allow access' }).check(); + await expect(adminPage.getByText('They will receive an email to choose their password.')).toBeVisible({ timeout: 2_000 }); + }).toPass(); + await pickOption(adminPage, adminPage, 'Roles', 'publisher'); + await adminPage.getByRole('button', { name: 'Create', exact: true }).click(); + await expectNotification(adminPage, `An invitation to choose the password has been sent to ${email}.`); + + const created = php<{ id: number; password: string | null; roles: string[] }>(` + $user = \\App\\Models\\User::where('email', ${JSON.stringify(email)})->firstOrFail(); + + return ['id' => $user->id, 'password' => $user->password, 'roles' => $user->getRoleNames()->all()]; + `); + expect(created.password).toBeNull(); + expect(created.roles).toEqual(['publisher']); + + // Among the emails of the address: others (e.g. a new campaign) may reach it meanwhile + expect(lastMailTo(email, 'Your OCH E2E account')).not.toBeNull(); + const invitation = linkInLastMailTo(email, /\/password-reset\/reset/); + expect(invitation).toContain('invitation=1'); + + // The invited user, in a browser of their own + const invitedPage = await (await browser.newContext({ baseURL: appURL })).newPage(); + await invitedPage.goto(invitation); + await expect(invitedPage.getByRole('heading', { name: 'Choose your password' })).toBeVisible(); + const password = 'Invited-Password-2026!'; + await field(invitedPage, 'Password').fill(password); + await field(invitedPage, 'Confirm password').fill(password); + await invitedPage.getByRole('button', { name: 'Set password' }).click(); + await expectNotification(invitedPage, 'Your password has been set. You can now sign in.'); + + await logIn(invitedPage, email, password); + await expect(invitedPage).toHaveURL(/\/app\/?$/); + await expect(invitedPage.getByRole('button', { name: 'User menu' }).getByRole('img', { name: `Avatar of ${firstName} Newcomer` })).toBeVisible(); + await expect(sidebarLink(invitedPage, 'Territories')).toBeVisible(); + + await invitedPage.context().close(); + + // The invitation was used + const laterPage = await (await browser.newContext({ baseURL: appURL })).newPage(); + await laterPage.goto(invitation); + await field(laterPage, 'Password').fill('Another-Password-2026!'); + await field(laterPage, 'Confirm password').fill('Another-Password-2026!'); + await laterPage.getByRole('button', { name: 'Set password' }).click(); + await expect(laterPage.getByText('This invitation is no longer valid.', { exact: false }).first()).toBeVisible(); + await laterPage.context().close(); + }); + + test('the invitation is sent again from the list, once a minute at most', async ({ adminPage }) => { + const user = createUser({ password: null }); + + await visit(adminPage, '/app/users'); + await searchTable(adminPage, user.email); + await row(adminPage, user.email).getByRole('button', { name: 'Resend invitation' }).click(); + await expect(modal(adminPage).getByRole('heading', { name: 'Resend the invitation?' })).toBeVisible(); + await expect(modal(adminPage)).toContainText(user.email); + await confirmModal(adminPage, 'Resend invitation'); + await expectNotification(adminPage, `An invitation to choose the password has been sent to ${user.email}.`); + + expect(lastMailTo(user.email, 'Your OCH E2E account')).not.toBeNull(); + const firstLink = linkInLastMailTo(user.email, /\/password-reset\/reset/); + + await row(adminPage, user.email).getByRole('button', { name: 'Resend invitation' }).click(); + await confirmModal(adminPage, 'Resend invitation'); + await expectNotification(adminPage, /An invitation has just been sent: wait \d+ seconds/); + expect(linkInLastMailTo(user.email, /\/password-reset\/reset/)).toBe(firstLink); + }); + + test('the users who chose their password are not offered to resend the invitation', async ({ adminPage }) => { + const user = createUser(); + + await visit(adminPage, `/app/users/${user.id}`); + await expect(adminPage.getByRole('heading', { name: `View ${user.name}` })).toBeVisible(); + await expect(adminPage.locator('.fi-header').getByRole('button', { name: 'Resend invitation' })).toHaveCount(0); + }); +}); + +test.describe('Editing users', () => { + test('change the name and the roles of a user, then disable their access', async ({ adminPage }) => { + const user = createUser(); + + await visit(adminPage, `/app/users/${user.id}/edit`); + await expect(adminPage.getByRole('heading', { name: `Edit ${user.name}` })).toBeVisible(); + + const firstName = uniqueName('Renamed'); + await field(adminPage, 'First Name').fill(firstName); + await field(adminPage, 'Last Name').fill('Edited'); + await pickOption(adminPage, adminPage, 'Roles', 'group_overseer'); + await adminPage.getByRole('button', { name: 'Remove publisher' }).click(); + await adminPage.getByRole('button', { name: 'Save changes' }).click(); + await expectNotification(adminPage, 'Saved'); + + expect(userInDatabase(user.id)).toMatchObject({ first_name: firstName, last_name: 'Edited', can_login: true, roles: ['group_overseer'] }); + + // A virtual user: the roles are hidden + await adminPage.getByRole('checkbox', { name: 'Allow access' }).uncheck(); + await expect(adminPage.locator('.fi-fo-field').filter({ has: adminPage.locator('label', { hasText: labelled('Roles') }) })).toHaveCount(0); + await adminPage.getByRole('button', { name: 'Save changes' }).click(); + await expectNotification(adminPage, 'Saved'); + + expect(userInDatabase(user.id)?.can_login).toBe(false); + + await visit(adminPage, '/app/users'); + await searchTable(adminPage, firstName); + await expect(row(adminPage, firstName)).toContainText('Edited'); + await expect(row(adminPage, firstName).getByText('Can log in')).toHaveCount(0); + }); +}); + +test.describe('List of users', () => { + test('search the users and filter them by access, email verification, two-factor authentication and department', async ({ adminPage }) => { + const lastName = uniqueName('Filtered').replaceAll(' ', ''); + const virtual = createUser({ can_login: false, email_verified_at: null }, null, lastName); + const secured = createUser({ app_authentication_secret: 'JBSWY3DPEHPK3PXP' }, 'publisher', lastName); + const plain = createUser({}, 'publisher', lastName); + php(`\\App\\Models\\Department::where('key', 'publications')->first()->members()->attach(${plain.id}, ['role' => 'assistant']); return null;`); + + await visit(adminPage, '/app/users'); + await searchTable(adminPage, lastName); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(3); + + // Search by email too + await searchTable(adminPage, secured.email); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + await expect(row(adminPage, secured.firstName)).toBeVisible(); + + await searchTable(adminPage, lastName); + await applyFilters(adminPage, { Access: 'Virtual' }); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + await expect(row(adminPage, virtual.firstName)).toBeVisible(); + await expect(adminPage.locator('.fi-ta-filter-indicators')).toContainText(/virtual/i); + + await applyFilters(adminPage, { Access: 'With access', 'Two-factor authentication': 'Enabled' }); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + await expect(row(adminPage, secured.firstName)).toBeVisible(); + + await applyFilters(adminPage, { Access: 'All', 'Two-factor authentication': 'All', 'Email verified': 'Not verified' }); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + await expect(row(adminPage, virtual.firstName)).toBeVisible(); + + await applyFilters(adminPage, { 'Email verified': 'Verified' }); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(2); + + // The department filter is a searchable select + await applyFilters(adminPage, { 'Email verified': 'All' }); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(3); + const panel = await openFilters(adminPage); + await pickOption(adminPage, panel, 'Department', 'Publications', () => panel.getByRole('heading', { name: 'Filters' }).click()); + await panel.getByRole('button', { name: 'Apply filters' }).click(); + await settle(adminPage); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(1); + await expect(row(adminPage, plain.firstName)).toContainText('Publications'); + }); + + test('add the selected users to a department', async ({ adminPage }) => { + const lastName = uniqueName('Bulk').replaceAll(' ', ''); + const first = createUser({}, 'publisher', lastName); + const second = createUser({}, 'publisher', lastName); + + await visit(adminPage, '/app/users'); + await searchTable(adminPage, lastName); + await expect(adminPage.locator('.fi-ta-row')).toHaveCount(2); + + await bulkMenuAction(adminPage, [first.firstName, second.firstName], 'Add to department'); + const dialog = modal(adminPage); + await expect(dialog.getByRole('heading', { name: 'Add to a department' })).toBeVisible(); + const department = dialog.getByRole('combobox', { name: labelled('Department') }); + if (await department.count()) { + await department.selectOption({ label: 'Public Witnessing' }); + } else { + await pickOption(adminPage, dialog, 'Department', 'Public Witnessing'); + } + await dialog.getByRole('radiogroup').getByText('Assistant', { exact: true }).click(); + await confirmModal(adminPage, 'Add'); + await expectNotification(adminPage, '2 brothers added to Public Witnessing'); + + expect(userInDatabase(first.id)?.departments).toEqual(['public_witnessing:assistant']); + expect(userInDatabase(second.id)?.departments).toEqual(['public_witnessing:assistant']); + await expect(row(adminPage, first.firstName)).toContainText('Public Witnessing'); + }); +}); + +test.describe('Contacts of a user', () => { + test('create, view, edit and delete a contact of a user', async ({ adminPage }) => { + const user = createUser(); + const contactName = uniqueName('Contact'); + + await visit(adminPage, `/app/users/${user.id}/edit`); + // The contacts are loaded once scrolled into view + await adminPage.getByRole('button', { name: 'Save changes' }).scrollIntoViewIfNeeded(); + await adminPage.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await expect(adminPage.getByRole('heading', { name: 'Contact information' })).toBeVisible(); + + await adminPage.getByRole('button', { name: 'New Contact' }).click(); + let dialog = modal(adminPage); + await expect(dialog.getByRole('heading', { name: 'Create Contact' })).toBeVisible(); + await field(dialog, 'Type').selectOption({ label: 'Emergency' }); + await field(dialog, 'Name').fill(contactName); + await field(dialog, 'Phone number').fill('+39 06 1234567'); + await field(dialog, 'Address').fill('Via Roma 1, Ciampino'); + await confirmModal(adminPage, 'Create'); + await expectNotification(adminPage, 'Created'); + + await expect(row(adminPage, contactName)).toContainText('Emergency'); + expect(php(`return \\App\\Models\\User::find(${user.id})->contacts()->where('name', ${JSON.stringify(contactName)})->count();`)).toBe(1); + + await rowAction(adminPage, contactName, 'View'); + dialog = modal(adminPage); + await expect(dialog).toContainText(contactName); + await expect(dialog.getByRole('link', { name: 'Call' })).toHaveAttribute('href', 'tel:+39 06 1234567'); + const maps = dialog.getByRole('link', { name: 'Open in Maps' }); + await expect(maps).toHaveAttribute('href', 'https://www.google.com/maps/search/Via+Roma+1%2C+Ciampino'); + await expect(maps).toHaveAttribute('target', '_blank'); + await dialog.getByRole('button', { name: 'Close' }).first().click(); + + const renamed = `${contactName} renamed`; + await rowAction(adminPage, contactName, 'Edit'); + dialog = modal(adminPage); + await field(dialog, 'Name').fill(renamed); + await confirmModal(adminPage, 'Save changes'); + await expectNotification(adminPage, 'Saved'); + await expect(row(adminPage, renamed)).toBeVisible(); + + await rowAction(adminPage, renamed, 'Delete'); + await confirmModal(adminPage, 'Delete'); + await expectNotification(adminPage, 'Deleted'); + await expect(adminPage.locator('.fi-ta-row').filter({ hasText: renamed })).toHaveCount(0); + expect(php(`return \\App\\Models\\User::find(${user.id})->contacts()->count();`)).toBe(0); + }); +}); + +test.describe('Impersonation', () => { + test('the administrator impersonates a publisher from the list, then leaves', async ({ browser }) => { + const user = createUser(); + const page = await ownAdminPage(browser); + + await visit(page, '/app/users'); + await searchTable(page, user.email); + await row(page, user.email).getByRole('button', { name: 'Impersonate' }).click(); + await expect(modal(page).getByRole('heading', { name: 'Impersonate' })).toBeVisible(); + await confirmModal(page, 'Confirm'); + await page.waitForURL((url) => !url.pathname.startsWith('/app/users')); + + await visit(page, '/app'); + await expect(page.getByText('Impersonating user')).toBeVisible(); + await expect(page.getByRole('button', { name: 'User menu' }).getByRole('img', { name: `Avatar of ${user.name}` })).toBeVisible(); + await expect(sidebarLink(page, 'Territories')).toBeVisible(); + await expect(sidebarLink(page, 'Users')).toHaveCount(0); + expect((await page.context().request.get('/app/users', { maxRedirects: 0 })).status()).toBe(403); + + await visit(page, '/app'); + await page.getByRole('link', { name: 'Leave' }).click(); + await settle(page); + await visit(page, '/app'); + await expect(page.getByText('Impersonating user')).toHaveCount(0); + await expect(page.getByRole('button', { name: 'User menu' }).getByRole('img', { name: `Avatar of ${users.admin.name}` })).toBeVisible(); + await expect(sidebarLink(page, 'Users')).toBeVisible(); + + await page.context().close(); + }); + + test('the root user can be neither impersonated, edited nor deleted by the other administrators', async ({ adminPage }) => { + await visit(adminPage, '/app/users'); + await searchTable(adminPage, users.root.email); + + const root = row(adminPage, users.root.email); + await expect(root).toBeVisible(); + await expect(root.getByRole('button', { name: 'Impersonate' })).toHaveCount(0); + await expect(root.getByRole('link', { name: 'Edit' })).toHaveCount(0); + + // Another administrator can be impersonated + await searchTable(adminPage, users.servant.email); + await expect(row(adminPage, users.servant.email).getByRole('button', { name: 'Impersonate' })).toBeVisible(); + + const rootId = php(`return \\App\\Models\\User::where('email', ${JSON.stringify(users.root.email)})->value('id');`); + await visit(adminPage, `/app/users/${rootId}`); + await expect(adminPage.getByRole('heading', { name: `View ${users.root.name}` })).toBeVisible(); + const header = adminPage.locator('.fi-header'); + await expect(header.getByRole('button', { name: 'Impersonate' })).toHaveCount(0); + await expect(header.getByRole('button', { name: 'Delete' })).toHaveCount(0); + await expect(header.getByRole('button', { name: 'Transfer root' })).toHaveCount(0); + await expect(header.getByRole('link', { name: 'Edit' })).toHaveCount(0); + + expect((await adminPage.context().request.get(`/app/users/${rootId}/edit`, { maxRedirects: 0 })).status()).toBe(403); + }); +}); + +test.describe('Deleting users', () => { + test('a user who has assignments cannot be deleted, and has their access disabled instead', async ({ adminPage }) => { + const user = createUser(); + php(` + \\App\\Models\\TerritoryAssignment::factory()->create([ + 'territory_id' => \\App\\Models\\Territory::factory()->create([ + 'name' => ${JSON.stringify(uniqueName('Deletion Territory'))}, + 'territory_zone_id' => \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(uniqueName('Deletion Zone'))}])->id, + ])->id, + 'assignee_id' => ${user.id}, + 'started_at' => now()->subMonths(2), + 'ended_at' => now()->subMonth(), + ]); + + return null; + `); + + await visit(adminPage, `/app/users/${user.id}`); + await adminPage.locator('.fi-header').getByRole('button', { name: 'Delete' }).click(); + const dialog = modal(adminPage); + await expect(dialog).toContainText('Territories have been assigned to this user'); + await expect(dialog).toContainText('Disable their access instead'); + await expect(dialog.getByRole('button', { name: 'Delete' })).toHaveCount(0); + + await dialog.getByRole('button', { name: 'Disable access' }).click(); + await expectNotification(adminPage, `Access disabled: ${user.name} is now a virtual user.`); + + expect(userInDatabase(user.id)).toMatchObject({ can_login: false }); + }); + + test('a user without assignments is deleted', async ({ adminPage }) => { + const user = createUser(); + + await visit(adminPage, `/app/users/${user.id}`); + await adminPage.locator('.fi-header').getByRole('button', { name: 'Delete' }).click(); + await confirmModal(adminPage, 'Delete'); + await expectNotification(adminPage, 'Deleted'); + + await expect(adminPage).toHaveURL(/\/app\/users$/); + expect(userInDatabase(user.id)).toBeNull(); + }); +}); + +test.describe('Publication requests of a user', () => { + test('list the publications requested by the user', async ({ adminPage }) => { + const user = createUser(); + const publication = uniqueName('Requested Publication'); + php(` + \\App\\Models\\PublicationRequest::factory()->create([ + 'user_id' => ${user.id}, + 'publication_id' => \\App\\Models\\Publication::factory()->create(['name' => ${JSON.stringify(publication)}])->id, + 'quantity' => 2, + ]); + + return null; + `); + + await visit(adminPage, `/app/users/${user.id}`); + await adminPage.getByRole('link', { name: /^Publication requests/ }).click(); + + await expect(adminPage).toHaveURL(new RegExp(`/app/users/${user.id}/publication-requests$`)); + await expect(adminPage.getByRole('heading', { name: `Publication requests of ${user.name}`, level: 1 })).toBeVisible(); + await expect(row(adminPage, publication)).toContainText('2'); + await expect(row(adminPage, publication)).toContainText('Requested'); + // One request, besides the summary + await expect(adminPage.getByRole('row').filter({ hasText: 'Requested Publication' })).toHaveCount(1); + await expect(adminPage.getByRole('row').filter({ has: adminPage.getByRole('rowheader', { name: 'Summary' }) })).toContainText('Total 2'); + }); +}); diff --git a/tests/e2e/workflows.spec.ts b/tests/e2e/workflows.spec.ts new file mode 100644 index 00000000..046be01f --- /dev/null +++ b/tests/e2e/workflows.spec.ts @@ -0,0 +1,278 @@ +import type { Browser, Locator, Page } from '@playwright/test'; +import { appURL } from '../../playwright.config'; +import { php } from './support/artisan'; +import { + bulkMenuAction, + chooseOption, + confirmModal, + expectNotification, + field, + labelled, + modal, + row, + rowMenuAction, + searchTableUntilApplied, + visit, +} from './support/filament'; +import { expect, logIn, test, uniqueName, users } from './support/fixtures'; +import { linkInMailsTo } from './support/mail'; + +/** + * The whole workflows of the users, from start to end and through the pages they use, as documented in + * `docs/user-documentation/en/`: they chain the features that the other specs test one by one. + * + * Every workflow creates the records it works on, with names of its own. + */ + +test.describe.configure({ mode: 'parallel' }); + +/** The rows of the records of a table (not its individual search row). */ +const tableRows = (page: Page): Locator => page.locator('.fi-ta-row:has(.fi-ta-record-checkbox)'); + +/** A tab of the pages of a record (e.g. the territories of a zone), with its count, in the page (not the sidebar). */ +const recordTab = (page: Page, name: string): Locator => + page.getByRole('main').getByRole('link', { name: new RegExp(`^${name}( \\d+)?$`) }).first(); + +/** + * Create a user who can sign in (password `password`), with the role, returning their name and email. + */ +function createUser(role: string): { name: string; email: string } { + const firstName = uniqueName('Workflow').replace(/\s+/g, ''); + + return php(` + $user = \\App\\Models\\User::factory()->verified()->create([ + 'first_name' => ${JSON.stringify(firstName)}, + 'last_name' => 'Tester', + 'email' => strtolower(${JSON.stringify(firstName)}).'@e2e.test', + 'locale' => 'en', + ]); + $user->assignRole(${JSON.stringify(role)}); + + return ['name' => $user->full_name, 'email' => $user->email]; + `); +} + +/** + * Sign in in a browser of one's own. + */ +async function signIn(browser: Browser, email: string, password = 'password'): Promise { + const page = await (await browser.newContext({ baseURL: appURL })).newPage(); + await logIn(page, email, password); + await expect(page).not.toHaveURL(/\/login/); + + return page; +} + +/** + * Open the database notifications from the top bar, and follow the "View" link of the one with the title. + */ +async function openNotification(page: Page, title: string): Promise { + await visit(page, '/app'); + await page.getByRole('button', { name: /^Notifications/ }).click(); + const notification = page.locator('.fi-no-notification').filter({ hasText: title }).first(); + await expect(notification).toBeVisible(); + await notification.getByRole('link', { name: 'View' }).click(); +} + +test.describe('Territory workflow', () => { + test('a zone and a territory are created, then the territory is assigned, worked and returned', async ({ browser, servantPage: servant }) => { + const publisher = createUser('publisher'); + const zone = uniqueName('Workflow Zone'); + const territory = `${zone} Main Street`; + + // 1. The territory servant creates a zone… + await visit(servant, '/app/territory-zones/create'); + await field(servant, 'Name').fill(zone); + await servant.getByRole('button', { name: 'Create', exact: true }).and(servant.locator('[type="submit"]')).click(); + await expectNotification(servant, 'Created'); + await expect(servant.getByRole('heading', { level: 1 })).toContainText(zone); + + // 2. …then a territory in it, from the territories of the zone + await recordTab(servant, 'Territories').click(); + await expect(servant.getByRole('heading', { level: 1, name: `Territories of zone ${zone}` })).toBeVisible(); + await servant.getByRole('button', { name: 'New territory' }).click(); + await field(modal(servant), 'Name').fill(territory); + await chooseOption(modal(servant), 'Zone', zone); + await field(modal(servant), 'Notes').fill('Start from the church'); + await confirmModal(servant, 'Create'); + await expectNotification(servant, 'Created'); + await expect(row(servant, territory)).toBeVisible(); + + // 3. …and assigns it to a publisher, from the page of the territory + await visit(servant, '/app/territories'); + await searchTableUntilApplied(servant, territory); + await row(servant, territory).getByRole('link', { name: territory }).first().click(); + await expect(servant.getByRole('heading', { level: 1, name: `View ${territory}` })).toBeVisible(); + await servant.locator('.fi-header').getByRole('button', { name: 'Assign Territory' }).click(); + await chooseOption(modal(servant), 'Assigned to', publisher.name); + await confirmModal(servant, 'Create'); + await expectNotification(servant, 'Territory assigned'); + + // 4. The publisher is notified, opens the assignment, works the territory and asks to return it + const publisherPage = await signIn(browser, publisher.email); + await openNotification(publisherPage, `Territory ${territory} assigned`); + await expect(publisherPage).toHaveURL(/\/app\/territory-assignments\/\d+$/); + await expect(publisherPage.getByText(territory).first()).toBeVisible(); + await publisherPage.locator('.fi-header').getByRole('button', { name: 'Ask to return' }).click(); + await confirmModal(publisherPage, 'Ask to return'); + await expectNotification(publisherPage, 'Return requested'); + await publisherPage.context().close(); + + // 5. The territory servant is notified of the request, and ends the assignment + await openNotification(servant, `Return of territory ${territory} requested`); + await expect(servant.getByRole('heading', { name: /Return requested on / })).toBeVisible(); + await servant.locator('.fi-sc-callout, [class*="callout"]').filter({ hasText: 'Return requested on' }) + .getByRole('button', { name: 'End Assignment' }).click(); + await confirmModal(servant, 'End'); + await expectNotification(servant, 'Assignment returned'); + + // 6. The territory is free again, with the assignment in its history + const id = php(`return \\App\\Models\\Territory::where('name', ${JSON.stringify(territory)})->sole()->id;`); + await visit(servant, `/app/territories/${id}`); + await expect(servant.locator('.fi-header').getByRole('button', { name: 'Assign Territory' })).toBeVisible(); + expect(php(` + return \\App\\Models\\TerritoryAssignment::with('assignee')->where('territory_id', ${id})->get() + ->map(fn ($assignment) => [$assignment->assignee->full_name, $assignment->return_requested_at !== null, $assignment->ended_at !== null]) + ->all(); + `)).toEqual([[publisher.name, true, true]]); + }); +}); + +test.describe('Campaign workflow', () => { + test('a campaign is created, its territories are assigned in it, then its assignments are terminated', async ({ adminPage: admin }) => { + // Everyone is notified (and emailed) of a new campaign while it is created, which takes a while + test.slow(); + const campaign = uniqueName('Workflow Campaign'); + const zone = uniqueName('Campaign Zone'); + const territory = `${zone} Market`; + php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(zone)}]); + \\App\\Models\\Territory::factory()->for($zone)->create(['name' => ${JSON.stringify(territory)}]); + + return true; + `); + + // 1. The campaign is created, from today for two months + const day = 24 * 60 * 60 * 1000; + const dateTimeInput = (date: Date): string => date.toISOString().slice(0, 16); + await visit(admin, '/app/campaigns'); + await admin.getByRole('button', { name: 'New campaign' }).click(); + await field(modal(admin), 'Name').fill(campaign); + await field(modal(admin), 'Short Name').fill('WF'); + await field(modal(admin), 'Valid From').fill(dateTimeInput(new Date(Date.now() - day))); + await field(modal(admin), 'Valid Until').fill(dateTimeInput(new Date(Date.now() + 60 * day))); + await confirmModal(admin, 'Create'); + await expect(admin.locator('.fi-modal-window').filter({ hasText: 'Create Campaign' })).toBeHidden({ timeout: 150_000 }); + await expectNotification(admin, 'Created'); + + // 2. A territory is assigned in the campaign, with the wizard of its assignments + await searchTableUntilApplied(admin, campaign); + await expect(row(admin, campaign)).toContainText('Active'); + await row(admin, campaign).getByRole('link', { name: campaign }).first().click(); + await recordTab(admin, 'Assignments').click(); + await admin.getByRole('button', { name: 'New territory assignment' }).click(); + const wizard = modal(admin); + await chooseOption(wizard, 'Territory', territory); + await chooseOption(wizard, 'Assigned to', users.group.name); + await wizard.getByRole('button', { name: 'Next' }).click(); + await wizard.getByRole('button', { name: 'Next' }).click(); + await expect(wizard).toContainText(campaign); + await wizard.getByRole('button', { name: 'Create', exact: true }).click(); + await expectNotification(admin, 'Created'); + await expect(tableRows(admin)).toHaveCount(1); + await expect(row(admin, territory)).toContainText(users.group.name); + + // 3. The territory shows the campaign of its assignment + const territoryId = php(`return \\App\\Models\\Territory::where('name', ${JSON.stringify(territory)})->sole()->id;`); + await visit(admin, '/app/territories'); + await searchTableUntilApplied(admin, territory); + await expect(row(admin, territory)).toContainText(users.group.name); + + // 4. At the end of the campaign, its assignments are terminated + await visit(admin, '/app/campaigns'); + await searchTableUntilApplied(admin, campaign); + await row(admin, campaign).getByRole('link', { name: campaign }).first().click(); + await recordTab(admin, 'Assignments').click(); + await bulkMenuAction(admin, [territory], 'Terminate assignments'); + await confirmModal(admin, 'Terminate'); + await expectNotification(admin, 'Assignments terminated'); + await expect(tableRows(admin)).toHaveCount(0); + + expect(php(` + $assignment = \\App\\Models\\TerritoryAssignment::with('campaign')->where('territory_id', ${territoryId})->sole(); + + return [$assignment->campaign->name, $assignment->ended_at !== null]; + `)).toEqual([campaign, true]); + }); +}); + +test.describe('Onboarding workflow', () => { + test('a group overseer is invited, chooses their password, signs in and assigns a territory', async ({ adminPage: admin, browser }) => { + const firstName = uniqueName('Overseer').replace(/\s+/g, ''); + const email = `${firstName.toLowerCase()}@e2e.test`; + const zone = uniqueName('Group Zone'); + const territory = `${zone} Park Avenue`; + php(` + $zone = \\App\\Models\\TerritoryZone::factory()->create(['name' => ${JSON.stringify(zone)}]); + \\App\\Models\\Territory::factory()->for($zone)->create(['name' => ${JSON.stringify(territory)}]); + + return true; + `); + + // 1. The administrator creates the user, with the group overseer role and access to the app + await visit(admin, '/app/users/create'); + await field(admin, 'First Name').fill(firstName); + await field(admin, 'Last Name').fill('Group'); + await field(admin, 'Email').fill(email); + // A live field: checked again if Livewire re-rendered it unchecked (the page was not ready yet) + await expect(async () => { + await admin.getByRole('checkbox', { name: 'Allow access' }).check(); + await expect(admin.getByText('They will receive an email to choose their password.')).toBeVisible({ timeout: 2_000 }); + }).toPass(); + await admin.locator('.fi-fo-field').filter({ has: admin.locator('label', { hasText: labelled('Roles') }) }) + .locator('.fi-select-input-btn').click(); + await admin.getByRole('option', { name: 'group_overseer', exact: true }).filter({ visible: true }).first().click(); + await admin.keyboard.press('Escape'); + await admin.getByRole('button', { name: 'Create', exact: true }).click(); + await expectNotification(admin, `An invitation to choose the password has been sent to ${email}.`); + + // 2. The new user follows the link of the invitation and chooses a password + const password = 'Workflow-Password-2026!'; + // Searched among the emails of the address: other emails (e.g. a new campaign) may have reached it since + let invitation: string | null = null; + await expect.poll(() => (invitation = linkInMailsTo(email, /\/password-reset\/reset/))).not.toBeNull(); + const invited = await (await browser.newContext({ baseURL: appURL })).newPage(); + await visit(invited, invitation!); + await expect(invited.getByRole('heading', { name: 'Choose your password' })).toBeVisible(); + await field(invited, 'Password').fill(password); + await field(invited, 'Confirm password').fill(password); + // Clicked again if the first click was lost (sent before the form was ready): the password is not set then + await expect(async () => { + await invited.getByRole('button', { name: 'Set password' }).click(); + await expect(invited.locator('.fi-no-notification').filter({ hasText: 'Your password has been set. You can now sign in.' }).first()) + .toBeVisible({ timeout: 10_000 }); + }).toPass({ timeout: 40_000 }); + await invited.context().close(); + + // 3. They sign in, and assign a territory to a publisher of their group + const overseer = await signIn(browser, email, password); + await visit(overseer, '/app/territories'); + await searchTableUntilApplied(overseer, territory); + await rowMenuAction(overseer, territory, 'Assign Territory'); + await chooseOption(modal(overseer), 'Assigned to', users.publisher.name); + await confirmModal(overseer, 'Create'); + await expectNotification(overseer, 'Territory assigned'); + + // 4. The assignment is listed among the assignments, created by them + await visit(overseer, '/app/territory-assignments'); + await searchTableUntilApplied(overseer, territory); + await expect(row(overseer, territory)).toContainText(users.publisher.name); + expect(php(` + $assignment = \\App\\Models\\TerritoryAssignment::with('assignee', 'creator') + ->whereHas('territory', fn ($query) => $query->where('name', ${JSON.stringify(territory)}))->sole(); + + return [$assignment->assignee->email, $assignment->creator->email]; + `)).toEqual([users.publisher.email, email]); + await overseer.context().close(); + }); +});