diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..828c4bd --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +.git +.github +.dart_tool +build +android +ios +macos +linux +windows +docs +test +backend.Tests +backend/bin +backend/obj +backend/wwwroot +**/bin +**/obj diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..cbbb0eb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,33 @@ +name: Bug report +description: Something does not work, looks wrong, or is confusing +labels: [bug] +body: + - type: textarea + id: what + attributes: + label: What happened + description: What you did, what you expected, and what you saw instead. + validations: + required: true + - type: dropdown + id: where + attributes: + label: Where + options: + - Phone layout + - Printer panel layout + - Administrator screen + - Sign-in + - Server or API + - Hosting + validations: + required: true + - type: input + id: setup + attributes: + label: Device, browser and text size + placeholder: "Phone, Chrome, text size larger than normal" + - type: textarea + id: shot + attributes: + label: Screenshot or message shown diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..43b0abb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security problem privately + url: https://github.com/Hikki-dev/pull_printing_app/security/advisories/new + about: Please do not open a public issue for security problems. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..50849d8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,15 @@ +name: Idea or improvement +description: Something that would make the demo or the product better +labels: [enhancement] +body: + - type: textarea + id: problem + attributes: + label: What problem would this solve, and for whom + description: Describe the person and the moment, not the solution. + validations: + required: true + - type: textarea + id: idea + attributes: + label: What you have in mind diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..fd17276 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,21 @@ +## What this changes + + + +## How it was checked + + + +- [ ] `dotnet test backend.Tests` +- [ ] `flutter analyze --no-fatal-infos` and `flutter test` +- [ ] Tried it in a browser or on a device + +## Not checked + + + +## Checklist + +- [ ] Rules about who may do what are enforced by the server, with a test +- [ ] New or changed screens work at 1.5 and 2 times text size +- [ ] Docs in `docs/` and `CHANGELOG.md` updated if behaviour changed diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..07dbe21 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + push: + pull_request: + +jobs: + backend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + - run: dotnet test backend.Tests + + frontend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + - run: flutter pub get + - run: flutter analyze --no-fatal-infos + - run: flutter test + + docker: + # Builds the image the way a host would, then starts it and checks it answers. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: docker build -t pull-print-demo . + - name: Start the image and check it + run: | + docker run -d --name pp -p 8080:8080 pull-print-demo + for i in $(seq 1 30); do curl -fs http://localhost:8080/healthz && break; sleep 2; done + curl -fs http://localhost:8080/healthz + curl -fs http://localhost:8080/ | grep -q "Pull Print demo" + curl -fs -X POST -H 'content-type: application/json' -d '{"admin":false}' \ + http://localhost:8080/api/auth/demo-login | grep -q '"token"' + test "$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/api/jobs/held)" = "401" + - if: failure() + run: docker logs pp diff --git a/.gitignore b/.gitignore index 79c113f..785a3fe 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,8 @@ app.*.map.json /android/app/debug /android/app/profile /android/app/release + +# .NET +**/bin/ +**/obj/ +backend/wwwroot/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..702f0c9 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,43 @@ +# Changelog + +All notable changes. Newest first. + +## Unreleased (pull request #1) + +### Added +- **Work-account sign-in.** People sign in with their Microsoft 365 or Google Workspace account. The server does the sign-in, only lets in people from your organisation, adds them on first sign-in, and decides who is an administrator. +- **Printers and quotas managed on the server.** Administrators add, switch off and remove printers, set pages a month for new people, for everyone or for one person, and see a setup check that names anything still to do. Pages start again each month. +- A printer picker on the phone, and printer panels fixed to one printer by their address (`?printer=`). +- `docs/09-connecting-your-workspace.md`: the ten-minute setup for Microsoft and Google. +- A new README and guides with pictures of every screen taken from the running app (`docs/Getting%20started.md`, `docs/Fixing%20problems.md`), two diagrams, a short demo GIF, and `tools/screenshots/` to make them again. +- Phone and printer-panel screens: sign in, choose documents, print, confirmation, administrator view. +- A working .NET 8 backend with protected routes, quota checks on the server, and private demo sandboxes. +- Demo banner and "What is this?" dialog on every screen, sample documents on demand, and **Start over**. +- Select all and Clear, plain messages for a long document and for no pages left, partial-print notice. +- The printer panel signs out after 60 seconds without a touch. +- Static hosting on Vercel (`vercel.json`, `scripts/vercel-build.sh`) and a `Dockerfile` and `render.yaml` for the full stack. +- A branded loading screen, page title, description, icons and manifest for the web build. +- Design documents, mockups, an architecture and API reference, and a review record in `docs/`. +- CI for the backend, the app, and the Docker image. +- 112 backend tests and 64 app tests, including a simulated Microsoft/Google sign-in. + +### Changed +- `PullPrintingBackend.csproj` is no longer empty; the backend builds. +- Routes match what the app calls. `POST /api/jobs/release` takes `jobIds` and returns what really printed. +- The app uses the server's answer about what printed, and refreshes a stale list. + +### Fixed +- Sign in button pushed off screen at large text sizes and on short phones. +- Overflows at 1.5 and 2 times text size. +- A demo administrator could see every visitor's documents. +- Unexpected server errors, missing security headers, and unbounded request sizes. + +### Removed +- The MSAL wrapper (`msal_flutter`, `MsAuthService.dart`) and the `AUTH_MODE` and `MS_SCOPE` build settings. Sign-in no longer needs anything in the app. +- The `AzureAd__*` settings, replaced by `Workspace__*`. `Demo__SigningKey` is now `Auth__SigningKey` (the old name still works). +- Windows-only printing code (`System.Printing`), replaced by `IPrintDispatcher` with a simulated implementation. +- The mock JSON server data (`frontend/db.json`). + +## Before this + +An early prototype: screens and an API shape that were not connected, and a backend that did not build. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9a01518 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,46 @@ +# Contributing + +Thanks for helping. This is a small project, so the process is light. + +## Get set up + +You need the [Flutter SDK](https://docs.flutter.dev/get-started/install) and the [.NET 8 SDK](https://dotnet.microsoft.com/download). + +```bash +flutter pub get +flutter run -t frontend/lib/main.dart # the app on built-in sample data + +dotnet run --project backend # the API (ASPNETCORE_ENVIRONMENT=Development turns demo sign-in on) +``` + +The README has the full list of ways to run it, and [`docs/How%20it%20works.md`](docs/How%20it%20works.md) explains how the pieces fit. + +## Before you open a pull request + +Run what CI runs: + +```bash +dotnet test backend.Tests +flutter analyze --no-fatal-infos +flutter test +``` + +There are 64 app tests and 112 backend tests. + +- **Add a test with every behaviour change.** Server rules go in `backend.Tests`; screens and the API client go in `test/`. +- **Check large text.** `test/widget_test.dart` runs the phone screens at 1.5 and 2 times text size and fails on any overflow. New screens should be added there. +- **Keep the server in charge.** The app only shows things; any rule about who may do what belongs in the backend, with a test. +- **Match the style around you.** Run `dart format` on Flutter code you touch. +- **Wording is part of the design.** Use the plain words in [`docs/03-screen-specs.md`](docs/03-screen-specs.md#wording), and keep messages saying what to do next. +- **No stock or generated imagery, no emoji.** See [`docs/04-design-guidelines.md`](docs/04-design-guidelines.md). + +## Pull requests + +- One change per pull request, with a description that says what changed, why, and how you checked it. +- Say what you did **not** check. +- Update the docs in `docs/` and `CHANGELOG.md` when behaviour changes. +- If a screen changed, take its pictures again: [`tools/screenshots`](tools/screenshots/README.md) explains how. Pictures come from the running app, never from a mock-up. + +## Reporting problems + +Use the issue templates. For anything security related, read [SECURITY.md](SECURITY.md) first. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b6b828d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,31 @@ +# One image that serves both the web app and the API, for a free demo host. +# Build: docker build -t pull-print-demo . +# Run: docker run -p 8080:8080 pull-print-demo then open http://localhost:8080 + +# 1) The web app (Flutter), built to talk to the API on the same address. +FROM ghcr.io/cirruslabs/flutter:stable AS web +WORKDIR /src +COPY pubspec.yaml pubspec.lock .metadata ./ +COPY frontend ./frontend +COPY web ./web +RUN flutter pub get +RUN flutter build web -t frontend/lib/main.dart --release --no-web-resources-cdn \ + --dart-define=USE_MOCK=false + +# 2) The API (ASP.NET Core). +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS api +WORKDIR /src +COPY backend ./backend +RUN dotnet publish backend -c Release -o /out + +# 3) Run both together: the API serves the web app from wwwroot. +FROM mcr.microsoft.com/dotnet/aspnet:8.0 +WORKDIR /app +COPY --from=api /out . +COPY --from=web /src/build/web ./wwwroot +ENV ASPNETCORE_ENVIRONMENT=Production \ + Demo__Enabled=true +USER $APP_UID +EXPOSE 8080 +# Hosts such as Render tell the app which port to use through PORT. +CMD ["sh", "-c", "ASPNETCORE_URLS=http://0.0.0.0:${PORT:-8080} exec dotnet PullPrintingBackend.dll"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e163f27 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Pull Print contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index d2d13a0..61a212f 100644 --- a/README.md +++ b/README.md @@ -1,122 +1,309 @@ -# pull_printing_app - -A **secure pull-printing** system prototype. A user sends a document to print, the server **holds** it, and it only prints when the user walks up to a printer, signs in and releases it. Built with a **Flutter** client and a **.NET (ASP.NET Core)** backend, with **Microsoft Entra ID (Azure AD)** for identity. +# Pull Print +[![CI](https://github.com/Hikki-dev/pull_printing_app/actions/workflows/ci.yml/badge.svg)](https://github.com/Hikki-dev/pull_printing_app/actions/workflows/ci.yml) ![Flutter](https://img.shields.io/badge/Flutter-3.x-02569B?logo=flutter&logoColor=white) -![.NET](https://img.shields.io/badge/.NET-ASP.NET%20Core-512BD4?logo=dotnet&logoColor=white) -![Status](https://img.shields.io/badge/status-prototype-orange) +![.NET](https://img.shields.io/badge/.NET-8-512BD4?logo=dotnet&logoColor=white) +[![Live demo](https://img.shields.io/badge/live-demo-0B5CAD)](https://pull-print-demo.vercel.app) +![Status](https://img.shields.io/badge/status-working%20demo-orange) +[![Licence: MIT](https://img.shields.io/github/license/Hikki-dev/pull_printing_app)](LICENSE) + +Send a document to print. It waits safely on a server. It only prints when you walk up to a printer, sign in with your work account and press **Print**. Printers and every person's page limit are managed from one screen. -> **Status: early prototype.** The screens and API shape exist, but the pieces are not wired together yet and the backend does not build. Read [Current status](#current-status) before relying on any part of it. +

A short walk through on a phone: sign in, two documents are ticked, the third would go over the page limit, then Print and the confirmation

-## About +

A short walk through on a phone. Try it yourself. It runs on sample data, so nothing is really printed and no account is needed.

-An app that runs against a server and uses Azure to get the user's login details. When someone prints, the server keeps the job on hold until they go to the printer, sign in with the required credentials, and release it. They only ever see and print **their own** documents. +You do not need to know how any of it works. Every screen says in plain words what to do next. -## How it works +## On this page -1. A user sends a file to print, in the format they choose, from anywhere in the company (any floor). -2. The server stores the job as **Held**. Nothing prints yet. -3. At the printer the user signs in with their Azure credentials (card login is the intended next step). -4. A screen shows **only their held jobs**. They press print on the ones they want. -5. The job prints and their print quota goes down by one. An admin can set quotas. +* [What you get](#what-you-get) +* [How everything fits together](#how-everything-fits-together): one document, from sending to paper +* [Try it first](#try-it-first): the live demo, no account needed +* [Use it with your own accounts](#use-it-with-your-own-accounts): Microsoft 365 or Google Workspace +* [The screens, step by step](#the-screens-step-by-step) + * [1. Sign in](#1-sign-in) + * [2. Choose what to print](#2-choose-what-to-print) + * [3. Print](#3-print) + * [At the printer's own screen](#at-the-printers-own-screen) + * [For administrators](#for-administrators) + * [Signing in with a work account](#signing-in-with-a-work-account) +* [Run it yourself](#run-it-yourself) and [host it for free](#host-it-for-free) +* [Your privacy and safety](#your-privacy-and-safety) +* [The API in one table](#the-api-in-one-table) +* [Limits](#limits) and [roadmap](#roadmap) +* [Help and more reading](#help-and-more-reading) -## Features +## What you get -| Feature | Where | State | +| | | | |---|---|---| -| Sign in with Microsoft | `frontend/lib/screens/login_screen.dart`, `services/MsAuthService.dart` | UI done, sign-in does not complete yet (see status) | -| List my held jobs and release one | `frontend/lib/screens/release_jobs_screen.dart` | UI done | -| Admin dashboard listing all jobs | `frontend/lib/screens/admin_dashboard_screen.dart` | UI done, not reachable from login | -| Quota indicator and job cards | `frontend/lib/widgets/` | Done | -| Release endpoint with quota check | `backend/controllers/JobsController.cs` | Written | -| Admin set-quota endpoint | `backend/controllers/AdminController.cs` | Written | -| Print to a Windows queue | `backend/services/PrintService.cs` | Written (Windows only) | +| **A phone and printer screen** | Sign in, see only your own documents, tick what you want, press Print | [Screens](#the-screens-step-by-step) | +| **Page limits that cannot be skipped** | Checked on the server. Going over blocks Print and says by how many pages | [Choose what to print](#2-choose-what-to-print) | +| **Work-account sign-in** | Microsoft 365 or Google Workspace. Only your organisation gets in | [Work accounts](#signing-in-with-a-work-account) | +| **One place to manage everything** | Add printers, set pages a month for one person or everyone, see what is still to set up | [Administrators](#for-administrators) | +| **Printer screens fixed to one printer** | Open a printer's link on its own screen and it prints there | [Printer's own screen](#at-the-printers-own-screen) | +| **A free demo** | Every visitor gets private sample documents | [Try it first](#try-it-first) | -## Architecture +## How everything fits together -``` -Flutter app (frontend/) ASP.NET Core API (backend/) - LoginScreen ── MsAuthService (MSAL) AuthController POST /api/auth/login - ReleaseJobsScreen ──┐ JobsController GET /api/jobs - AdminDashboardScreen ┴── ApiService ─HTTP─▶ POST /api/jobs/release - AdminController POST /api/admin/set-quota - │ - AzureAuthService · UserService · PrintService - └─ System.Printing queue -``` +Send once, walk up, sign in, press Print. The server holds the document until then, and decides who may do what. -### Data models +

Diagram: a person sends a document, the Pull Print server holds it, at the printer's screen the person signs in and presses Print, the server checks their pages and sends it to the printer. Microsoft 365 or Google Workspace proves who the person is

-- `User`: `Id`, `DisplayName`, `Email`, `IsAdmin`, `PrintQuota` -- `PrintJob`: `Id`, `UserId`, `FileName`, `IsReleased`, `SubmittedAt` -- `Quota`: `UserId`, `RemainingQuota` +The whole story, including who decides what, is in [How it works](docs/How%20it%20works.md). -### Backend API +## Try it first -| Method | Route | Purpose | -|---|---|---| -| `POST` | `/api/auth/login` | Body is a token string. 200 if valid, 401 otherwise | -| `GET` | `/api/jobs` | List jobs | -| `POST` | `/api/jobs/release` | Release a job. 403 when the user's quota is 0, otherwise prints and decrements the quota | -| `POST` | `/api/admin/set-quota` | Body `{ "userId", "quota" }` | +**Live demo: ** (runs entirely in your browser on built-in sample data). -## Repository layout +* Press **Sign in with Microsoft**. In the demo that signs you in to a private sandbox as "Alice Tan". No account is needed. +* You start with four sample documents and 38 of 50 pages left. +* Tick the documents you want and press **Print**. Tick too many and Print switches off and says by how many pages. +* Printing does not use a real printer. It marks the documents as printed and uses up pages. +* **Demo: sign in as administrator** shows every job and lets you manage printers and page limits, on a private copy of sample people. +* A banner on every screen says it is a demo, and **What is this?** explains it in plain words. It also has **Start over**. +* Other visitors never see your documents. -``` -frontend/lib/ Flutter source: main.dart, screens, services, models, widgets -frontend/db.json Sample held and released jobs for a mock JSON API -backend/ ASP.NET Core API: controllers, services, models, data -android/ ios/ web/ macos/ linux/ windows/ Flutter platform folders -pubspec.yaml Flutter dependencies (repo root) -``` +## Use it with your own accounts -The Flutter entry point is **`frontend/lib/main.dart`**, not `lib/main.dart`. +Run the server with your Microsoft 365 or Google Workspace details and people sign in with the work account they already have. You add printers once, and set pages a month for one person or everyone, from one screen. Step by step, about ten minutes: **[Connecting your workspace](docs/09-connecting-your-workspace.md)**. + +> Tested against a simulated Microsoft/Google sign-in only. It has not been run against a real tenant yet, so try it on a test tenant first ([issue #2](https://github.com/Hikki-dev/pull_printing_app/issues/2)). + +## The screens, step by step + +Every picture below was taken from the running app. Click one to see it full size. [Getting started](docs/Getting%20started.md) walks through the same screens with more detail, and [how the pictures are made](tools/screenshots/README.md) is explained if you want to refresh them. + +### 1. Sign in + +

Phone sign-in screen: a printer picture, the heading Print now, collect at any printer, three steps and a Sign in with Microsoft button

+ +One button. There is no registration and no password field: the person signs in with their work account. In the demo the same button opens a private sandbox, and the banner at the top says so. + +

The About this demo dialog explaining that nothing is really printed

+ +### 2. Choose what to print + +

The person's waiting documents with the first two ticked, a ring showing 38 pages left, and a Print 2 documents, 15 pages button

+ +Only the person's own documents are listed, newest first. The newest ones are ticked for them, stopping before anything would go over their limit. The ring shows the pages left this month. + +Tick a document that is too big, and Print switches off and says what to do: + +

Three documents ticked, 43 pages. The button is grey and says Over your limit by 5 pages. Untick one.

+ +If more than one printer is set up, tap the printer name at the bottom to choose where to print: + +

A list of three printers with their places, Level 3 East ticked

+ +### 3. Print + +

Confirmation: Printing at Reception, the two documents with their pages, and 23 of 50 pages left this month

+ +The confirmation names the printer, lists what printed, and shows the pages left. If the printer rejects some documents, they are named and stay on the list. Nothing is charged for a document that did not print. + +### At the printer's own screen + +Open a printer's **panel link** on the screen next to it, in full screen. It is fixed to that printer, so there is no question about where to print. It signs the person out after 60 seconds without a touch, and 20 seconds after printing, so the next person never sees their documents. + +

The printer screen sign-in: Sign in with your work account, and a Tap your staff card option marked Coming later

+ +

The printer screen showing the person's documents as large cards, the printer name Level 3 East and 38 pages left at the top, and a large Print button

+ +

The printer screen after printing: Printing 15 pages, with the pages left this month

+ +Staff-card sign-in and a phone-code sign-in are drawn in the mockups but not built yet ([issue #6](https://github.com/Hikki-dev/pull_printing_app/issues/6)). + +### For administrators + +Everything an administrator needs is on one screen, in the order they need it. + +

The administrator screen: a Setup is complete card, four counts, and the Printers list

+ +**Setup.** The first card says **Setup is complete**, or **Finish setting up** with each thing still to do in plain words. For a Microsoft or Google set-up it also shows the exact sign-in address to register, with a **Copy** button. + +

The setup card saying Finish setting up, with the line No printers yet. Add one so people can print.

+ +

The setup card listing two things to do, and the sign-in address to register with Google, with a Copy button

+ +**Printers.** Add, rename, switch off and remove printers. **Copy panel link** gives the address to open on that printer's own screen. + +

The Printers list: Level 3 East, Print room and Reception, each with an on switch, Copy panel link, edit and remove

-## Running the Flutter app +

The Add a printer dialog with a name and an optional place

+ +**People and quotas.** **New people start with** sets the pages a month for anyone who signs in from now on. **Give everyone** sets one number for the whole organisation (it asks first, because it replaces every limit). Each person also has their own row. People appear here the first time they sign in. Pages start again on the 1st of every month. + +

People and quotas: a default for new people, a box to give everyone the same pages, and a row per person with a bar and a Save button. Bob Reyes shows 50 of 50, none left.

+ +

The confirmation Give everyone 75 pages a month? with Cancel and Apply to everyone

+ +**All jobs.** Every job with a search box and a status filter. A failed job says why. + +

The All jobs table with the user, document, pages, when it was sent and its status

+ +### Signing in with a work account + +When the server is set up for Microsoft 365 or Google Workspace, the sign-in button changes to match, and says who can use it. + + + + + + + + +
Phone sign-in with a Sign in with Google button and the line Use your @example.com accountPhone sign-in with a Sign in with Microsoft button and the line Use your work accountPhone sign-in with a Google button and a Try the demo instead link
Google WorkspaceMicrosoft 365With the demo still on
+ +Someone who is not allowed in sees the reason, and can try again: + +

The sign-in screen with a red box: That account is not allowed here. Sign in with your work account.

+ +What happens behind the button: + +

Six steps: press Sign in, sent to the provider, sign in there, the server checks, added if new, back in the app. A person who is not allowed sees the reason.

+ +## Run it yourself + +You need the [Flutter SDK](https://docs.flutter.dev/get-started/install) and the [.NET 8 SDK](https://dotnet.microsoft.com/download). ```bash git clone https://github.com/Hikki-dev/pull_printing_app.git cd pull_printing_app + +# Just the app, on built-in sample data. No server needed. flutter pub get flutter run -t frontend/lib/main.dart + +# The whole thing: API plus app, the way the hosted demo runs. +flutter build web -t frontend/lib/main.dart --dart-define=USE_MOCK=false +mkdir -p backend/wwwroot && cp -r build/web/. backend/wwwroot/ +ASPNETCORE_ENVIRONMENT=Development dotnet run --project backend # then open the address it prints + +# The app against an API running somewhere else (for example flutter run -d chrome) +flutter run -d chrome -t frontend/lib/main.dart \ + --dart-define=USE_MOCK=false --dart-define=API_BASE_URL=http://localhost:5000/api ``` -- `ApiService` calls `http://localhost:3000` with `GET /jobs`, `GET /jobs/held` and `POST /jobs/release`. Point it at your API, or at a mock server fed by `frontend/db.json`. -- `frontend/lib/utils/constants.dart` holds an `apiBaseUrl` (default `http://localhost:5000/api`), but `ApiService` does not use it yet. +Run the tests with `flutter test` (64) and `dotnet test backend.Tests` (112). + +Screens narrower than 760 px use the phone layout, wider ones the printer-panel layout. -## Azure AD setup +### Host it for free -1. In the Azure portal, register an application in **Microsoft Entra ID**. -2. Add a **Mobile and desktop** redirect URI of the form `msal://auth`. -3. Add the delegated permission `User.Read`. -4. Put your tenant and client ID in `frontend/lib/services/MsAuthService.dart` and `backend/services/AzureAuthService.cs`. Both currently contain placeholder or sample values. +Two ways, both described in [Hosting the demo](docs/06-demo-hosting.md): -## Current status +* **Static, no server (what the live demo uses).** `vercel.json` and `scripts/vercel-build.sh` build the app on built-in sample data. Connect the repository to a Vercel project. +* **Full stack.** A `Dockerfile` builds the web app and the API into one image, and `render.yaml` deploys it on Render's free plan: create a free account, choose **New, Blueprint**, and pick this repository. -Known gaps, in rough priority order: +To use real accounts instead of the demo, follow [Connecting your workspace](docs/09-connecting-your-workspace.md). -1. **`backend/PullPrintingBackend.csproj` is empty**, so `dotnet build` fails. It needs a `Microsoft.NET.Sdk.Web` project that references `Microsoft.Identity.Client`. -2. **Sign-in never completes.** `MsAuthService.init()` is never called, so the MSAL client is not created when `login()` runs, the error is caught and the user sees "Login failed.". -3. **`AzureAuthService.ValidateToken` always returns `true`.** Real JWT validation against your tenant is required before this is exposed anywhere. -4. **Endpoints are not protected.** `AdminController` and `JobsController` have no authorization, and the user id comes from the request body. -5. **State is in memory.** Jobs and users live in lists and reset on restart. `ApplicationDbContext` is an empty placeholder. -6. **Frontend and backend do not match.** The app calls `localhost:3000/jobs`, `/jobs/held`, `/jobs/release`, while the .NET API exposes `/api/jobs` and `/api/jobs/release`, and has no "my held jobs" route. -7. **The admin dashboard uses a placeholder token** (`'your_token_here'`) and is not linked from the login flow. -8. **No job submission path.** Nothing creates a held job yet. -9. **Printing is Windows only.** `PrintService` uses `System.Printing`. -10. **Duplicate MSAL wrappers.** `MsAuthService.dart` and `msal_flutter.dart` (`MsalService`) overlap. Keep one. -11. **Tests are the Flutter template.** `test/widget_test.dart` still expects the counter app. +### Repository layout + +``` +frontend/lib/ Flutter source: main.dart, screens, services, models, widgets, utils +backend/ ASP.NET Core API: controllers, services, models +backend.Tests/ API, store and sign-in tests (with a simulated Microsoft/Google) +test/ Flutter tests +tools/screenshots/ Takes every picture in these docs from the running app +scripts/ Build script for static hosting +docs/ Guides, design documents, pictures and mockups +Dockerfile One image with the API and the web app +render.yaml One-click free hosting on Render +.github/workflows/ CI: backend tests, Flutter tests, and the Docker image +CONTRIBUTING.md SECURITY.md CHANGELOG.md +``` + +The Flutter entry point is **`frontend/lib/main.dart`**, not `lib/main.dart`. + +## Your privacy and safety + +* **Every route except sign-in and `/healthz` needs a valid token.** Tokens are signed by the server and checked on every request. Admin routes need the Admin role. +* **People only reach their own data.** Printing ignores any document that is not yours and waiting. Administrators only see and change people in their own group. +* **Work accounts** sign in on Microsoft's or Google's own page. Pull Print never sees a password, only your organisation gets in, and the client secret stays on the server. +* **The demo** is limited to 20 sign-ins a minute per address, at most 300 sandboxes exist at once, and each is deleted after 2 hours without use. Switch it off for anything real (`Demo__Enabled=false`): its tokens stop working immediately. +* **Data is in memory** and is lost when the server restarts (see [Limits](#limits)). + +To report a security problem, read [SECURITY.md](SECURITY.md). + +## The API in one table + +All routes except sign-in and health need `Authorization: Bearer `. + +| Method | Route | Who | What it does | +|---|---|---|---| +| `GET` | `/api/auth/config` | anyone | Which sign-in to offer: `{ provider, providerName, domain, demo }` | +| `POST` | `/api/auth/demo-login` | anyone, demo only | Creates a private sandbox and returns a token. Body `{ "admin": false }`. 404 unless `Demo__Enabled` is true | +| `GET` | `/api/auth/login` | anyone, work accounts only | Sends the browser to Microsoft or Google. `?returnTo=/path` says where to come back to. 404 unless work sign-in is set up | +| `GET` | `/api/auth/me` | signed in | Name and role from the token | +| `GET` | `/api/printers` | signed in | The printers people can use (administrators also see switched-off ones) | +| `GET` | `/api/jobs/held` | signed in | Your waiting documents, newest first | +| `GET` | `/api/jobs/quota` | signed in | `{ used, total, left }` pages | +| `POST` | `/api/jobs/release` | signed in | Body `{ "jobIds": [...], "printerId": "..." }`. 200 with what printed and where, 409 `quota_exceeded` with `pagesOver`, 409 `no_printer` or `printer_unavailable`, 404 if none of them are yours and waiting, 400 if empty | +| `POST` | `/api/jobs/sample` | signed in, demo only | Adds one sample document to your list | +| `GET` | `/api/jobs` | administrator | Every job in the administrator's own group | +| `GET` | `/api/admin/setup` | administrator | How the server is set up and anything still to do, plus the address to register with Microsoft or Google | +| `GET` | `/api/admin/users` | administrator | People in the administrator's group with their quotas | +| `POST` | `/api/admin/set-quota` | administrator | Body `{ "userId", "quota" }`, 0 to 10000 pages | +| `POST` | `/api/admin/default-quota` | administrator | Body `{ "quota" }`. Pages a month for people who sign in from now on | +| `POST` | `/api/admin/set-quota-all` | administrator | Body `{ "quota" }`. Gives everyone the same pages, returns `{ "changed" }` | +| `POST` `PUT` `DELETE` | `/api/admin/printers`, `/api/admin/printers/{id}` | administrator | Add, change (name, place, on or off) and remove printers | +| `GET` | `/healthz` | anyone | `{ "status": "ok" }` | + +## Limits + +This is a demo, so on purpose: + +1. **Data lives in memory.** Everything resets when the server restarts, and demo sandboxes are deleted after 2 hours without use. A database would replace `PrintStore` (it sits behind `IPrintStore`). +2. **Nothing is really printed.** `SimulatedPrintDispatcher` only logs. A real printer integration implements `IPrintDispatcher`. +3. **No way to send a file yet.** The demo makes sample documents. Real submission (a print driver, email-to-print or upload) is an open decision, see `docs/05-open-decisions.md`. +4. **Work-account sign-in is untested** against a real Microsoft or Google tenant. Sign-in runs in the browser, so a printer panel needs a browser in kiosk mode. +5. **Free hosts sleep.** The first visit after a quiet period can take a minute to wake the server. +6. **Placeholders to replace:** the Pull Print mark, the printer illustration, drawn document thumbnails and the drawn Microsoft and Google marks (use their own assets). See `docs/04-design-guidelines.md`. +7. **Not built:** staff-card sign-in and the phone code sign-in screen from the mockups. +8. **People, printers and quotas are lost on restart** until a database backs `IPrintStore`, and quotas are per person (no groups yet). ## Roadmap -- [ ] Fill in the `.csproj` and get `dotnet run` working -- [ ] Call `MsAuthService.init()` and complete Microsoft sign-in -- [ ] Validate Entra ID tokens and add `[Authorize]` with an admin role -- [ ] Persist users, jobs and quotas with EF Core -- [ ] Add a job submission path and a "my held jobs" endpoint -- [ ] Align frontend routes with the API +- [x] Redesigned UI, demo mode and tests +- [x] Backend builds, routes match the app, endpoints protected, tests +- [x] Free hosting for a public demo +- [x] A review from each user's point of view, with fixes ([docs/08](docs/08-review-and-fixes.md)) +- [x] Work-account sign-in (Microsoft and Google), central printers and quotas +- [ ] Test work-account sign-in against a real tenant +- [ ] Persist users, jobs and quotas in a database +- [ ] A way to send a file to be held +- [ ] A real printer integration - [ ] Card login at the printer -- [ ] Real tests + +## Help and more reading + +| If you want to | Read | +|---|---| +| Follow every screen with pictures | [Getting started](docs/Getting%20started.md) | +| Use Microsoft 365 or Google Workspace | [Connecting your workspace](docs/09-connecting-your-workspace.md) | +| Find a quick answer | [Questions and answers](docs/FAQ.md) | +| Fix a problem | [Fixing problems](docs/Fixing%20problems.md) | +| Put the demo online for free | [Hosting the demo](docs/06-demo-hosting.md) | +| Understand how the pieces fit, every route and setting | [How it works](docs/How%20it%20works.md) | +| See what went wrong from each user's point of view, and the fixes | [Review and fixes](docs/08-review-and-fixes.md) | +| See the screens as designed, with exact wording | [Screen specs](docs/03-screen-specs.md) | +| Answer the questions that change the design | [Open decisions](docs/05-open-decisions.md) | +| Refresh the pictures in these docs | [tools/screenshots](tools/screenshots/README.md) | +| Change the code | [Contributing](CONTRIBUTING.md) | +| See what changed | [Changes](CHANGELOG.md) | + +All the design documents are listed in [`docs/`](docs/README.md). + +## Legal and responsibility + +* Pull Print is a portfolio and learning project, and a demo. It is not a finished print product, and nothing in the live demo prints on paper. +* The code is released under the [MIT licence](LICENSE), as it is, with no promises. + +## Credits + +The Microsoft and Google marks on the sign-in buttons are drawn to their published rules and are placeholders: swap in their own assets before a public launch. Printer and document pictures are drawn for this project. ## Author diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..22ce1b1 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,39 @@ +# Security + +## Reporting a problem + +Please **do not open a public issue** for a security problem. Use GitHub's private reporting instead: on the repository page choose **Security**, then **Report a vulnerability**. Say what you found, how to reproduce it, and what it lets someone do. + +You will get an answer as soon as someone can look at it. This is a demo project maintained by one person, so there is no promised response time. + +## What this project is, and is not + +This is a **demo**. Its hosted version lets anyone sign in to a private sandbox of sample data. Do not put real documents, real people or real printers behind it. + +## What is protected + +- Every route except sign-in, the sign-in options and `/healthz` needs a valid signed token. +- People only reach their own waiting documents. Administrators only reach people in their own group. +- Printing is checked against the person's page quota on the server. +- Demo sign-in is rate limited, sandboxes are capped and deleted after two hours idle, and request bodies are limited to 16 KB. +- Work-account sign-in uses the authorization code flow with PKCE, only accepts people from your organisation, and sends the session token back after `#` so it is not sent to any server or left in the history. +- Replies carry basic security headers, and unexpected errors never return details. + +## What is not done yet + +- Microsoft and Google work-account sign-in is tested against a simulated provider only. It **has not been run against a real tenant**. +- A session token lasts 8 hours and cannot be revoked early. Someone removed from your organisation keeps access until it ends. +- Data is in memory only, with no encryption at rest because there is nothing at rest. +- Limits are per network address and trust the host's `X-Forwarded-For` header, which is right behind Render or similar hosts and wrong anywhere that does not set it. +- No audit log. + +## Settings that matter + +| Setting | What to do | +|---|---| +| `Demo__Enabled` | Turn **off** for anything that is not a demo. Its tokens stop working immediately | +| `Auth__SigningKey` | Set to a long random value (32 characters or more) and keep it secret. Without it everyone is signed out on every restart | +| `Workspace__Provider`, `__ClientId`, `__ClientSecret`, `__TenantId`, `__Domain` | Turn on Microsoft or Google sign-in. See [docs/09](docs/09-connecting-your-workspace.md). The client secret belongs only on the server | +| `Workspace__Admins` | Who is an administrator. Keep it short | + +The client secret is never sent to the app. Google sign-in refuses to turn on without `Workspace__Domain`, so it cannot be left open to every Google account. diff --git a/backend.Tests/ApiTests.cs b/backend.Tests/ApiTests.cs new file mode 100644 index 0000000..eac9a01 --- /dev/null +++ b/backend.Tests/ApiTests.cs @@ -0,0 +1,474 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace PullPrintingBackend.Tests; + +public class ApiFactory : WebApplicationFactory +{ + public const string Key = "test-signing-key-that-is-long-enough-for-hs256"; + + protected virtual bool DemoEnabled => true; + + /// Tests call the API a lot from one address, so the limits are raised unless a test is about them. + protected virtual int LoginsPerMinute => 1000; + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Testing"); + builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(new Dictionary + { + ["Demo:Enabled"] = DemoEnabled ? "true" : "false", + ["Auth:SigningKey"] = Key, + ["RateLimit:LoginPerMinute"] = LoginsPerMinute.ToString(), + ["RateLimit:PerMinute"] = "100000", + })); + } +} + +public class DemoOffFactory : ApiFactory +{ + protected override bool DemoEnabled => false; +} + +public class DefaultLimitsFactory : ApiFactory +{ + protected override int LoginsPerMinute => 20; +} + +/// A store that fails the way a real bug would, to check what the person sees. +public class BrokenStoreFactory : ApiFactory +{ + protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.ConfigureServices(services => + { + var inner = new PullPrintingBackend.Services.PrintStore( + new PullPrintingBackend.Services.SimulatedPrintDispatcher( + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance), + TimeProvider.System, + Microsoft.Extensions.Options.Options.Create(new PullPrintingBackend.Services.WorkspaceOptions())); + services.AddSingleton(new BrokenStore(inner)); + }); + } +} + +public class BrokenStore : PullPrintingBackend.Services.IPrintStore +{ + private readonly PullPrintingBackend.Services.IPrintStore _inner; + public BrokenStore(PullPrintingBackend.Services.IPrintStore inner) => _inner = inner; + + // Signing in works so the test can get a token; reading documents blows up. + public PullPrintingBackend.Models.UserSummary EnsureUser(string id, string name, bool isAdmin, string? email = null) => _inner.EnsureUser(id, name, isAdmin, email); + public PullPrintingBackend.Models.UserSummary EnsureDemoUser(string id, string name, bool isAdmin) => _inner.EnsureDemoUser(id, name, isAdmin); + public PullPrintingBackend.Models.UserSummary CreateDemoUser(bool isAdmin) => _inner.CreateDemoUser(isAdmin); + public PullPrintingBackend.Models.Quota? GetQuota(string userId) => _inner.GetQuota(userId); + public IReadOnlyList HeldJobs(string userId) => throw new InvalidOperationException("secret internal detail"); + public IReadOnlyList AllJobs(string requesterId) => _inner.AllJobs(requesterId); + public IReadOnlyList Users(string requesterId) => _inner.Users(requesterId); + public PullPrintingBackend.Services.ReleaseResult Release(string userId, IReadOnlyCollection jobIds, string? printerId = null) => _inner.Release(userId, jobIds, printerId); + public int? DefaultQuota(string requesterId) => _inner.DefaultQuota(requesterId); + public bool SetDefaultQuota(string requesterId, int quota) => _inner.SetDefaultQuota(requesterId, quota); + public int SetQuotaForAll(string requesterId, int quota) => _inner.SetQuotaForAll(requesterId, quota); + public IReadOnlyList Printers(string requesterId) => _inner.Printers(requesterId); + public PullPrintingBackend.Models.Printer? AddPrinter(string requesterId, string name, string location) => _inner.AddPrinter(requesterId, name, location); + public bool UpdatePrinter(string requesterId, string printerId, string name, string location, bool enabled) => _inner.UpdatePrinter(requesterId, printerId, name, location, enabled); + public bool DeletePrinter(string requesterId, string printerId) => _inner.DeletePrinter(requesterId, printerId); + public bool SetQuota(string requesterId, string userId, int quota) => _inner.SetQuota(requesterId, userId, quota); + public PullPrintingBackend.Models.PrintJob? AddSample(string userId) => _inner.AddSample(userId); + public int Sweep() => _inner.Sweep(); +} + +public record Session(string Token, string UserId, string Name, bool IsAdmin); + +public class ApiTests : IClassFixture +{ + private readonly ApiFactory _factory; + public ApiTests(ApiFactory factory) => _factory = factory; + + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + private async Task<(HttpClient Client, Session Session)> SignIn(bool admin = false) + { + var client = _factory.CreateClient(); + var response = await client.PostAsJsonAsync("/api/auth/demo-login", new { admin }); + response.EnsureSuccessStatusCode(); + var session = (await response.Content.ReadFromJsonAsync(Json))!; + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token); + return (client, session); + } + + private static async Task Body(HttpResponseMessage response) => + (await response.Content.ReadFromJsonAsync(Json)); + + private static async Task> Held(HttpClient client) => + (await Body(await client.GetAsync("/api/jobs/held"))).EnumerateArray().ToList(); + + private static async Task HeldNames(HttpClient client) => + (await Held(client)).Select(j => j.GetProperty("fileName").GetString()!).ToArray(); + + // ---- authentication ---------------------------------------------------- + + [Theory] + [InlineData("GET", "/api/jobs/held")] + [InlineData("GET", "/api/jobs/quota")] + [InlineData("GET", "/api/jobs")] + [InlineData("GET", "/api/auth/me")] + [InlineData("GET", "/api/admin/users")] + [InlineData("POST", "/api/jobs/release")] + [InlineData("POST", "/api/jobs/sample")] + [InlineData("POST", "/api/admin/set-quota")] + public async Task Endpoints_need_a_token(string method, string path) + { + var client = _factory.CreateClient(); + var response = await client.SendAsync(new HttpRequestMessage(new HttpMethod(method), path)); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task Garbage_and_wrongly_signed_tokens_are_rejected() + { + var client = _factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "not-a-token"); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs/held")).StatusCode); + + // A well-formed token signed with some other key. + var forged = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken( + new System.IdentityModel.Tokens.Jwt.JwtSecurityToken( + "pullprint", "pullprint", + new[] { new System.Security.Claims.Claim("uid", "u2"), new System.Security.Claims.Claim("role", "Admin") }, + expires: DateTime.UtcNow.AddHours(1), + signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials( + new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey( + System.Text.Encoding.UTF8.GetBytes("a-completely-different-signing-key-123456")), + Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256))); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", forged); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs")).StatusCode); + } + + [Fact] + public async Task Demo_sign_in_returns_a_token_that_names_the_visitor() + { + var (client, session) = await SignIn(); + Assert.Equal("Alice Tan", session.Name); + Assert.False(session.IsAdmin); + + var me = await Body(await client.GetAsync("/api/auth/me")); + Assert.Equal(session.UserId, me.GetProperty("userId").GetString()); + Assert.False(me.GetProperty("isAdmin").GetBoolean()); + } + + [Fact] + public async Task Demo_sign_in_can_be_switched_off_and_then_its_tokens_stop_working() + { + var (_, session) = await SignIn(); + + using var off = new DemoOffFactory(); + var client = off.CreateClient(); + Assert.Equal(HttpStatusCode.NotFound, + (await client.PostAsJsonAsync("/api/auth/demo-login", new { admin = false })).StatusCode); + + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs/held")).StatusCode); + } + + [Fact] + public async Task Normal_users_cannot_use_admin_routes() + { + var (client, session) = await SignIn(); + Assert.Equal(HttpStatusCode.Forbidden, (await client.GetAsync("/api/jobs")).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, (await client.GetAsync("/api/admin/users")).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, + (await client.PostAsJsonAsync("/api/admin/set-quota", new { userId = session.UserId, quota = 9999 })).StatusCode); + + // And the quota was not changed. + var quota = await Body(await client.GetAsync("/api/jobs/quota")); + Assert.Equal(50, quota.GetProperty("total").GetInt32()); + } + + [Fact] + public async Task Admins_see_the_jobs_of_their_own_sample_people_and_nobody_elses() + { + var (visitor, _) = await SignIn(); + var visitorJobIds = (await Held(visitor)).Select(j => j.GetProperty("id").GetString()).ToHashSet(); + + var (admin, _) = await SignIn(admin: true); + var response = await admin.GetAsync("/api/jobs"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var jobs = (await Body(response)).EnumerateArray().ToList(); + var names = jobs.Select(j => j.GetProperty("fileName").GetString()).ToList(); + Assert.Contains("Safety audit.pdf", names); + Assert.Contains("Invoice 2291.pdf", names); + + // The visitor's documents are not in the administrator's view. + Assert.DoesNotContain(jobs, j => visitorJobIds.Contains(j.GetProperty("id").GetString())); + } + + [Fact] + public async Task Sign_in_attempts_are_rate_limited() + { + using var factory = new DefaultLimitsFactory(); + var client = factory.CreateClient(); + HttpStatusCode last = HttpStatusCode.OK; + for (var i = 0; i < 25; i++) + last = (await client.PostAsJsonAsync("/api/auth/demo-login", new { admin = false })).StatusCode; + Assert.Equal(HttpStatusCode.TooManyRequests, last); + } + + [Fact] + public async Task Health_check_needs_no_token() + { + var response = await _factory.CreateClient().GetAsync("/healthz"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Replies_carry_basic_security_headers() + { + var response = await _factory.CreateClient().GetAsync("/healthz"); + Assert.Equal("nosniff", response.Headers.GetValues("X-Content-Type-Options").Single()); + Assert.Equal("DENY", response.Headers.GetValues("X-Frame-Options").Single()); + Assert.Equal("no-referrer", response.Headers.GetValues("Referrer-Policy").Single()); + Assert.Contains("frame-ancestors 'none'", response.Headers.GetValues("Content-Security-Policy").Single()); + } + + [Fact] + public async Task An_unexpected_failure_gives_a_short_json_error_with_no_details() + { + using var broken = new BrokenStoreFactory(); + var client = broken.CreateClient(); + var login = await client.PostAsJsonAsync("/api/auth/demo-login", new { admin = false }); + var session = (await login.Content.ReadFromJsonAsync(Json))!; + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token); + + var response = await client.GetAsync("/api/jobs/held"); + + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + var text = await response.Content.ReadAsStringAsync(); + Assert.Contains("server_error", text); + Assert.DoesNotContain("secret internal detail", text); + Assert.DoesNotContain(" at ", text); // no stack trace + } + + // ---- documents and quota ----------------------------------------------- + + [Fact] + public async Task A_visitor_sees_only_their_own_waiting_documents() + { + var (client, _) = await SignIn(); + var names = await HeldNames(client); + Assert.Equal( + new[] { "Q3 budget review.pdf", "Site visit notes.docx", "Contract draft v4.pdf", "Floor plan.png" }, + names); + Assert.DoesNotContain("Safety audit.pdf", names); + + var quota = await Body(await client.GetAsync("/api/jobs/quota")); + Assert.Equal(12, quota.GetProperty("used").GetInt32()); + Assert.Equal(50, quota.GetProperty("total").GetInt32()); + Assert.Equal(38, quota.GetProperty("left").GetInt32()); + } + + [Fact] + public async Task Printing_uses_up_pages_and_removes_the_documents_from_the_list() + { + var (client, _) = await SignIn(); + var held = await Held(client); + var ids = held.Take(2).Select(j => j.GetProperty("id").GetString()).ToList(); + + var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var body = await Body(response); + Assert.Equal(15, body.GetProperty("pages").GetInt32()); + Assert.Equal(27, body.GetProperty("quota").GetProperty("used").GetInt32()); + + Assert.Equal(new[] { "Contract draft v4.pdf", "Floor plan.png" }, await HeldNames(client)); + } + + [Fact] + public async Task Going_over_quota_prints_nothing_and_says_by_how_much() + { + var (client, _) = await SignIn(); + var ids = (await Held(client)).Select(j => j.GetProperty("id").GetString()).ToList(); // 44 pages, 38 left + + var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids }); + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + var body = await Body(response); + Assert.Equal("quota_exceeded", body.GetProperty("error").GetString()); + Assert.Equal(6, body.GetProperty("pagesOver").GetInt32()); + + Assert.Equal(4, (await Held(client)).Count); + var quota = await Body(await client.GetAsync("/api/jobs/quota")); + Assert.Equal(12, quota.GetProperty("used").GetInt32()); + } + + [Fact] + public async Task Someone_elses_document_cannot_be_printed() + { + var (client, _) = await SignIn(); + var (admin, _) = await SignIn(admin: true); + var all = (await Body(await admin.GetAsync("/api/jobs"))).EnumerateArray().ToList(); + var priyas = all.First(j => j.GetProperty("fileName").GetString() == "Safety audit.pdf").GetProperty("id").GetString(); + + var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = new[] { priyas } }); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + + var after = (await Body(await admin.GetAsync("/api/jobs"))).EnumerateArray() + .First(j => j.GetProperty("id").GetString() == priyas); + Assert.Equal("Held", after.GetProperty("status").GetString()); + } + + [Fact] + public async Task Visitors_are_isolated_from_each_other() + { + var (first, _) = await SignIn(); + var (second, _) = await SignIn(); + var ids = (await Held(first)).Take(2).Select(j => j.GetProperty("id").GetString()).ToList(); + Assert.Equal(HttpStatusCode.OK, (await first.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids })).StatusCode); + + Assert.Equal(2, (await Held(first)).Count); + Assert.Equal(4, (await Held(second)).Count); + var quota = await Body(await second.GetAsync("/api/jobs/quota")); + Assert.Equal(12, quota.GetProperty("used").GetInt32()); + } + + [Fact] + public async Task Bad_release_requests_are_refused() + { + var (client, _) = await SignIn(); + Assert.Equal(HttpStatusCode.BadRequest, + (await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = Array.Empty() })).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = new[] { "nope" } })).StatusCode); + + var id = (await Held(client)).First().GetProperty("id").GetString(); + Assert.Equal(HttpStatusCode.OK, (await client.PostAsJsonAsync("/api/jobs/release", new { jobId = id })).StatusCode); + // Printing the same document twice is refused and charges nothing more. + Assert.Equal(HttpStatusCode.NotFound, (await client.PostAsJsonAsync("/api/jobs/release", new { jobId = id })).StatusCode); + var quota = await Body(await client.GetAsync("/api/jobs/quota")); + Assert.Equal(24, quota.GetProperty("used").GetInt32()); + } + + [Fact] + public async Task Printing_too_many_documents_in_one_go_is_refused() + { + var (client, _) = await SignIn(); + var ids = Enumerable.Range(0, 51).Select(i => "id" + i).ToArray(); + var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = ids }); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("too_many", (await Body(response)).GetProperty("error").GetString()); + } + + [Fact] + public async Task The_same_document_sent_twice_is_charged_once() + { + var (client, _) = await SignIn(); + var id = (await Held(client)).First().GetProperty("id").GetString(); + + var response = await client.PostAsJsonAsync("/api/jobs/release", new { jobIds = new[] { id, id } }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(12, (await Body(response)).GetProperty("pages").GetInt32()); + } + + [Fact] + public async Task Sample_documents_are_new_ones_first_and_run_out() + { + var (client, _) = await SignIn(); + var added = new List(); + for (var i = 0; i < 4; i++) + { + var response = await client.PostAsync("/api/jobs/sample", null); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + added.Add((await Body(response)).GetProperty("fileName").GetString()!); + } + Assert.Equal( + new[] { "Meeting agenda.docx", "Safety checklist.pdf", "Onboarding guide.pdf", "Site photo.png" }, + added.OrderBy(n => n).Select(n => n).OrderBy(n => Array.IndexOf( + new[] { "Meeting agenda.docx", "Safety checklist.pdf", "Onboarding guide.pdf", "Site photo.png" }, n))); + Assert.Equal(8, (await Held(client)).Count); + Assert.Equal(HttpStatusCode.Conflict, (await client.PostAsync("/api/jobs/sample", null)).StatusCode); + } + + [Fact] + public async Task A_printed_document_does_not_come_straight_back_as_a_sample() + { + var (client, _) = await SignIn(); + var first = (await Held(client)).First().GetProperty("id").GetString(); + await client.PostAsJsonAsync("/api/jobs/release", new { jobId = first }); // Q3 budget review.pdf + + var sample = await Body(await client.PostAsync("/api/jobs/sample", null)); + Assert.NotEqual("Q3 budget review.pdf", sample.GetProperty("fileName").GetString()); + } + + // ---- administration ----------------------------------------------------- + + private static async Task> AdminUsers(HttpClient admin) => + (await Body(await admin.GetAsync("/api/admin/users"))).EnumerateArray().ToList(); + + private static JsonElement Person(List users, string name) => + users.First(u => u.GetProperty("name").GetString() == name); + + [Fact] + public async Task An_admin_sees_sample_people_and_can_change_their_quota() + { + var (admin, _) = await SignIn(admin: true); + var users = await AdminUsers(admin); + Assert.Equal( + new[] { "Alice Tan", "Bob Reyes", "Marcus Lee", "Priya Nair" }, + users.Select(u => u.GetProperty("name").GetString()).ToArray()); + Assert.Equal(200, Person(users, "Priya Nair").GetProperty("quota").GetProperty("total").GetInt32()); + + var priya = Person(users, "Priya Nair").GetProperty("userId").GetString(); + Assert.Equal(HttpStatusCode.OK, + (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = priya, quota = 20 })).StatusCode); + + var after = await AdminUsers(admin); + Assert.Equal(20, Person(after, "Priya Nair").GetProperty("quota").GetProperty("total").GetInt32()); + } + + [Fact] + public async Task An_admin_cannot_see_or_change_a_visitors_account() + { + var (_, visitor) = await SignIn(); + var (admin, _) = await SignIn(admin: true); + + Assert.DoesNotContain(await AdminUsers(admin), u => u.GetProperty("userId").GetString() == visitor.UserId); + Assert.Equal(HttpStatusCode.NotFound, + (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = visitor.UserId, quota = 1 })).StatusCode); + } + + [Fact] + public async Task Two_admins_do_not_affect_each_other() + { + var (first, _) = await SignIn(admin: true); + var (second, _) = await SignIn(admin: true); + + var priya = Person(await AdminUsers(first), "Priya Nair").GetProperty("userId").GetString(); + Assert.Equal(HttpStatusCode.OK, + (await first.PostAsJsonAsync("/api/admin/set-quota", new { userId = priya, quota = 5 })).StatusCode); + + Assert.Equal(200, Person(await AdminUsers(second), "Priya Nair").GetProperty("quota").GetProperty("total").GetInt32()); + Assert.Equal(HttpStatusCode.NotFound, + (await second.PostAsJsonAsync("/api/admin/set-quota", new { userId = priya, quota = 1 })).StatusCode); + } + + [Fact] + public async Task Quota_changes_are_validated() + { + var (admin, session) = await SignIn(admin: true); + Assert.Equal(HttpStatusCode.BadRequest, + (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = session.UserId, quota = -1 })).StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, + (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = session.UserId, quota = 1_000_000 })).StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, + (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = "", quota = 10 })).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await admin.PostAsJsonAsync("/api/admin/set-quota", new { userId = "nobody", quota = 10 })).StatusCode); + } +} diff --git a/backend.Tests/PrinterAndQuotaTests.cs b/backend.Tests/PrinterAndQuotaTests.cs new file mode 100644 index 0000000..18511a0 --- /dev/null +++ b/backend.Tests/PrinterAndQuotaTests.cs @@ -0,0 +1,317 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using PullPrintingBackend.Models; +using PullPrintingBackend.Services; + +namespace PullPrintingBackend.Tests; + +public class PrinterAndQuotaStoreTests +{ + private class FakeClock : TimeProvider + { + public DateTimeOffset Now { get; set; } = new(2026, 10, 22, 9, 0, 0, TimeSpan.Zero); + public override DateTimeOffset GetUtcNow() => Now; + } + + private static PrintStore NewStore(FakeClock? clock = null, int defaultQuota = 50) => + new(new SimulatedPrintDispatcher(NullLogger.Instance), + clock ?? new FakeClock(), + Options.Create(new WorkspaceOptions { DefaultQuota = defaultQuota })); + + [Fact] + public void Pages_used_start_again_when_the_month_changes() + { + var clock = new FakeClock { Now = new(2026, 10, 31, 23, 0, 0, TimeSpan.Zero) }; + var store = NewStore(clock); + var visitor = store.CreateDemoUser(isAdmin: false); + var ids = store.HeldJobs(visitor.UserId).Take(2).Select(j => j.Id).ToList(); + + var printed = store.Release(visitor.UserId, ids); + Assert.Equal(ReleaseOutcome.Printed, printed.Outcome); + Assert.True(store.GetQuota(visitor.UserId)!.Used > 0); + + clock.Now = new(2026, 11, 1, 0, 30, 0, TimeSpan.Zero); + Assert.Equal(0, store.GetQuota(visitor.UserId)!.Used); + } + + [Fact] + public void Pages_used_do_not_reset_within_the_same_month() + { + var clock = new FakeClock { Now = new(2026, 10, 1, 0, 0, 0, TimeSpan.Zero) }; + var store = NewStore(clock); + var visitor = store.CreateDemoUser(isAdmin: false); + store.Release(visitor.UserId, store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList()); + var used = store.GetQuota(visitor.UserId)!.Used; + + clock.Now = new(2026, 10, 31, 23, 59, 0, TimeSpan.Zero); + Assert.Equal(used, store.GetQuota(visitor.UserId)!.Used); + } + + [Fact] + public void The_default_quota_is_used_for_people_who_sign_in_later_and_not_for_those_already_there() + { + var store = NewStore(defaultQuota: 40); + var boss = store.EnsureUser("boss", "Boss", isAdmin: true); + var early = store.EnsureUser("early", "Early", isAdmin: false); + Assert.Equal(40, early.Quota.Total); + + Assert.True(store.SetDefaultQuota(boss.UserId, 120)); + Assert.Equal(120, store.DefaultQuota(boss.UserId)); + Assert.Equal(120, store.EnsureUser("late", "Late", isAdmin: false).Quota.Total); + Assert.Equal(40, store.GetQuota("early")!.Total); + } + + [Fact] + public void Giving_everyone_the_same_pages_changes_the_whole_group_and_only_that_group() + { + var store = NewStore(); + var boss = store.EnsureUser("boss", "Boss", isAdmin: true); + store.EnsureUser("a", "A", isAdmin: false); + store.EnsureUser("b", "B", isAdmin: false); + var visitor = store.CreateDemoUser(isAdmin: false); + var visitorBefore = store.GetQuota(visitor.UserId)!.Total; + + var changed = store.SetQuotaForAll(boss.UserId, 15); + + Assert.True(changed >= 2); + Assert.Equal(15, store.GetQuota("a")!.Total); + Assert.Equal(15, store.GetQuota("b")!.Total); + Assert.Equal(visitorBefore, store.GetQuota(visitor.UserId)!.Total); + } + + [Fact] + public void A_demo_visitor_starts_with_three_printers_and_a_workspace_with_none() + { + var store = NewStore(); + var visitor = store.CreateDemoUser(isAdmin: false); + var boss = store.EnsureUser("boss", "Boss", isAdmin: true); + + Assert.Equal(new[] { "Level 3 East", "Print room", "Reception" }, + store.Printers(visitor.UserId).Select(p => p.Name).ToArray()); + Assert.Empty(store.Printers(boss.UserId)); + } + + [Fact] + public void Printers_can_be_added_renamed_switched_off_and_removed() + { + var store = NewStore(); + var boss = store.EnsureUser("boss", "Boss", isAdmin: true); + + var added = store.AddPrinter(boss.UserId, "Studio", "Level 1")!; + Assert.Equal("Studio", store.Printers(boss.UserId).Single().Name); + + Assert.True(store.UpdatePrinter(boss.UserId, added.Id, "Design studio", "Level 2", enabled: false)); + var changed = store.Printers(boss.UserId).Single(); + Assert.Equal(("Design studio", "Level 2", false), (changed.Name, changed.Location, changed.Enabled)); + + Assert.True(store.DeletePrinter(boss.UserId, added.Id)); + Assert.Empty(store.Printers(boss.UserId)); + Assert.False(store.DeletePrinter(boss.UserId, added.Id)); + Assert.False(store.UpdatePrinter(boss.UserId, "nope", "x", "", true)); + } + + [Fact] + public void One_group_cannot_change_or_see_another_groups_printers() + { + var store = NewStore(); + var boss = store.EnsureUser("boss", "Boss", isAdmin: true); + var visitor = store.CreateDemoUser(isAdmin: true); + var theirs = store.Printers(visitor.UserId).First(); + + Assert.False(store.UpdatePrinter(boss.UserId, theirs.Id, "Hijacked", "", true)); + Assert.False(store.DeletePrinter(boss.UserId, theirs.Id)); + Assert.Equal("Level 3 East", store.Printers(visitor.UserId).First().Name); + } + + [Fact] + public void There_is_a_limit_to_how_many_printers_can_be_added() + { + var store = NewStore(); + var boss = store.EnsureUser("boss", "Boss", isAdmin: true); + for (var i = 0; i < PrintStore.MaxPrinters; i++) + Assert.NotNull(store.AddPrinter(boss.UserId, $"P{i}", "")); + Assert.Null(store.AddPrinter(boss.UserId, "One too many", "")); + } + + [Fact] + public void Printing_names_the_printer_used_and_picks_the_first_one_that_is_on_by_default() + { + var store = NewStore(); + var visitor = store.CreateDemoUser(isAdmin: false); + var first = store.Printers(visitor.UserId).First(); + store.UpdatePrinter(visitor.UserId, first.Id, first.Name, first.Location, enabled: false); + + var any = store.Release(visitor.UserId, store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList()); + Assert.Equal(ReleaseOutcome.Printed, any.Outcome); + Assert.Equal("Print room", any.PrinterName); + + var chosen = store.Printers(visitor.UserId).Last(); + var picked = store.Release(visitor.UserId, store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList(), chosen.Id); + Assert.Equal(chosen.Name, picked.PrinterName); + Assert.Equal(chosen.Name, picked.Printed.Single().PrinterName); + } + + [Fact] + public void A_switched_off_or_unknown_printer_prints_nothing_and_costs_nothing() + { + var store = NewStore(); + var visitor = store.CreateDemoUser(isAdmin: false); + var off = store.Printers(visitor.UserId).First(); + store.UpdatePrinter(visitor.UserId, off.Id, off.Name, off.Location, enabled: false); + var ids = store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList(); + var before = store.GetQuota(visitor.UserId)!.Used; + + Assert.Equal(ReleaseOutcome.PrinterUnavailable, store.Release(visitor.UserId, ids, off.Id).Outcome); + Assert.Equal(ReleaseOutcome.PrinterUnavailable, store.Release(visitor.UserId, ids, "no-such-printer").Outcome); + Assert.Equal(before, store.GetQuota(visitor.UserId)!.Used); + Assert.Equal(ids.Count, store.HeldJobs(visitor.UserId).Count(j => ids.Contains(j.Id))); + } + + [Fact] + public void A_printer_from_another_group_cannot_be_used() + { + var store = NewStore(); + var a = store.CreateDemoUser(isAdmin: false); + var b = store.CreateDemoUser(isAdmin: false); + var bsPrinter = store.Printers(b.UserId).First(); + var ids = store.HeldJobs(a.UserId).Take(1).Select(j => j.Id).ToList(); + + Assert.Equal(ReleaseOutcome.PrinterUnavailable, store.Release(a.UserId, ids, bsPrinter.Id).Outcome); + } + + [Fact] + public void With_no_printers_at_all_the_outcome_says_so() + { + var store = NewStore(); + var visitor = store.CreateDemoUser(isAdmin: false); + foreach (var p in store.Printers(visitor.UserId)) store.DeletePrinter(visitor.UserId, p.Id); + + var ids = store.HeldJobs(visitor.UserId).Take(1).Select(j => j.Id).ToList(); + Assert.Equal(ReleaseOutcome.NoPrinter, store.Release(visitor.UserId, ids).Outcome); + } +} + +public class PrinterAndQuotaApiTests : IClassFixture +{ + private readonly ApiFactory _factory; + public PrinterAndQuotaApiTests(ApiFactory factory) => _factory = factory; + + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + private async Task SignIn(bool admin) + { + var client = _factory.CreateClient(); + var response = await client.PostAsJsonAsync("/api/auth/demo-login", new { admin }); + var session = (await response.Content.ReadFromJsonAsync(Json))!; + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.Token); + return client; + } + + [Fact] + public async Task A_visitor_can_list_printers_but_not_manage_them() + { + var client = await SignIn(admin: false); + var list = await client.GetFromJsonAsync("/api/printers", Json); + Assert.Equal(3, list.GetArrayLength()); + + Assert.Equal(HttpStatusCode.Forbidden, + (await client.PostAsJsonAsync("/api/admin/printers", new { name = "X" })).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, + (await client.PostAsJsonAsync("/api/admin/default-quota", new { quota = 10 })).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, + (await client.PostAsJsonAsync("/api/admin/set-quota-all", new { quota = 10 })).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, (await client.GetAsync("/api/admin/setup")).StatusCode); + } + + [Fact] + public async Task An_administrator_adds_switches_off_and_removes_a_printer() + { + var admin = await SignIn(admin: true); + + var added = await admin.PostAsJsonAsync("/api/admin/printers", new { name = "Studio", location = "L1" }); + Assert.Equal(HttpStatusCode.OK, added.StatusCode); + var printer = await added.Content.ReadFromJsonAsync(Json); + var id = printer.GetProperty("id").GetString()!; + + var off = await admin.PutAsJsonAsync($"/api/admin/printers/{id}", new { name = "Studio", location = "L1", enabled = false }); + Assert.Equal(HttpStatusCode.OK, off.StatusCode); + var listed = (await admin.GetFromJsonAsync("/api/printers", Json)).EnumerateArray() + .First(p => p.GetProperty("id").GetString() == id); + Assert.False(listed.GetProperty("enabled").GetBoolean()); + + Assert.Equal(HttpStatusCode.OK, (await admin.DeleteAsync($"/api/admin/printers/{id}")).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await admin.DeleteAsync($"/api/admin/printers/{id}")).StatusCode); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public async Task A_printer_needs_a_name(string name) + { + var admin = await SignIn(admin: true); + var response = await admin.PostAsJsonAsync("/api/admin/printers", new { name }); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Theory] + [InlineData("/api/admin/default-quota", -1)] + [InlineData("/api/admin/default-quota", 10_001)] + [InlineData("/api/admin/set-quota-all", -5)] + [InlineData("/api/admin/set-quota-all", 1_000_000)] + public async Task Quota_rules_outside_the_allowed_range_are_refused(string path, int quota) + { + var admin = await SignIn(admin: true); + Assert.Equal(HttpStatusCode.BadRequest, (await admin.PostAsJsonAsync(path, new { quota })).StatusCode); + } + + [Fact] + public async Task The_administrators_quota_rules_take_effect() + { + var admin = await SignIn(admin: true); + + Assert.Equal(HttpStatusCode.OK, (await admin.PostAsJsonAsync("/api/admin/default-quota", new { quota = 77 })).StatusCode); + var setup = await admin.GetFromJsonAsync("/api/admin/setup", Json); + Assert.Equal(77, setup.GetProperty("defaultQuota").GetInt32()); + + var all = await admin.PostAsJsonAsync("/api/admin/set-quota-all", new { quota = 9 }); + var changed = (await all.Content.ReadFromJsonAsync(Json)).GetProperty("changed").GetInt32(); + Assert.True(changed >= 1); + var users = await admin.GetFromJsonAsync("/api/admin/users", Json); + Assert.All(users.EnumerateArray(), u => Assert.Equal(9, u.GetProperty("quota").GetProperty("total").GetInt32())); + } + + [Fact] + public async Task Printing_on_an_unknown_printer_is_refused_with_a_reason_and_prints_nothing() + { + var client = await SignIn(admin: false); + var held = (await client.GetFromJsonAsync("/api/jobs/held", Json)).EnumerateArray().First(); + var response = await client.PostAsJsonAsync("/api/jobs/release", + new { jobIds = new[] { held.GetProperty("id").GetString() }, printerId = "no-such-printer" }); + + Assert.Equal(HttpStatusCode.Conflict, response.StatusCode); + var body = await response.Content.ReadFromJsonAsync(Json); + Assert.Equal("printer_unavailable", body.GetProperty("error").GetString()); + var stillHeld = (await client.GetFromJsonAsync("/api/jobs/held", Json)).EnumerateArray(); + Assert.Contains(stillHeld, j => j.GetProperty("id").GetString() == held.GetProperty("id").GetString()); + } + + [Fact] + public async Task Printing_on_a_chosen_printer_says_which_one() + { + var client = await SignIn(admin: false); + var printers = (await client.GetFromJsonAsync("/api/printers", Json)).EnumerateArray().ToList(); + var reception = printers.First(p => p.GetProperty("name").GetString() == "Reception"); + var held = (await client.GetFromJsonAsync("/api/jobs/held", Json)).EnumerateArray().First(j => j.GetProperty("pages").GetInt32() <= 12); + + var response = await client.PostAsJsonAsync("/api/jobs/release", + new { jobIds = new[] { held.GetProperty("id").GetString() }, printerId = reception.GetProperty("id").GetString() }); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var body = await response.Content.ReadFromJsonAsync(Json); + Assert.Equal("Reception", body.GetProperty("printerName").GetString()); + } +} diff --git a/backend.Tests/PullPrintingBackend.Tests.csproj b/backend.Tests/PullPrintingBackend.Tests.csproj new file mode 100644 index 0000000..0957630 --- /dev/null +++ b/backend.Tests/PullPrintingBackend.Tests.csproj @@ -0,0 +1,25 @@ + + + + net8.0 + enable + enable + false + + + + + + + + + + + + + + + + + + diff --git a/backend.Tests/StoreTests.cs b/backend.Tests/StoreTests.cs new file mode 100644 index 0000000..2c523e8 --- /dev/null +++ b/backend.Tests/StoreTests.cs @@ -0,0 +1,148 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using PullPrintingBackend.Models; +using PullPrintingBackend.Services; + +namespace PullPrintingBackend.Tests; + +public class StoreTests +{ + private class FakeClock : TimeProvider + { + public DateTimeOffset Now { get; set; } = new(2026, 10, 22, 9, 0, 0, TimeSpan.Zero); + public override DateTimeOffset GetUtcNow() => Now; + } + + private class FailingDispatcher : IPrintDispatcher + { + public void Print(PrintJob job, Printer printer) => throw new InvalidOperationException("printer offline"); + } + + private static PrintStore NewStore(FakeClock? clock = null, IPrintDispatcher? dispatcher = null, int defaultQuota = 50) => + new(dispatcher ?? new SimulatedPrintDispatcher(NullLogger.Instance), + clock ?? new FakeClock(), + Options.Create(new WorkspaceOptions { DefaultQuota = defaultQuota })); + + [Fact] + public void Idle_sandboxes_are_removed_with_their_documents_but_the_shared_group_stays() + { + var clock = new FakeClock(); + var store = NewStore(clock); + var root = store.EnsureUser("root", "Root", isAdmin: true); + store.EnsureUser("pat", "Pat Doe", isAdmin: false); + var visitor = store.CreateDemoUser(isAdmin: false); + + clock.Now += TimeSpan.FromHours(1); + Assert.Equal(0, store.Sweep()); + + clock.Now += TimeSpan.FromHours(1.5); + Assert.Equal(1, store.Sweep()); + Assert.Null(store.GetQuota(visitor.UserId)); + Assert.Empty(store.HeldJobs(visitor.UserId)); + Assert.Contains(store.Users(root.UserId), u => u.Name == "Pat Doe"); + } + + [Fact] + public void An_active_visitor_is_not_swept() + { + var clock = new FakeClock(); + var store = NewStore(clock); + var visitor = store.CreateDemoUser(isAdmin: false); + + clock.Now += TimeSpan.FromHours(1.5); + store.EnsureDemoUser(visitor.UserId, visitor.Name, false); // any request counts as activity + clock.Now += TimeSpan.FromHours(1.5); + Assert.Equal(0, store.Sweep()); + Assert.NotNull(store.GetQuota(visitor.UserId)); + } + + [Fact] + public void An_active_admin_keeps_the_whole_sample_group() + { + var clock = new FakeClock(); + var store = NewStore(clock); + var admin = store.CreateDemoUser(isAdmin: true); + + clock.Now += TimeSpan.FromHours(1.5); + store.EnsureDemoUser(admin.UserId, admin.Name, true); + clock.Now += TimeSpan.FromHours(1.5); // sample people are 3 hours old, the admin is 1.5 + + Assert.Equal(0, store.Sweep()); + Assert.Equal(4, store.Users(admin.UserId).Count); + } + + [Fact] + public void An_admin_whose_sandbox_was_cleaned_up_gets_a_fresh_one_on_the_next_request() + { + var clock = new FakeClock(); + var store = NewStore(clock); + var admin = store.CreateDemoUser(isAdmin: true); + clock.Now += TimeSpan.FromHours(3); + Assert.Equal(1, store.Sweep()); + Assert.Empty(store.Users(admin.UserId)); + + store.EnsureDemoUser(admin.UserId, admin.Name, true); + + Assert.Equal(4, store.Users(admin.UserId).Count); + } + + [Fact] + public void The_number_of_sandboxes_is_capped_by_removing_the_least_recent() + { + var clock = new FakeClock(); + var store = NewStore(clock); + var first = store.CreateDemoUser(isAdmin: false); + UserSummary last = first; + for (var i = 0; i < PrintStore.MaxVisitors + 5; i++) + { + clock.Now += TimeSpan.FromSeconds(1); + last = store.CreateDemoUser(isAdmin: i % 2 == 0); + } + + Assert.Equal(PrintStore.MaxVisitors, store.SandboxCount); + Assert.Null(store.GetQuota(first.UserId)); + Assert.NotNull(store.GetQuota(last.UserId)); + } + + [Fact] + public void Quotas_can_only_be_changed_inside_the_requesters_own_group() + { + var store = NewStore(); + var admin = store.CreateDemoUser(isAdmin: true); + var visitor = store.CreateDemoUser(isAdmin: false); + var alice = store.Users(admin.UserId).First(u => u.Name == "Alice Tan"); + + Assert.True(store.SetQuota(admin.UserId, alice.UserId, 99)); + Assert.Equal(99, store.GetQuota(alice.UserId)!.Total); + Assert.False(store.SetQuota(admin.UserId, visitor.UserId, 1)); + Assert.Equal(50, store.GetQuota(visitor.UserId)!.Total); + Assert.False(store.SetQuota("nobody", alice.UserId, 1)); + } + + [Fact] + public void A_job_the_printer_rejects_is_marked_failed_and_costs_no_pages() + { + var store = NewStore(dispatcher: new FailingDispatcher()); + var visitor = store.CreateDemoUser(isAdmin: false); + var job = store.HeldJobs(visitor.UserId).First(); + + var result = store.Release(visitor.UserId, new[] { job.Id }); + + Assert.Empty(result.Printed); + Assert.Equal(12, store.GetQuota(visitor.UserId)!.Used); + var stored = store.AllJobs(visitor.UserId).Single(j => j.Id == job.Id); + Assert.Equal(JobStatus.Failed, stored.Status); + Assert.Equal("printer offline", stored.FailureReason); + Assert.DoesNotContain(store.HeldJobs(visitor.UserId), j => j.Id == job.Id); + } + + [Fact] + public void Signing_in_with_a_new_account_creates_a_user_with_the_default_quota() + { + var store = NewStore(); + var user = store.EnsureUser("entra-oid-1", "Dana Cole", isAdmin: false); + Assert.Equal(50, user.Quota.Total); + Assert.Equal(0, user.Quota.Used); + Assert.Empty(store.HeldJobs("entra-oid-1")); + } +} diff --git a/backend.Tests/WorkspaceTests.cs b/backend.Tests/WorkspaceTests.cs new file mode 100644 index 0000000..a71a9e8 --- /dev/null +++ b/backend.Tests/WorkspaceTests.cs @@ -0,0 +1,617 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using PullPrintingBackend.Controllers; +using PullPrintingBackend.Services; + +namespace PullPrintingBackend.Tests; + +// ---- the rules that decide whether a work account is let in --------------- + +public class WorkspaceRuleTests +{ + private static ClaimsPrincipal Account(params (string Type, string Value)[] claims) => + new(new ClaimsIdentity(claims.Select(c => new Claim(c.Type, c.Value)), "test")); + + private static WorkspaceOptions Google(string? admins = null) => new() + { + Provider = "Google", ClientId = "c", ClientSecret = "s", Domain = "example.com", Admins = admins, + }; + + private static WorkspaceOptions Microsoft(string? domain = null, string? admins = null) => new() + { + Provider = "Microsoft", ClientId = "c", ClientSecret = "s", TenantId = "tenant-1", Domain = domain, Admins = admins, + }; + + [Fact] + public void A_Google_account_in_the_domain_is_let_in() + { + var (user, denied) = WorkspaceIdentity.Map(Google(), Account( + ("sub", "123"), ("email", "Pat.Doe@Example.com"), ("email_verified", "true"), ("hd", "example.com"), ("name", "Pat Doe"))); + + Assert.Null(denied); + Assert.Equal("g-123", user!.Id); + Assert.Equal("Pat Doe", user.Name); + Assert.Equal("pat.doe@example.com", user.Email); + Assert.False(user.IsAdmin); + } + + [Theory] + [InlineData("boss@example.com")] + [InlineData("Boss@Example.com")] + [InlineData("other@example.com, boss@example.com")] + [InlineData("other@example.com;boss@example.com")] + [InlineData("other@example.com boss@example.com")] + public void Administrators_are_found_by_email_however_the_list_is_written(string admins) + { + var (user, _) = WorkspaceIdentity.Map(Google(admins), Account( + ("sub", "1"), ("email", "boss@example.com"), ("email_verified", "true"), ("hd", "example.com"))); + Assert.True(user!.IsAdmin); + } + + [Fact] + public void A_personal_Google_account_is_turned_away() + { + // Personal accounts have no "hd" (hosted domain) claim. + var (user, denied) = WorkspaceIdentity.Map(Google(), Account( + ("sub", "1"), ("email", "pat@gmail.com"), ("email_verified", "true"))); + Assert.Null(user); + Assert.Equal("wrong_account", denied!.Code); + Assert.Contains("example.com", denied.Message); + } + + [Fact] + public void A_Google_account_from_another_organisation_is_turned_away() + { + var (user, denied) = WorkspaceIdentity.Map(Google(), Account( + ("sub", "1"), ("email", "pat@other.org"), ("email_verified", "true"), ("hd", "other.org"))); + Assert.Null(user); + Assert.Equal("wrong_account", denied!.Code); + } + + [Fact] + public void An_unverified_Google_email_is_turned_away() + { + var (user, denied) = WorkspaceIdentity.Map(Google(), Account( + ("sub", "1"), ("email", "pat@example.com"), ("email_verified", "false"), ("hd", "example.com"))); + Assert.Null(user); + Assert.Equal("unverified_email", denied!.Code); + } + + [Fact] + public void A_Google_domain_claim_alone_is_not_enough_the_email_must_match_too() + { + var (user, denied) = WorkspaceIdentity.Map(Google(), Account( + ("sub", "1"), ("email", "pat@evil.test"), ("email_verified", "true"), ("hd", "example.com"))); + Assert.Null(user); + Assert.Equal("wrong_account", denied!.Code); + } + + [Fact] + public void A_Microsoft_account_in_the_tenant_is_let_in_and_the_app_role_makes_an_administrator() + { + var (user, denied) = WorkspaceIdentity.Map(Microsoft(), Account( + ("oid", "abc"), ("tid", "tenant-1"), ("preferred_username", "Pat@Contoso.com"), ("name", "Pat Doe"), ("roles", "PullPrint.Admin"))); + + Assert.Null(denied); + Assert.Equal("m-abc", user!.Id); + Assert.Equal("pat@contoso.com", user.Email); + Assert.True(user.IsAdmin); + } + + [Fact] + public void A_Microsoft_account_from_another_tenant_is_turned_away() + { + var (user, denied) = WorkspaceIdentity.Map(Microsoft(), Account( + ("oid", "abc"), ("tid", "someone-else"), ("preferred_username", "pat@contoso.com"))); + Assert.Null(user); + Assert.Equal("wrong_account", denied!.Code); + } + + [Fact] + public void Microsoft_sign_in_can_be_limited_to_one_email_domain() + { + var options = Microsoft(domain: "contoso.com"); + var inside = WorkspaceIdentity.Map(options, Account(("oid", "1"), ("tid", "tenant-1"), ("preferred_username", "a@contoso.com"))); + var guest = WorkspaceIdentity.Map(options, Account(("oid", "2"), ("tid", "tenant-1"), ("preferred_username", "b@partner.org"))); + var noEmail = WorkspaceIdentity.Map(options, Account(("oid", "3"), ("tid", "tenant-1"))); + + Assert.NotNull(inside.User); + Assert.Equal("wrong_account", guest.Denied!.Code); + Assert.Equal("wrong_account", noEmail.Denied!.Code); + } + + [Fact] + public void An_account_with_no_identity_is_turned_away() + { + Assert.Equal("no_identity", WorkspaceIdentity.Map(Microsoft(), Account(("name", "x"))).Denied!.Code); + Assert.Equal("no_identity", WorkspaceIdentity.Map(Google(), Account(("name", "x"))).Denied!.Code); + } + + [Fact] + public void Accounts_from_different_providers_never_share_an_id() + { + var google = WorkspaceIdentity.Map(Google(), Account(("sub", "42"), ("email", "a@example.com"), ("email_verified", "true"), ("hd", "example.com"))); + var microsoft = WorkspaceIdentity.Map(Microsoft(), Account(("oid", "42"), ("tid", "tenant-1"))); + Assert.NotEqual(google.User!.Id, microsoft.User!.Id); + } +} + +public class WorkspaceSettingsTests +{ + [Fact] + public void Nothing_is_wrong_when_nothing_is_set_up() + { + var options = new WorkspaceOptions(); + Assert.False(options.IsConfigured); + Assert.False(options.Enabled); + Assert.Empty(options.Problems()); + } + + [Fact] + public void Missing_pieces_are_named_in_plain_words() + { + var google = new WorkspaceOptions { Provider = "Google" }.Problems(); + Assert.Contains(google, p => p.Contains("Workspace__ClientId")); + Assert.Contains(google, p => p.Contains("Workspace__ClientSecret")); + Assert.Contains(google, p => p.Contains("Workspace__Domain") && p.Contains("any Google account")); + + var microsoft = new WorkspaceOptions { Provider = "Microsoft", ClientId = "c", ClientSecret = "s" }.Problems(); + Assert.Single(microsoft); + Assert.Contains("Workspace__TenantId", microsoft[0]); + + Assert.Contains(new WorkspaceOptions { Provider = "Okta", ClientId = "c", ClientSecret = "s" }.Problems(), + p => p.Contains("Microsoft or Google")); + } + + [Fact] + public void A_complete_set_is_enabled_and_names_the_right_sign_in_address() + { + var google = new WorkspaceOptions { Provider = "google", ClientId = "c", ClientSecret = "s", Domain = "example.com" }; + Assert.True(google.Enabled); + Assert.Equal("Google", google.ProviderName); + Assert.Equal("https://accounts.google.com", google.EffectiveAuthority); + + var microsoft = new WorkspaceOptions { Provider = "MICROSOFT", ClientId = "c", ClientSecret = "s", TenantId = "t-1" }; + Assert.True(microsoft.Enabled); + Assert.Equal("https://login.microsoftonline.com/t-1/v2.0", microsoft.EffectiveAuthority); + } + + [Theory] + [InlineData("/", "/")] + [InlineData(null, "/")] + [InlineData("", "/")] + [InlineData("/?printer=abc123", "/?printer=abc123")] + [InlineData("/panel?printer=abc#frag", "/panel?printer=abc")] + [InlineData("//evil.example", "/")] + [InlineData("https://evil.example", "/")] + [InlineData("/\\evil.example", "/")] + [InlineData("javascript:alert(1)", "/")] + [InlineData("/ok\r\nSet-Cookie: x=1", "/")] + public void Sign_in_can_only_send_people_back_to_a_page_on_this_site(string? asked, string expected) => + Assert.Equal(expected, AuthController.SafeReturnPath(asked)); +} + +// ---- the whole sign-in round trip, against a pretend Microsoft or Google --- + +/// Plays the part of the provider's sign-in service: its settings, its keys and its token exchange. +public sealed class FakeIdentityProvider : HttpMessageHandler +{ + public const string Issuer = "https://idp.test"; + public const string ClientId = "test-client"; + public const string ClientSecret = "test-secret"; + + private readonly RSA _rsa = RSA.Create(2048); + private readonly RsaSecurityKey _key; + private readonly Dictionary _codes = new(); + + public bool SawProofKey { get; private set; } + public int TokenRequests { get; private set; } + + public FakeIdentityProvider() => _key = new RsaSecurityKey(_rsa) { KeyId = "k1" }; + + /// The person approves on the provider's page: returns the address the browser is sent back to. + public Uri Approve(Uri authorizeAddress, params Claim[] claims) + { + var query = System.Web.HttpUtility.ParseQueryString(authorizeAddress.Query); + var code = Guid.NewGuid().ToString("N"); + _codes[code] = (query["nonce"]!, claims); + return new Uri($"{query["redirect_uri"]}?code={code}&state={Uri.EscapeDataString(query["state"]!)}"); + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var path = request.RequestUri!.AbsolutePath; + HttpResponseMessage Json(object body) => new(HttpStatusCode.OK) + { + Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"), + }; + + if (path.EndsWith("/.well-known/openid-configuration")) + return Task.FromResult(Json(new + { + issuer = Issuer, + authorization_endpoint = Issuer + "/authorize", + token_endpoint = Issuer + "/token", + jwks_uri = Issuer + "/jwks", + response_types_supported = new[] { "code" }, + subject_types_supported = new[] { "public" }, + id_token_signing_alg_values_supported = new[] { "RS256" }, + })); + + if (path == "/jwks") + { + var p = _rsa.ExportParameters(false); + return Task.FromResult(Json(new + { + keys = new[] + { + new { kty = "RSA", use = "sig", alg = "RS256", kid = "k1", + n = Base64UrlEncoder.Encode(p.Modulus), e = Base64UrlEncoder.Encode(p.Exponent) }, + }, + })); + } + + if (path == "/token") + { + TokenRequests++; + var form = request.Content!.ReadAsStringAsync(ct).Result + .Split('&').Select(x => x.Split('=', 2)) + .ToDictionary(x => Uri.UnescapeDataString(x[0]), x => Uri.UnescapeDataString(x[1].Replace('+', ' '))); + if (form["client_secret"] != ClientSecret || !_codes.TryGetValue(form["code"], out var pending)) + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest) + { + Content = new StringContent("{\"error\":\"invalid_grant\"}", Encoding.UTF8, "application/json"), + }); + _codes.Remove(form["code"]); + SawProofKey = form.ContainsKey("code_verifier"); + + var claims = (pending.Claims.Any(c => c.Type == "sub") ? pending.Claims : pending.Claims.Append(new Claim("sub", "sub-" + Guid.NewGuid()))) + .Append(new Claim("nonce", pending.Nonce)) + .Append(new Claim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)); + var token = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken( + Issuer, ClientId, claims, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow.AddMinutes(10), + new SigningCredentials(_key, SecurityAlgorithms.RsaSha256))); + return Task.FromResult(Json(new { id_token = token, access_token = "at", token_type = "Bearer", expires_in = 3600 })); + } + + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)); + } +} + +public class WorkspaceFactory : WebApplicationFactory +{ + public FakeIdentityProvider Idp { get; } = new(); + private readonly Dictionary _settings; + + public WorkspaceFactory(string provider, Dictionary? extra = null) + { + _settings = new Dictionary + { + ["Workspace:Provider"] = provider, + ["Workspace:ClientId"] = FakeIdentityProvider.ClientId, + ["Workspace:ClientSecret"] = FakeIdentityProvider.ClientSecret, + ["Workspace:Authority"] = FakeIdentityProvider.Issuer, + ["Workspace:Admins"] = "boss@example.com", + ["Workspace:DefaultQuota"] = "40", + ["Demo:Enabled"] = "false", + ["Auth:SigningKey"] = ApiFactory.Key, + ["RateLimit:LoginPerMinute"] = "1000", + ["RateLimit:PerMinute"] = "100000", + }; + if (provider == "Google") _settings["Workspace:Domain"] = "example.com"; + if (provider == "Microsoft") _settings["Workspace:TenantId"] = "tenant-1"; + foreach (var (key, value) in extra ?? new()) _settings[key] = value; + } + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Testing"); + builder.ConfigureAppConfiguration((_, config) => config.AddInMemoryCollection(_settings)); + builder.ConfigureServices(services => + services.Configure(AuthController.WorkspaceScheme, o => o.BackchannelHttpHandler = Idp)); + } + + public HttpClient Browser() => CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = true, + }); + + /// + /// Plays a person signing in: the app sends them to the provider, they approve, the provider sends them + /// back, and the app sends them on to the page with a token (or an error) in the address fragment. + /// + public async Task SignIn(HttpClient browser, string? returnTo, params Claim[] account) + { + var start = await browser.GetAsync("/api/auth/login" + (returnTo is null ? "" : "?returnTo=" + Uri.EscapeDataString(returnTo))); + Assert.Equal(HttpStatusCode.Redirect, start.StatusCode); + Assert.StartsWith(FakeIdentityProvider.Issuer + "/authorize", start.Headers.Location!.ToString()); + + var back = await browser.GetAsync(Idp.Approve(start.Headers.Location, account)); + Assert.Equal(HttpStatusCode.Redirect, back.StatusCode); + + var finish = await browser.GetAsync(back.Headers.Location); + Assert.Equal(HttpStatusCode.Redirect, finish.StatusCode); + return finish.Headers.Location!.OriginalString; + } + + public static string TokenIn(string address) => address[(address.IndexOf("#token=", StringComparison.Ordinal) + 7)..]; + + public HttpClient Api(string token) + { + var client = CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + return client; + } +} + +public class WorkspaceSignInTests +{ + private static Claim[] GoogleAccount(string email, string hd = "example.com", string verified = "true", string sub = "sub-1") => new[] + { + new Claim("sub", sub), new Claim("email", email), new Claim("email_verified", verified), + new Claim("hd", hd), new Claim("name", "Pat Doe"), + }; + + [Fact] + public async Task The_sign_in_screen_is_told_which_work_account_to_offer() + { + using var factory = new WorkspaceFactory("Google"); + var config = await factory.CreateClient().GetFromJsonAsync("/api/auth/config"); + Assert.Equal("google", config.GetProperty("provider").GetString()); + Assert.Equal("Google", config.GetProperty("providerName").GetString()); + Assert.Equal("example.com", config.GetProperty("domain").GetString()); + Assert.False(config.GetProperty("demo").GetBoolean()); + } + + [Fact] + public async Task A_person_in_the_domain_signs_in_and_gets_a_working_session() + { + using var factory = new WorkspaceFactory("Google"); + var browser = factory.Browser(); + + var landed = await factory.SignIn(browser, null, GoogleAccount("pat@example.com")); + + Assert.StartsWith("/#token=", landed); + Assert.True(factory.Idp.SawProofKey, "The code exchange should use PKCE."); + + var api = factory.Api(WorkspaceFactory.TokenIn(landed)); + var me = await api.GetFromJsonAsync("/api/auth/me"); + Assert.Equal("Pat Doe", me.GetProperty("name").GetString()); + Assert.False(me.GetProperty("isAdmin").GetBoolean()); + + // First sign-in creates the person with the workspace's default quota, and an empty list. + var quota = await api.GetFromJsonAsync("/api/jobs/quota"); + Assert.Equal(40, quota.GetProperty("total").GetInt32()); + Assert.Equal(0, quota.GetProperty("used").GetInt32()); + Assert.Empty((await api.GetFromJsonAsync("/api/jobs/held")).EnumerateArray()); + } + + [Fact] + public async Task The_same_person_signing_in_again_is_the_same_person() + { + using var factory = new WorkspaceFactory("Google"); + var first = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com")); + var second = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com")); + + var a = await factory.Api(WorkspaceFactory.TokenIn(first)).GetFromJsonAsync("/api/auth/me"); + var b = await factory.Api(WorkspaceFactory.TokenIn(second)).GetFromJsonAsync("/api/auth/me"); + Assert.Equal(a.GetProperty("userId").GetString(), b.GetProperty("userId").GetString()); + } + + [Fact] + public async Task An_administrator_in_the_list_gets_the_administrator_screen_and_nobody_else_does() + { + using var factory = new WorkspaceFactory("Google"); + + var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("Boss@example.com", sub: "boss")); + var bossApi = factory.Api(WorkspaceFactory.TokenIn(boss)); + Assert.True((await bossApi.GetFromJsonAsync("/api/auth/me")).GetProperty("isAdmin").GetBoolean()); + Assert.Equal(HttpStatusCode.OK, (await bossApi.GetAsync("/api/admin/setup")).StatusCode); + + var pat = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com")); + var patApi = factory.Api(WorkspaceFactory.TokenIn(pat)); + Assert.Equal(HttpStatusCode.Forbidden, (await patApi.GetAsync("/api/admin/setup")).StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, (await patApi.GetAsync("/api/admin/users")).StatusCode); + } + + [Fact] + public async Task The_administrator_sees_people_as_they_sign_in_and_can_set_their_quota() + { + using var factory = new WorkspaceFactory("Google"); + var pat = await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@example.com")); + var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss")); + var bossApi = factory.Api(WorkspaceFactory.TokenIn(boss)); + + var people = (await bossApi.GetFromJsonAsync("/api/admin/users")).EnumerateArray().ToList(); + var person = Assert.Single(people); + Assert.Equal("pat@example.com", person.GetProperty("email").GetString()); + + var id = person.GetProperty("userId").GetString(); + Assert.Equal(HttpStatusCode.OK, (await bossApi.PostAsJsonAsync("/api/admin/set-quota", new { userId = id, quota = 15 })).StatusCode); + var quota = await factory.Api(WorkspaceFactory.TokenIn(pat)).GetFromJsonAsync("/api/jobs/quota"); + Assert.Equal(15, quota.GetProperty("total").GetInt32()); + } + + [Theory] + [InlineData("pat@gmail.com", "", "true", "wrong_account")] // a personal account has no domain + [InlineData("pat@other.org", "other.org", "true", "wrong_account")] // another organisation + [InlineData("pat@example.com", "example.com", "false", "unverified_email")] + public async Task Accounts_that_do_not_belong_are_turned_away_with_a_reason(string email, string hd, string verified, string code) + { + using var factory = new WorkspaceFactory("Google"); + var claims = hd == "" + ? new[] { new Claim("sub", "x"), new Claim("email", email), new Claim("email_verified", verified), new Claim("name", "Pat") } + : GoogleAccount(email, hd, verified); + + var landed = await factory.SignIn(factory.Browser(), null, claims); + + Assert.Equal($"/#error={code}", landed); + } + + [Fact] + public async Task A_turned_away_account_gets_no_session_and_is_not_added() + { + using var factory = new WorkspaceFactory("Google"); + await factory.SignIn(factory.Browser(), null, GoogleAccount("pat@other.org", "other.org")); + + var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss")); + var people = await factory.Api(WorkspaceFactory.TokenIn(boss)).GetFromJsonAsync("/api/admin/users"); + Assert.Empty(people.EnumerateArray()); + } + + [Fact] + public async Task The_page_the_person_came_from_is_kept_such_as_a_printer_panels_address() + { + using var factory = new WorkspaceFactory("Google"); + var landed = await factory.SignIn(factory.Browser(), "/?printer=abc123", GoogleAccount("pat@example.com")); + Assert.StartsWith("/?printer=abc123#token=", landed); + } + + [Theory] + [InlineData("//evil.example/steal")] + [InlineData("https://evil.example/")] + public async Task Sign_in_cannot_be_used_to_send_people_to_another_site(string returnTo) + { + using var factory = new WorkspaceFactory("Google"); + var landed = await factory.SignIn(factory.Browser(), returnTo, GoogleAccount("pat@example.com")); + Assert.StartsWith("/#token=", landed); + } + + [Fact] + public async Task A_forged_return_from_the_provider_is_refused() + { + using var factory = new WorkspaceFactory("Google"); + var browser = factory.Browser(); + var response = await browser.GetAsync("/api/auth/callback?code=made-up&state=made-up"); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/#error=sign_in_failed", response.Headers.Location!.OriginalString); + Assert.Equal(0, factory.Idp.TokenRequests); // never even reached the code exchange + } + + [Fact] + public async Task Finishing_sign_in_without_having_started_it_gives_nothing() + { + using var factory = new WorkspaceFactory("Google"); + var response = await factory.Browser().GetAsync("/api/auth/complete"); + Assert.Equal("/#error=sign_in_failed", response.Headers.Location!.OriginalString); + } + + [Fact] + public async Task A_Microsoft_account_signs_in_and_the_app_role_makes_an_administrator() + { + using var factory = new WorkspaceFactory("Microsoft"); + var landed = await factory.SignIn(factory.Browser(), null, + new Claim("oid", "o-1"), new Claim("tid", "tenant-1"), new Claim("preferred_username", "ada@contoso.com"), + new Claim("name", "Ada Lovelace"), new Claim("roles", "PullPrint.Admin")); + + var me = await factory.Api(WorkspaceFactory.TokenIn(landed)).GetFromJsonAsync("/api/auth/me"); + Assert.Equal("Ada Lovelace", me.GetProperty("name").GetString()); + Assert.True(me.GetProperty("isAdmin").GetBoolean()); + } + + [Fact] + public async Task A_Microsoft_account_from_another_tenant_is_turned_away() + { + using var factory = new WorkspaceFactory("Microsoft"); + var landed = await factory.SignIn(factory.Browser(), null, + new Claim("oid", "o-1"), new Claim("tid", "someone-elses-tenant"), new Claim("preferred_username", "x@elsewhere.com")); + Assert.Equal("/#error=wrong_account", landed); + } + + [Fact] + public async Task Setup_check_names_the_address_to_register_and_what_needs_attention() + { + using var factory = new WorkspaceFactory("Google", new() { ["Demo:Enabled"] = "true", ["Auth:SigningKey"] = "" }); + var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss")); + var setup = await factory.Api(WorkspaceFactory.TokenIn(boss)).GetFromJsonAsync("/api/admin/setup"); + + Assert.Equal("Google", setup.GetProperty("provider").GetString()); + Assert.Equal("example.com", setup.GetProperty("domain").GetString()); + Assert.Equal(40, setup.GetProperty("defaultQuota").GetInt32()); + Assert.EndsWith("/api/auth/callback", setup.GetProperty("redirectUri").GetString()); + + var warnings = string.Join("\n", setup.GetProperty("warnings").EnumerateArray().Select(w => w.GetString())); + Assert.Contains("No printers yet", warnings); + Assert.Contains("Demo sign-in is on", warnings); + Assert.Contains("Auth__SigningKey is not set", warnings); + } + + [Fact] + public async Task A_clean_setup_has_no_warnings_once_a_printer_is_added() + { + using var factory = new WorkspaceFactory("Google"); + var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss")); + var api = factory.Api(WorkspaceFactory.TokenIn(boss)); + Assert.Equal(HttpStatusCode.OK, (await api.PostAsJsonAsync("/api/admin/printers", new { name = "Level 3 East", location = "Third floor" })).StatusCode); + + var setup = await api.GetFromJsonAsync("/api/admin/setup"); + Assert.Empty(setup.GetProperty("warnings").EnumerateArray()); + Assert.Equal(1, setup.GetProperty("printers").GetInt32()); + } + + [Fact] + public async Task Half_finished_settings_switch_work_sign_in_off_and_say_why() + { + using var factory = new WorkspaceFactory("Google", new() { ["Workspace:ClientSecret"] = "", ["Demo:Enabled"] = "true" }); + + var config = await factory.CreateClient().GetFromJsonAsync("/api/auth/config"); + Assert.Equal("none", config.GetProperty("provider").GetString()); + Assert.Equal(HttpStatusCode.NotFound, (await factory.Browser().GetAsync("/api/auth/login")).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await factory.Browser().GetAsync("/api/auth/callback?code=x&state=y")).StatusCode); + + // The demo still works, and its administrator is told what is wrong. + var login = await factory.CreateClient().PostAsJsonAsync("/api/auth/demo-login", new { admin = true }); + var token = (await login.Content.ReadFromJsonAsync()).GetProperty("token").GetString()!; + var setup = await factory.Api(token).GetFromJsonAsync("/api/admin/setup"); + Assert.Contains("Workspace__ClientSecret", string.Join("\n", setup.GetProperty("warnings").EnumerateArray().Select(w => w.GetString()))); + } + + [Fact] + public async Task Work_sign_in_is_off_when_nothing_is_set_up() + { + using var factory = new ApiFactory(); + Assert.Equal(HttpStatusCode.NotFound, (await factory.CreateClient().GetAsync("/api/auth/login")).StatusCode); + var config = await factory.CreateClient().GetFromJsonAsync("/api/auth/config"); + Assert.Equal("none", config.GetProperty("provider").GetString()); + Assert.True(config.GetProperty("demo").GetBoolean()); + } + + [Fact] + public async Task A_work_session_stops_working_if_work_sign_in_is_switched_off() + { + string token; + using (var on = new WorkspaceFactory("Google")) + token = WorkspaceFactory.TokenIn(await on.SignIn(on.Browser(), null, GoogleAccount("pat@example.com"))); + + using var off = new ApiFactory(); // same signing key, no work sign-in + var client = off.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/jobs/quota")).StatusCode); + } + + [Fact] + public async Task A_workspace_starts_with_no_sample_people_and_no_printers() + { + using var factory = new WorkspaceFactory("Google"); + var boss = await factory.SignIn(factory.Browser(), null, GoogleAccount("boss@example.com", sub: "boss")); + var api = factory.Api(WorkspaceFactory.TokenIn(boss)); + + Assert.Empty((await api.GetFromJsonAsync("/api/admin/users")).EnumerateArray()); + Assert.Empty((await api.GetFromJsonAsync("/api/jobs")).EnumerateArray()); + Assert.Empty((await api.GetFromJsonAsync("/api/printers")).EnumerateArray()); + Assert.Equal(HttpStatusCode.NotFound, (await api.PostAsync("/api/jobs/sample", null)).StatusCode); // demo is off + } +} diff --git a/backend/Program.cs b/backend/Program.cs index f20975f..dc9377f 100644 --- a/backend/Program.cs +++ b/backend/Program.cs @@ -1,10 +1,233 @@ +using System.Security.Claims; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Authentication.OpenIdConnect; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Protocols.OpenIdConnect; +using Microsoft.IdentityModel.Tokens; +using PullPrintingBackend.Controllers; +using PullPrintingBackend.Services; + var builder = WebApplication.CreateBuilder(args); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); + +builder.Services.Configure(builder.Configuration.GetSection("Demo")); +builder.Services.Configure(builder.Configuration.GetSection("Auth")); +builder.Services.Configure(builder.Configuration.GetSection("Workspace")); + +builder.Services.AddSingleton(TimeProvider.System); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddHostedService(); builder.Services.AddControllers(); +// --- Authentication ------------------------------------------------------- +// Everyone ends up with the server's own session token (see AppTokenService), whether they signed in +// to a demo sandbox or with their organisation's Microsoft or Google work account. The work-account +// step is a normal OpenID Connect sign-in done here on the server, so the app needs no provider SDK. +builder.Services.AddAuthentication("Bearer") + .AddJwtBearer("Bearer", options => + { + options.MapInboundClaims = false; + options.Events = new JwtBearerEvents + { + OnTokenValidated = context => + { + var services = context.HttpContext.RequestServices; + var principal = context.Principal!; + var store = services.GetRequiredService(); + var name = principal.FindFirstValue(Claims.Name) ?? "Signed-in user"; + var isAdmin = principal.IsInRole(Claims.AdminRole); + switch (principal.FindFirstValue(Claims.Kind)) + { + case Claims.DemoKind when services.GetRequiredService>().Value.Enabled: + store.EnsureDemoUser(principal.UserId(), name, isAdmin); + break; + case Claims.WorkspaceKind when services.GetRequiredService>().Value.Enabled: + store.EnsureUser(principal.UserId(), name, isAdmin); + break; + default: + // The way this token was issued has been switched off since. + context.Fail("That kind of sign-in is switched off."); + break; + } + return Task.CompletedTask; + }, + }; + }) + .AddCookie(AuthController.ExternalScheme, options => + { + // Holds who the work account said you are for the few seconds between the two redirects. + options.Cookie.Name = ".pullprint.external"; + options.Cookie.SameSite = SameSiteMode.Lax; + options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; + options.ExpireTimeSpan = TimeSpan.FromMinutes(5); + options.SlidingExpiration = false; + options.Events.OnRedirectToLogin = context => + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + }; + }) + // Always registered, but only used when Workspace settings are complete (see AuthController.Login). + // Its settings are read when it is first used, so it needs nothing when the server runs on demo sign-in alone. + .AddOpenIdConnect(AuthController.WorkspaceScheme, _ => { }); + +builder.Services.AddOptions("Bearer") + .Configure((options, tokens) => + { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidIssuer = AppTokenService.Issuer, + ValidAudience = AppTokenService.Audience, + IssuerSigningKey = tokens.Key, + ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }, + NameClaimType = Claims.Name, + RoleClaimType = Claims.Role, + ClockSkew = TimeSpan.FromMinutes(1), + }; + }); + +builder.Services.AddOptions(AuthController.WorkspaceScheme) + .Configure>((options, workspace) => + { + var w = workspace.Value; + options.Authority = w.EffectiveAuthority; + options.ClientId = string.IsNullOrWhiteSpace(w.ClientId) ? "not-configured" : w.ClientId; + options.ClientSecret = string.IsNullOrWhiteSpace(w.ClientSecret) ? "not-configured" : w.ClientSecret; + options.RequireHttpsMetadata = w.RequireHttpsMetadata; + options.ResponseType = OpenIdConnectResponseType.Code; + options.UsePkce = true; + options.CallbackPath = "/api/auth/callback"; + options.SignInScheme = AuthController.ExternalScheme; + options.MapInboundClaims = false; + options.SaveTokens = false; + options.GetClaimsFromUserInfoEndpoint = false; + options.Scope.Clear(); + options.Scope.Add("openid"); + options.Scope.Add("profile"); + options.Scope.Add("email"); + options.CorrelationCookie.SameSite = SameSiteMode.Lax; + options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; + options.NonceCookie.SameSite = SameSiteMode.Lax; + options.NonceCookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; + options.TokenValidationParameters.NameClaimType = Claims.Name; + options.Events = new OpenIdConnectEvents + { + OnRedirectToIdentityProvider = context => + { + context.ProtocolMessage.Prompt = "select_account"; + // A hint that limits the account chooser to the organisation. The server still checks the account itself. + if (w.IsGoogle && !string.IsNullOrWhiteSpace(w.Domain)) + context.ProtocolMessage.SetParameter("hd", w.Domain!.TrimStart('@')); + return Task.CompletedTask; + }, + OnRemoteFailure = context => + { + context.Response.Redirect("/#error=sign_in_failed"); + context.HandleResponse(); + return Task.CompletedTask; + }, + }; + }); + +builder.Services.AddAuthorization(options => + options.AddPolicy(Claims.AdminPolicy, policy => policy.RequireRole(Claims.AdminRole))); + +// --- Abuse limits --------------------------------------------------------- +builder.Services.AddRateLimiter(_ => { }); +builder.Services.AddOptions().Configure((options, config) => +{ + var perMinute = config.GetValue("RateLimit:PerMinute", 300); + var loginsPerMinute = config.GetValue("RateLimit:LoginPerMinute", 20); + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.GlobalLimiter = PartitionedRateLimiter.Create(context => + RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "unknown", + _ => new FixedWindowRateLimiterOptions { PermitLimit = perMinute, Window = TimeSpan.FromMinutes(1) })); + options.AddPolicy("login", context => + RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "unknown", + _ => new FixedWindowRateLimiterOptions { PermitLimit = loginsPerMinute, Window = TimeSpan.FromMinutes(1) })); +}); + +// The app normally sits behind the host's proxy, which adds the real client address. +builder.Services.Configure(options => +{ + options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); +}); + +// Only needed when the web app is served from a different address, such as `flutter run`. +if (builder.Configuration.GetValue("Cors:AllowAnyOrigin")) +{ + builder.Services.AddCors(options => + options.AddDefaultPolicy(policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod())); +} + var app = builder.Build(); + +app.UseForwardedHeaders(); + +// Anything unexpected becomes a short JSON error. Details stay in the server log, never in the reply. +app.UseExceptionHandler(errors => errors.Run(async context => +{ + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + await context.Response.WriteAsJsonAsync( + new PullPrintingBackend.Models.ApiError("server_error", "Something went wrong on the server. Please try again.")); +})); + +app.Use(async (context, next) => +{ + var headers = context.Response.Headers; + headers["X-Content-Type-Options"] = "nosniff"; + headers["Referrer-Policy"] = "no-referrer"; + headers["X-Frame-Options"] = "DENY"; + headers["Content-Security-Policy"] = "frame-ancestors 'none'"; + await next(); +}); + +// The Flutter web build is served from wwwroot. Files that change on every deploy must not be cached. +app.UseDefaultFiles(); +app.UseStaticFiles(new StaticFileOptions +{ + OnPrepareResponse = context => + { + var name = context.File.Name; + if (name is "index.html" or "flutter_service_worker.js" or "flutter_bootstrap.js" or "version.json") + context.Context.Response.Headers.CacheControl = "no-cache"; + }, +}); + +// The work-account callback only exists once Microsoft or Google sign-in is set up. +app.Use(async (context, next) => +{ + if (context.Request.Path.StartsWithSegments("/api/auth/callback") && + !context.RequestServices.GetRequiredService>().Value.Enabled) + { + context.Response.StatusCode = StatusCodes.Status404NotFound; + return; + } + await next(); +}); + app.UseRouting(); -app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); +if (builder.Configuration.GetValue("Cors:AllowAnyOrigin")) app.UseCors(); +app.UseRateLimiter(); +app.UseAuthentication(); +app.UseAuthorization(); + +app.MapGet("/healthz", () => Results.Ok(new { status = "ok" })).DisableRateLimiting(); +app.MapControllers(); + +if (app.Environment.WebRootFileProvider.GetFileInfo("index.html").Exists) + app.MapFallbackToFile("/{*path:regex(^(?!api/).*$)}", "index.html"); + app.Run(); + +/// Lets the integration tests start the app. +public partial class Program { } diff --git a/backend/PullPrintingBackend.csproj b/backend/PullPrintingBackend.csproj index e69de29..355a89a 100644 --- a/backend/PullPrintingBackend.csproj +++ b/backend/PullPrintingBackend.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + PullPrintingBackend + + + + + + + + diff --git a/backend/appsettings.Development.json b/backend/appsettings.Development.json new file mode 100644 index 0000000..4501bbf --- /dev/null +++ b/backend/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Demo": { + "Enabled": true + }, + "Cors": { + "AllowAnyOrigin": true + } +} diff --git a/backend/appsettings.json b/backend/appsettings.json new file mode 100644 index 0000000..b4cc71a --- /dev/null +++ b/backend/appsettings.json @@ -0,0 +1,26 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Microsoft.AspNetCore.DataProtection": "Error" + } + }, + "AllowedHosts": "*", + "Demo": { + "Enabled": false, + "SigningKey": "" + }, + "AzureAd": { + "TenantId": "", + "ClientId": "", + "AdminRole": "PullPrint.Admin" + }, + "RateLimit": { + "PerMinute": 300, + "LoginPerMinute": 20 + }, + "Cors": { + "AllowAnyOrigin": false + } +} diff --git a/backend/controllers/AdminController.cs b/backend/controllers/AdminController.cs index 13c2ca9..ac61cb7 100644 --- a/backend/controllers/AdminController.cs +++ b/backend/controllers/AdminController.cs @@ -1,19 +1,144 @@ +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; +using PullPrintingBackend.Models; using PullPrintingBackend.Services; -[ApiController] -[Route("api/[controller]")] -public class AdminController : ControllerBase +namespace PullPrintingBackend.Controllers { - private readonly UserService _userService; - public AdminController(UserService userService) => _userService = userService; - - [HttpPost("set-quota")] - public IActionResult SetQuota([FromBody] dynamic payload) + [ApiController] + [Route("api/[controller]")] + [Authorize(Policy = Claims.AdminPolicy)] + [RequestSizeLimit(16_384)] + public class AdminController : ControllerBase { - string userId = payload.userId; - int quota = payload.quota; - _userService.UpdateQuota(userId, quota); - return Ok(); + public const int MaxQuota = 10_000; + + private readonly IPrintStore _store; + private readonly WorkspaceOptions _workspace; + private readonly DemoOptions _demo; + private readonly AppTokenService _tokens; + + public AdminController(IPrintStore store, IOptions workspace, + IOptions demo, AppTokenService tokens) + { + _store = store; + _workspace = workspace.Value; + _demo = demo.Value; + _tokens = tokens; + } + + // ---- the setup check --------------------------------------------------- + + /// + /// A plain summary of how this server is set up and anything that needs attention, + /// including the address to register with Microsoft or Google. + /// + [HttpGet("setup")] + public SetupDto Setup() + { + var me = User.UserId(); + var warnings = new List(); + foreach (var problem in _workspace.Problems()) warnings.Add("Work account sign-in is not ready. " + problem); + if (_workspace.Enabled && _demo.Enabled) + warnings.Add("Demo sign-in is on, so anyone on the internet can sign in to a sample sandbox. Turn it off for real use (Demo__Enabled=false)."); + var printers = _store.Printers(me); + if (printers.Count == 0) warnings.Add("No printers yet. Add one so people can print."); + else if (printers.All(p => !p.Enabled)) warnings.Add("Every printer is switched off, so nobody can print."); + if (_workspace.Enabled && _tokens.UsesRandomKey) + warnings.Add("Auth__SigningKey is not set, so everyone is signed out whenever the server restarts."); + + var provider = _workspace.Enabled ? _workspace.ProviderName! + : _demo.Enabled ? "Demo only" + : "None"; + return new SetupDto( + provider, + _workspace.Enabled ? _workspace.ProviderName : null, + _workspace.Enabled ? _workspace.Domain : null, + _demo.Enabled, + _store.DefaultQuota(me) ?? PrintStore.DefaultQuotaPages, + _store.Users(me).Count, + printers.Count, + $"{Request.Scheme}://{Request.Host}/api/auth/callback", + warnings); + } + + // ---- people and quotas ------------------------------------------------- + + [HttpGet("users")] + public IEnumerable Users() => + _store.Users(User.UserId()).Select(u => new UserQuotaDto(u.UserId, u.Name, u.Quota, u.Email)); + + [HttpPost("set-quota")] + public IActionResult SetQuota([FromBody] SetQuotaRequest request) + { + if (string.IsNullOrWhiteSpace(request.UserId)) + return BadRequest(new ApiError("bad_request", "userId is required.")); + if (InvalidQuota(request.Quota, out var problem)) return problem!; + return _store.SetQuota(User.UserId(), request.UserId, request.Quota) + ? Ok() + : NotFound(new ApiError("not_found", "No such user.")); + } + + /// The pages a month that new people start with. + [HttpPost("default-quota")] + public IActionResult SetDefaultQuota([FromBody] QuotaValueRequest request) + { + if (InvalidQuota(request.Quota, out var problem)) return problem!; + return _store.SetDefaultQuota(User.UserId(), request.Quota) ? Ok() : NotFound(); + } + + /// Gives everyone the same pages a month, and returns how many people changed. + [HttpPost("set-quota-all")] + public IActionResult SetQuotaForAll([FromBody] QuotaValueRequest request) + { + if (InvalidQuota(request.Quota, out var problem)) return problem!; + return Ok(new { changed = _store.SetQuotaForAll(User.UserId(), request.Quota) }); + } + + // ---- printers ---------------------------------------------------------- + + [HttpPost("printers")] + public IActionResult AddPrinter([FromBody] PrinterRequest request) + { + if (InvalidPrinter(request, out var problem)) return problem!; + var printer = _store.AddPrinter(User.UserId(), request.Name!, request.Location ?? ""); + return printer is null + ? Conflict(new ApiError("too_many", $"At most {PrintStore.MaxPrinters} printers.")) + : Ok(printer); + } + + [HttpPut("printers/{id}")] + public IActionResult UpdatePrinter(string id, [FromBody] PrinterRequest request) + { + if (InvalidPrinter(request, out var problem)) return problem!; + return _store.UpdatePrinter(User.UserId(), id, request.Name!, request.Location ?? "", request.Enabled ?? true) + ? Ok() + : NotFound(new ApiError("not_found", "No such printer.")); + } + + [HttpDelete("printers/{id}")] + public IActionResult DeletePrinter(string id) => + _store.DeletePrinter(User.UserId(), id) ? Ok() : NotFound(new ApiError("not_found", "No such printer.")); + + // ---- checks ------------------------------------------------------------ + + private static bool InvalidQuota(int quota, out IActionResult? problem) + { + problem = quota is < 0 or > MaxQuota + ? new BadRequestObjectResult(new ApiError("bad_request", $"Quota must be between 0 and {MaxQuota} pages.")) + : null; + return problem is not null; + } + + private static bool InvalidPrinter(PrinterRequest request, out IActionResult? problem) + { + problem = null; + if (string.IsNullOrWhiteSpace(request.Name)) + problem = new BadRequestObjectResult(new ApiError("bad_request", "A printer needs a name.")); + else if (request.Name.Length > 60 || (request.Location?.Length ?? 0) > 100) + problem = new BadRequestObjectResult(new ApiError("bad_request", "Name up to 60 characters, location up to 100.")); + return problem is not null; + } } } diff --git a/backend/controllers/AuthController.cs b/backend/controllers/AuthController.cs index b495643..08ad126 100644 --- a/backend/controllers/AuthController.cs +++ b/backend/controllers/AuthController.cs @@ -1,18 +1,110 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using PullPrintingBackend.Models; using PullPrintingBackend.Services; -[ApiController] -[Route("api/[controller]")] -public class AuthController : ControllerBase +namespace PullPrintingBackend.Controllers { - private readonly AzureAuthService _authService; - public AuthController(AzureAuthService authService) => _authService = authService; - - [HttpPost("login")] - public IActionResult Login([FromBody] string token) + [ApiController] + [Route("api/[controller]")] + [RequestSizeLimit(16_384)] + public class AuthController : ControllerBase { - if (_authService.ValidateToken(token)) - return Ok(new { message = "Token valid" }); - return Unauthorized(); + public const string WorkspaceScheme = "Workspace"; + public const string ExternalScheme = "External"; + + private readonly IPrintStore _store; + private readonly AppTokenService _tokens; + private readonly DemoOptions _demo; + private readonly WorkspaceOptions _workspace; + private readonly TimeProvider _time; + + public AuthController(IPrintStore store, AppTokenService tokens, IOptions demo, + IOptions workspace, TimeProvider time) + { + _store = store; + _tokens = tokens; + _demo = demo.Value; + _workspace = workspace.Value; + _time = time; + } + + /// What the sign-in screen needs before anyone is signed in: which work account to offer. + [HttpGet("config")] + public AuthConfigDto Config() => new( + _workspace.Enabled ? _workspace.ProviderName!.ToLowerInvariant() : "none", + _workspace.Enabled ? _workspace.ProviderName : null, + _workspace.Enabled ? _workspace.Domain : null, + _demo.Enabled); + + /// + /// Demo sign-in: creates a private sandbox with sample documents and returns a token for it. + /// Not found unless Demo:Enabled is true. + /// + [HttpPost("demo-login")] + [EnableRateLimiting("login")] + public ActionResult DemoLogin([FromBody] DemoLoginRequest? request) + { + if (!_demo.Enabled) return NotFound(); + var user = _store.CreateDemoUser(request?.Admin ?? false); + return new SessionDto(_tokens.Create(user, Claims.DemoKind, _time), user.UserId, user.Name, user.IsAdmin); + } + + /// Who the token belongs to. + [HttpGet("me")] + [Authorize] + public MeDto Me() => new( + User.UserId(), + User.FindFirst(Claims.Name)?.Value ?? "Signed-in user", + User.IsInRole(Claims.AdminRole)); + + /// + /// Starts sign-in with the organisation's work account: sends the browser to Microsoft or Google. + /// is a path on this site to come back to, such as /?printer=abc. + /// + [HttpGet("login")] + [EnableRateLimiting("login")] + public IActionResult Login([FromQuery] string? returnTo) + { + if (!_workspace.Enabled) return NotFound(); + var properties = new AuthenticationProperties { RedirectUri = "/api/auth/complete" }; + properties.Items["returnTo"] = SafeReturnPath(returnTo); + return Challenge(properties, WorkspaceScheme); + } + + /// + /// Where the browser lands after the work account signed in. Checks the account belongs to this + /// organisation, then hands the app a session token in the address fragment, which never reaches a server log. + /// + [HttpGet("complete")] + public async Task Complete() + { + var result = await HttpContext.AuthenticateAsync(ExternalScheme); + await HttpContext.SignOutAsync(ExternalScheme); + + var returnTo = SafeReturnPath(result.Properties?.Items.TryGetValue("returnTo", out var saved) == true ? saved : null); + if (!result.Succeeded || result.Principal is null || !_workspace.Enabled) + return Redirect(returnTo + "#error=sign_in_failed"); + + var (person, denied) = WorkspaceIdentity.Map(_workspace, result.Principal); + if (person is null) return Redirect(returnTo + "#error=" + (denied?.Code ?? "sign_in_failed")); + + var user = _store.EnsureUser(person.Id, person.Name, person.IsAdmin, person.Email); + var token = _tokens.Create(user, Claims.WorkspaceKind, _time); + return Redirect(returnTo + "#token=" + token); + } + + /// Only paths on this site are allowed, so sign-in cannot be used to send people elsewhere. + public static string SafeReturnPath(string? path) + { + if (string.IsNullOrEmpty(path) || path.Length > 200) return "/"; + if (path[0] != '/' || path.StartsWith("//") || path.Contains('\\')) return "/"; + if (path.Any(char.IsControl)) return "/"; + var hash = path.IndexOf('#'); + return hash >= 0 ? path[..hash] : path; + } } } diff --git a/backend/controllers/JobsController.cs b/backend/controllers/JobsController.cs index bce8e4f..50f9d0e 100644 --- a/backend/controllers/JobsController.cs +++ b/backend/controllers/JobsController.cs @@ -1,31 +1,83 @@ +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Options; using PullPrintingBackend.Models; using PullPrintingBackend.Services; -[ApiController] -[Route("api/[controller]")] -public class JobsController : ControllerBase +namespace PullPrintingBackend.Controllers { - private readonly PrintService _printService; - private readonly UserService _userService; - private static List _jobs = new(); - - public JobsController(PrintService printService, UserService userService) + [ApiController] + [Route("api/[controller]")] + [Authorize] + [RequestSizeLimit(16_384)] + public class JobsController : ControllerBase { - _printService = printService; - _userService = userService; - } + public const int MaxDocumentsPerRelease = 50; - [HttpGet] - public IEnumerable GetJobs() => _jobs; + private readonly IPrintStore _store; + private readonly DemoOptions _demo; - [HttpPost("release")] - public IActionResult ReleaseJob([FromBody] PrintJob job) - { - var user = _userService.GetUserById(job.UserId); - if (user.PrintQuota <= 0) return Forbid("Quota exceeded"); - _printService.ReleaseJob(job, "DefaultPrinter"); - user.PrintQuota--; - return Ok(); + public JobsController(IPrintStore store, IOptions demo) + { + _store = store; + _demo = demo.Value; + } + + /// Every job in the administrator's own group. Administrators only. + [HttpGet] + [Authorize(Policy = Claims.AdminPolicy)] + public IReadOnlyList All() => _store.AllJobs(User.UserId()); + + /// The signed-in user's documents that are waiting to print, newest first. + [HttpGet("held")] + public IReadOnlyList Held() => _store.HeldJobs(User.UserId()); + + /// Pages used and allowed this month for the signed-in user. + [HttpGet("quota")] + public ActionResult MyQuota() => + _store.GetQuota(User.UserId()) is { } quota ? quota : NotFound(); + + /// + /// Prints the chosen documents. Only the caller's own waiting documents are used, + /// and nothing prints if the total would go over their quota. + /// + [HttpPost("release")] + public ActionResult Release([FromBody] ReleaseRequest request) + { + var ids = (request.JobIds ?? new List()).ToList(); + if (request.JobId is { Length: > 0 }) ids.Add(request.JobId); + ids = ids.Where(id => !string.IsNullOrWhiteSpace(id)).Distinct().ToList(); + if (ids.Count == 0) + return BadRequest(new ApiError("no_jobs", "Choose at least one document.")); + if (ids.Count > MaxDocumentsPerRelease) + return BadRequest(new ApiError("too_many", $"Print at most {MaxDocumentsPerRelease} documents at a time.")); + + var result = _store.Release(User.UserId(), ids, request.PrinterId); + return result.Outcome switch + { + ReleaseOutcome.Printed => new ReleaseResponse( + result.Printed.Select(j => j.Id).ToList(), result.Pages, result.Quota, result.PrinterName), + ReleaseOutcome.NoPrinter => Conflict(new ApiError( + "no_printer", "No printer has been set up yet. Ask an administrator.")), + ReleaseOutcome.PrinterUnavailable => Conflict(new ApiError( + "printer_unavailable", "That printer is not available. Choose another one.")), + ReleaseOutcome.OverQuota => Conflict(new ApiError( + "quota_exceeded", + $"Over your limit by {result.PagesOver} pages.", + result.PagesOver)), + _ => NotFound(new ApiError("not_found", "Those documents are not waiting to print.")), + }; + } + + /// Demo only: sends one more sample document to the signed-in user. + [HttpPost("sample")] + public ActionResult Sample() + { + if (!_demo.Enabled) return NotFound(); + var job = _store.AddSample(User.UserId()); + return job is null + ? Conflict(new ApiError("no_more_samples", "You already have plenty of documents waiting.")) + : job; + } } } diff --git a/backend/controllers/PrintersController.cs b/backend/controllers/PrintersController.cs new file mode 100644 index 0000000..831882e --- /dev/null +++ b/backend/controllers/PrintersController.cs @@ -0,0 +1,23 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PullPrintingBackend.Models; +using PullPrintingBackend.Services; + +namespace PullPrintingBackend.Controllers +{ + [ApiController] + [Route("api/[controller]")] + [Authorize] + public class PrintersController : ControllerBase + { + private readonly IPrintStore _store; + public PrintersController(IPrintStore store) => _store = store; + + /// + /// The printers people can print to. Administrators also see switched-off ones, so they can switch them back on. + /// + [HttpGet] + public IReadOnlyList List() => + _store.Printers(User.UserId()).Where(p => p.Enabled || User.IsInRole(Claims.AdminRole)).ToList(); + } +} diff --git a/backend/data/ApplicationDbContext.cs b/backend/data/ApplicationDbContext.cs deleted file mode 100644 index e69de29..0000000 diff --git a/backend/models/Dtos.cs b/backend/models/Dtos.cs new file mode 100644 index 0000000..108fb7d --- /dev/null +++ b/backend/models/Dtos.cs @@ -0,0 +1,37 @@ +namespace PullPrintingBackend.Models +{ + public record DemoLoginRequest(bool Admin = false); + + public record SessionDto(string Token, string UserId, string Name, bool IsAdmin); + + public record MeDto(string UserId, string Name, bool IsAdmin, string? Email = null); + + /// What the sign-in screen needs to know before anyone is signed in. + public record AuthConfigDto(string Provider, string? ProviderName, string? Domain, bool Demo); + + /// Send jobIds; a single jobId is also accepted. Without printerId the first enabled printer is used. + public record ReleaseRequest(List? JobIds = null, string? JobId = null, string? PrinterId = null); + + public record ReleaseResponse(List Printed, int Pages, Quota Quota, string? PrinterName); + + public record SetQuotaRequest(string? UserId, int Quota); + + public record QuotaValueRequest(int Quota); + + public record PrinterRequest(string? Name, string? Location, bool? Enabled); + + public record UserQuotaDto(string UserId, string Name, Quota Quota, string? Email = null); + + public record SetupDto( + string Provider, + string? ProviderName, + string? Domain, + bool DemoEnabled, + int DefaultQuota, + int People, + int Printers, + string RedirectUri, + List Warnings); + + public record ApiError(string Error, string Message, int? PagesOver = null); +} diff --git a/backend/models/PrintJob.cs b/backend/models/PrintJob.cs index 7a84b03..a0d8e9a 100644 --- a/backend/models/PrintJob.cs +++ b/backend/models/PrintJob.cs @@ -1,11 +1,21 @@ namespace PullPrintingBackend.Models { - public class PrintJob + public static class JobStatus { - public string Id { get; set; } - public string UserId { get; set; } - public string FileName { get; set; } - public bool IsReleased { get; set; } - public DateTime SubmittedAt { get; set; } + public const string Held = "Held"; + public const string Printed = "Printed"; + public const string Failed = "Failed"; } + + /// One document waiting to print, or already printed. Immutable, updated with with. + public record PrintJob( + string Id, + string UserId, + string UserName, + string FileName, + int Pages, + DateTimeOffset SubmittedAt, + string Status, + string? FailureReason = null, + string? PrinterName = null); } diff --git a/backend/models/Printer.cs b/backend/models/Printer.cs new file mode 100644 index 0000000..ea128af --- /dev/null +++ b/backend/models/Printer.cs @@ -0,0 +1,5 @@ +namespace PullPrintingBackend.Models +{ + /// A printer an administrator has set up. People can only print to enabled ones. + public record Printer(string Id, string Name, string Location, bool Enabled); +} diff --git a/backend/models/Quota.cs b/backend/models/Quota.cs index cce6f65..e7da194 100644 --- a/backend/models/Quota.cs +++ b/backend/models/Quota.cs @@ -1,8 +1,8 @@ namespace PullPrintingBackend.Models { - public class Quota + /// Pages used and allowed this month. + public record Quota(int Used, int Total) { - public string UserId { get; set; } - public int RemainingQuota { get; set; } + public int Left => Math.Max(Total - Used, 0); } } diff --git a/backend/models/User.cs b/backend/models/User.cs index 0ecb8bf..fd36e16 100644 --- a/backend/models/User.cs +++ b/backend/models/User.cs @@ -1,11 +1,28 @@ namespace PullPrintingBackend.Models { + /// A person known to the store. Mutated only while the store's lock is held. public class User { - public string Id { get; set; } - public string DisplayName { get; set; } - public string Email { get; set; } + public required string Id { get; init; } + public required string DisplayName { get; set; } + public string? Email { get; set; } public bool IsAdmin { get; set; } public int PrintQuota { get; set; } + public int PagesUsed { get; set; } + + /// The month the used pages count belongs to, as year * 100 + month. Pages reset when it changes. + public int QuotaPeriod { get; set; } + + public DateTimeOffset LastSeen { get; set; } + + /// + /// Who can see and manage this person. Everyone who signs in with a work account shares the + /// default group; each demo visitor and demo administrator gets a private one. + /// + public string SandboxId { get; init; } = "default"; + + public Quota Quota => new(PagesUsed, PrintQuota); } + + public record UserSummary(string UserId, string Name, bool IsAdmin, Quota Quota, string? Email = null); } diff --git a/backend/services/AuthServices.cs b/backend/services/AuthServices.cs new file mode 100644 index 0000000..84f8fbd --- /dev/null +++ b/backend/services/AuthServices.cs @@ -0,0 +1,99 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using PullPrintingBackend.Models; + +namespace PullPrintingBackend.Services +{ + public static class Claims + { + public const string UserId = "uid"; + public const string Name = "name"; + public const string Role = "role"; + public const string Kind = "kind"; + public const string AdminRole = "Admin"; + public const string UserRole = "User"; + public const string AdminPolicy = "Admin"; + + /// Token made by demo sign-in. + public const string DemoKind = "demo"; + + /// Token made after a work account (Microsoft or Google) signed in. + public const string WorkspaceKind = "workspace"; + } + + public class DemoOptions + { + /// Lets anyone sign in to a private sandbox. Turn off for anything real. + public bool Enabled { get; set; } + } + + public class AuthOptions + { + /// At least 32 characters. When empty a random key is made at start-up and everyone is signed out on restart. + public string? SigningKey { get; set; } + } + + /// + /// Makes and describes the server's own session tokens. Whoever signs in, with a demo sandbox or a + /// work account, gets the same kind of token, so nothing else needs to know how they signed in. + /// + public class AppTokenService + { + public const string Issuer = "pullprint"; + public const string Audience = "pullprint"; + + public SymmetricSecurityKey Key { get; } + + /// True when no signing key was set, so tokens stop working at every restart. + public bool UsesRandomKey { get; } + + public AppTokenService(IOptions options, IConfiguration config, ILogger log) + { + // "Demo:SigningKey" is the older name for the same setting. + var configured = options.Value.SigningKey; + if (string.IsNullOrWhiteSpace(configured)) configured = config["Demo:SigningKey"]; + + if (string.IsNullOrWhiteSpace(configured)) + { + log.LogInformation("Auth:SigningKey is not set, using a random key. Everyone is signed out when the app restarts."); + Key = new SymmetricSecurityKey(RandomNumberGenerator.GetBytes(48)); + UsesRandomKey = true; + } + else + { + if (configured.Length < 32) + throw new InvalidOperationException("Auth:SigningKey must be at least 32 characters."); + Key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configured)); + } + } + + public string Create(UserSummary user, string kind, TimeProvider time) + { + var now = time.GetUtcNow(); + var token = new JwtSecurityToken( + issuer: Issuer, + audience: Audience, + claims: new[] + { + new Claim(Claims.UserId, user.UserId), + new Claim(Claims.Name, user.Name), + new Claim(Claims.Role, user.IsAdmin ? Claims.AdminRole : Claims.UserRole), + new Claim(Claims.Kind, kind), + }, + notBefore: now.UtcDateTime, + expires: now.AddHours(8).UtcDateTime, + signingCredentials: new SigningCredentials(Key, SecurityAlgorithms.HmacSha256)); + return new JwtSecurityTokenHandler().WriteToken(token); + } + } + + public static class ControllerUser + { + public static string UserId(this ClaimsPrincipal user) => + user.FindFirstValue(Claims.UserId) ?? throw new InvalidOperationException("Signed-in user has no id."); + } +} diff --git a/backend/services/AzureAuthService.cs b/backend/services/AzureAuthService.cs deleted file mode 100644 index 1b9f2fc..0000000 --- a/backend/services/AzureAuthService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using Microsoft.Identity.Client; - -namespace PullPrintingBackend.Services -{ - public class AzureAuthService - { - private readonly string _tenantId = "YOUR_TENANT_ID"; - private readonly string _clientId = "YOUR_CLIENT_ID"; - - public bool ValidateToken(string token) - { - // Implement Azure AD JWT validation here - return true; - } - } -} diff --git a/backend/services/DemoCleanupService.cs b/backend/services/DemoCleanupService.cs new file mode 100644 index 0000000..fc6424a --- /dev/null +++ b/backend/services/DemoCleanupService.cs @@ -0,0 +1,25 @@ +namespace PullPrintingBackend.Services +{ + /// Removes visitors who have been idle for two hours, with their documents. + public class DemoCleanupService : BackgroundService + { + private readonly IPrintStore _store; + private readonly ILogger _log; + + public DemoCleanupService(IPrintStore store, ILogger log) + { + _store = store; + _log = log; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromMinutes(10)); + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + var removed = _store.Sweep(); + if (removed > 0) _log.LogInformation("Removed {Count} idle visitors.", removed); + } + } + } +} diff --git a/backend/services/PrintDispatcher.cs b/backend/services/PrintDispatcher.cs new file mode 100644 index 0000000..119e21e --- /dev/null +++ b/backend/services/PrintDispatcher.cs @@ -0,0 +1,24 @@ +using PullPrintingBackend.Models; + +namespace PullPrintingBackend.Services +{ + /// + /// Sends a released job to a physical printer. Throw to mark the job as failed; + /// the message becomes the failure reason shown to administrators. + /// + public interface IPrintDispatcher + { + void Print(PrintJob job, Printer printer); + } + + /// Demo dispatcher: logs the job and prints nothing. + public class SimulatedPrintDispatcher : IPrintDispatcher + { + private readonly ILogger _log; + public SimulatedPrintDispatcher(ILogger log) => _log = log; + + public void Print(PrintJob job, Printer printer) => + _log.LogInformation("Simulated print: {File} ({Pages} pages) for {User} on {Printer}", + job.FileName, job.Pages, job.UserName, printer.Name); + } +} diff --git a/backend/services/PrintService.cs b/backend/services/PrintService.cs deleted file mode 100644 index 8ccbba2..0000000 --- a/backend/services/PrintService.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Printing; -using PullPrintingBackend.Models; - -namespace PullPrintingBackend.Services -{ - public class PrintService - { - public void ReleaseJob(PrintJob job, string printerName) - { - LocalPrintServer server = new LocalPrintServer(); - PrintQueue queue = server.GetPrintQueue(printerName); - queue.AddJob(job.FileName); - job.IsReleased = true; - } - } -} diff --git a/backend/services/PrintStore.cs b/backend/services/PrintStore.cs new file mode 100644 index 0000000..ee9a2c4 --- /dev/null +++ b/backend/services/PrintStore.cs @@ -0,0 +1,505 @@ +using Microsoft.Extensions.Options; +using PullPrintingBackend.Models; + +namespace PullPrintingBackend.Services +{ + public enum ReleaseOutcome { Printed, NothingToPrint, OverQuota, NoPrinter, PrinterUnavailable } + + public record ReleaseResult( + ReleaseOutcome Outcome, + IReadOnlyList Printed, + int Pages, + int PagesOver, + Quota Quota, + string? PrinterName = null); + + /// Users, printers, jobs and quotas. The only place that decides who may print what. + public interface IPrintStore + { + /// A person who signed in with a work account. Added to the shared group on first sight. + UserSummary EnsureUser(string id, string name, bool isAdmin, string? email = null); + + /// A demo visitor. Creates their private sandbox the first time, and again if it was cleaned up. + UserSummary EnsureDemoUser(string id, string name, bool isAdmin); + + UserSummary CreateDemoUser(bool isAdmin); + Quota? GetQuota(string userId); + IReadOnlyList HeldJobs(string userId); + + /// Every job in the requester's own group. + IReadOnlyList AllJobs(string requesterId); + + /// Everyone else in the requester's own group, for the quota table. + IReadOnlyList Users(string requesterId); + + /// Prints the person's own waiting documents on a printer. All or nothing against their quota. + ReleaseResult Release(string userId, IReadOnlyCollection jobIds, string? printerId = null); + + /// Changes a quota. Only people in the requester's own group can be changed. + bool SetQuota(string requesterId, string userId, int quota); + + /// Pages a month for people who sign in for the first time. Null when the requester is unknown. + int? DefaultQuota(string requesterId); + + bool SetDefaultQuota(string requesterId, int quota); + + /// Sets everyone's quota in the requester's group and returns how many people changed. + int SetQuotaForAll(string requesterId, int quota); + + /// Printers in the requester's group, including switched-off ones. + IReadOnlyList Printers(string requesterId); + + Printer? AddPrinter(string requesterId, string name, string location); + bool UpdatePrinter(string requesterId, string printerId, string name, string location, bool enabled); + bool DeletePrinter(string requesterId, string printerId); + + PrintJob? AddSample(string userId); + int Sweep(); + } + + /// + /// In-memory store. Everything resets when the app restarts, and demo sandboxes that + /// have been idle for are removed. Swap for a database + /// by implementing . + /// + public class PrintStore : IPrintStore + { + public const int DefaultQuotaPages = 50; + public const int MaxHeldPerUser = 12; + public const int MaxVisitors = 300; + public const int MaxPrinters = 50; + public const string DefaultSandbox = "default"; + public static readonly TimeSpan IdleLifetime = TimeSpan.FromHours(2); + + private static readonly (string File, int Pages)[] SampleDocuments = + { + ("Q3 budget review.pdf", 12), + ("Site visit notes.docx", 3), + ("Contract draft v4.pdf", 28), + ("Floor plan.png", 1), + ("Meeting agenda.docx", 2), + ("Safety checklist.pdf", 6), + ("Onboarding guide.pdf", 18), + ("Site photo.png", 1), + }; + + private readonly object _gate = new(); + private readonly Dictionary _users = new(); + private readonly List _jobs = new(); + private readonly Dictionary> _printers = new(); + private readonly Dictionary _defaultQuota = new(); + private readonly IPrintDispatcher _dispatcher; + private readonly TimeProvider _time; + private int _sampleCursor; + + public PrintStore(IPrintDispatcher dispatcher, TimeProvider time, IOptions workspace) + { + _dispatcher = dispatcher; + _time = time; + // The shared group starts empty: real people and printers are added by signing in and by administrators. + _defaultQuota[DefaultSandbox] = Math.Max(workspace.Value.DefaultQuota, 0); + } + + private DateTimeOffset Now => _time.GetUtcNow(); + + private static int Period(DateTimeOffset t) => t.Year * 100 + t.Month; + + /// Pages are used up per calendar month (UTC), so a new month starts everyone at zero. + private void Normalize(User user) + { + var period = Period(Now); + if (user.QuotaPeriod == period) return; + user.PagesUsed = 0; + user.QuotaPeriod = period; + } + + private int DefaultFor(string sandbox) => + _defaultQuota.TryGetValue(sandbox, out var q) ? q : DefaultQuotaPages; + + // ---- demo sample data ------------------------------------------------ + + /// Sample people with a few jobs each, so a demo administrator has something to look at. + private void SeedSandbox(string sandbox, string idPrefix) + { + var now = Now; + AddUser(idPrefix + "u2", "Bob Reyes", used: 50, total: 50, sandbox); + AddUser(idPrefix + "u3", "Priya Nair", used: 8, total: 200, sandbox); + AddUser(idPrefix + "u4", "Marcus Lee", used: 20, total: 50, sandbox); + AddJob(idPrefix + "u2", "Bob Reyes", "report.docx", 3, now.AddMinutes(-30), JobStatus.Printed, printer: "Reception"); + AddJob(idPrefix + "u3", "Priya Nair", "Safety audit.pdf", 41, now.AddHours(-1), JobStatus.Held); + AddJob(idPrefix + "u4", "Marcus Lee", "Invoice 2291.pdf", 2, now.AddDays(-1), JobStatus.Failed, "printer offline"); + } + + private void SeedPrinters(string sandbox) + { + _printers[sandbox] = new List + { + new(NewId(), "Level 3 East", "Third floor, east wing", true), + new(NewId(), "Reception", "Ground floor", true), + new(NewId(), "Print room", "Second floor", true), + }; + } + + private User AddUser(string id, string name, int used, int total, string sandbox, bool admin = false, string? email = null) + { + var user = new User + { + Id = id, + DisplayName = name, + Email = email, + IsAdmin = admin, + PagesUsed = used, + PrintQuota = total, + QuotaPeriod = Period(Now), + LastSeen = Now, + SandboxId = sandbox, + }; + _users[id] = user; + return user; + } + + /// Alice Tan with her four waiting documents, as every demo visitor starts. + private User AddAlice(string id, string sandbox) + { + const string name = "Alice Tan"; + var user = AddUser(id, name, used: 12, total: DefaultQuotaPages, sandbox); + var now = Now; + AddJob(id, name, "Q3 budget review.pdf", 12, now.AddMinutes(-20), JobStatus.Held); + AddJob(id, name, "Site visit notes.docx", 3, now.AddMinutes(-40), JobStatus.Held); + AddJob(id, name, "Contract draft v4.pdf", 28, now.AddDays(-1), JobStatus.Held); + AddJob(id, name, "Floor plan.png", 1, now.AddDays(-1).AddHours(-1), JobStatus.Held); + return user; + } + + private PrintJob AddJob(string userId, string userName, string file, int pages, + DateTimeOffset at, string status, string? reason = null, string? printer = null) + { + var job = new PrintJob(NewId(), userId, userName, file, pages, at, status, reason, printer); + _jobs.Add(job); + return job; + } + + private static string NewId() => Guid.NewGuid().ToString("N")[..8]; + + private UserSummary Summary(User u) + { + Normalize(u); + return new(u.Id, u.DisplayName, u.IsAdmin, u.Quota, u.Email); + } + + // ---- people ------------------------------------------------------------ + + public UserSummary EnsureUser(string id, string name, bool isAdmin, string? email = null) + { + lock (_gate) + { + if (!_users.TryGetValue(id, out var user)) + user = AddUser(id, name, used: 0, total: DefaultFor(DefaultSandbox), DefaultSandbox, admin: isAdmin, email: email); + user.DisplayName = name; + user.IsAdmin = isAdmin; + if (email is not null) user.Email = email; + user.LastSeen = Now; + return Summary(user); + } + } + + public UserSummary EnsureDemoUser(string id, string name, bool isAdmin) + { + lock (_gate) + { + if (_users.TryGetValue(id, out var existing)) + { + existing.LastSeen = Now; + return Summary(existing); + } + + EvictOldestSandboxes(MaxVisitors - 1); + SeedPrinters(id); + if (isAdmin) + { + // A private copy of the sample people, so changes here affect nobody else. + SeedSandbox(id, idPrefix: id + "-"); + AddAlice(id + "-u1", id); + return Summary(AddUser(id, name, used: 0, total: DefaultQuotaPages, id, admin: true)); + } + return Summary(AddAlice(id, id)); + } + } + + public UserSummary CreateDemoUser(bool isAdmin) => + EnsureDemoUser("demo-" + NewId(), isAdmin ? "Administrator" : "Alice Tan", isAdmin); + + public Quota? GetQuota(string userId) + { + lock (_gate) + { + if (!_users.TryGetValue(userId, out var u)) return null; + Normalize(u); + return u.Quota; + } + } + + public IReadOnlyList HeldJobs(string userId) + { + lock (_gate) + return _jobs + .Where(j => j.UserId == userId && j.Status == JobStatus.Held) + .OrderByDescending(j => j.SubmittedAt) + .ToList(); + } + + private string? SandboxOf(string userId) => + _users.TryGetValue(userId, out var u) ? u.SandboxId : null; + + public IReadOnlyList AllJobs(string requesterId) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + return _jobs + .Where(j => sandbox is not null && SandboxOf(j.UserId) == sandbox) + .OrderByDescending(j => j.SubmittedAt) + .ToList(); + } + } + + public IReadOnlyList Users(string requesterId) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + return _users.Values + .Where(u => sandbox is not null && u.SandboxId == sandbox && !u.IsAdmin) + .OrderBy(u => u.DisplayName) + .Select(Summary) + .ToList(); + } + } + + // ---- printing ---------------------------------------------------------- + + public ReleaseResult Release(string userId, IReadOnlyCollection jobIds, string? printerId = null) + { + lock (_gate) + { + if (!_users.TryGetValue(userId, out var user)) + return new ReleaseResult(ReleaseOutcome.NothingToPrint, Array.Empty(), 0, 0, new Quota(0, 0)); + Normalize(user); + + // Only the caller's own waiting jobs can be released, whatever ids were sent. + var chosen = _jobs + .Where(j => j.UserId == userId && j.Status == JobStatus.Held && jobIds.Contains(j.Id)) + .ToList(); + if (chosen.Count == 0) + return new ReleaseResult(ReleaseOutcome.NothingToPrint, Array.Empty(), 0, 0, user.Quota); + + var available = _printers.TryGetValue(user.SandboxId, out var list) + ? list.Where(p => p.Enabled).OrderBy(p => p.Name).ToList() + : new List(); + var printer = printerId is null + ? available.FirstOrDefault() + : available.FirstOrDefault(p => p.Id == printerId); + if (printer is null) + return new ReleaseResult( + printerId is null ? ReleaseOutcome.NoPrinter : ReleaseOutcome.PrinterUnavailable, + Array.Empty(), 0, 0, user.Quota); + + var pages = chosen.Sum(j => j.Pages); + if (pages > user.Quota.Left) + return new ReleaseResult(ReleaseOutcome.OverQuota, Array.Empty(), pages, + pages - user.Quota.Left, user.Quota, printer.Name); + + var printed = new List(); + foreach (var job in chosen) + { + var index = _jobs.IndexOf(job); + try + { + _dispatcher.Print(job, printer); + _jobs[index] = job with { Status = JobStatus.Printed, PrinterName = printer.Name }; + user.PagesUsed += job.Pages; + printed.Add(_jobs[index]); + } + catch (Exception e) + { + _jobs[index] = job with { Status = JobStatus.Failed, FailureReason = e.Message, PrinterName = printer.Name }; + } + } + user.LastSeen = Now; + return new ReleaseResult(ReleaseOutcome.Printed, printed, printed.Sum(j => j.Pages), 0, user.Quota, printer.Name); + } + } + + // ---- quotas and settings ------------------------------------------------- + + public bool SetQuota(string requesterId, string userId, int quota) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + if (sandbox is null || !_users.TryGetValue(userId, out var user) || user.SandboxId != sandbox) + return false; + user.PrintQuota = quota; + return true; + } + } + + public int? DefaultQuota(string requesterId) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + return sandbox is null ? null : DefaultFor(sandbox); + } + } + + public bool SetDefaultQuota(string requesterId, int quota) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + if (sandbox is null) return false; + _defaultQuota[sandbox] = quota; + return true; + } + } + + public int SetQuotaForAll(string requesterId, int quota) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + if (sandbox is null) return 0; + var people = _users.Values.Where(u => u.SandboxId == sandbox && !u.IsAdmin).ToList(); + foreach (var person in people) person.PrintQuota = quota; + return people.Count; + } + } + + // ---- printers ------------------------------------------------------------ + + public IReadOnlyList Printers(string requesterId) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + return sandbox is not null && _printers.TryGetValue(sandbox, out var list) + ? list.OrderBy(p => p.Name).ToList() + : new List(); + } + } + + public Printer? AddPrinter(string requesterId, string name, string location) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + if (sandbox is null) return null; + if (!_printers.TryGetValue(sandbox, out var list)) _printers[sandbox] = list = new List(); + if (list.Count >= MaxPrinters) return null; + var printer = new Printer(NewId(), name.Trim(), location.Trim(), true); + list.Add(printer); + return printer; + } + } + + public bool UpdatePrinter(string requesterId, string printerId, string name, string location, bool enabled) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + if (sandbox is null || !_printers.TryGetValue(sandbox, out var list)) return false; + var index = list.FindIndex(p => p.Id == printerId); + if (index < 0) return false; + list[index] = new Printer(printerId, name.Trim(), location.Trim(), enabled); + return true; + } + } + + public bool DeletePrinter(string requesterId, string printerId) + { + lock (_gate) + { + var sandbox = SandboxOf(requesterId); + return sandbox is not null + && _printers.TryGetValue(sandbox, out var list) + && list.RemoveAll(p => p.Id == printerId) > 0; + } + } + + // ---- demo helpers and clean-up ----------------------------------------- + + public PrintJob? AddSample(string userId) + { + lock (_gate) + { + if (!_users.TryGetValue(userId, out var user)) return null; + var held = _jobs.Where(j => j.UserId == userId && j.Status == JobStatus.Held).ToList(); + if (held.Count >= MaxHeldPerUser) return null; + + // Prefer a document this person has not had yet, then one that is not waiting right now. + var ever = _jobs.Where(j => j.UserId == userId).Select(j => j.FileName).ToHashSet(); + var waiting = held.Select(j => j.FileName).ToHashSet(); + foreach (var avoid in new[] { ever, waiting }) + { + for (var i = 0; i < SampleDocuments.Length; i++) + { + var (file, pages) = SampleDocuments[(_sampleCursor + i) % SampleDocuments.Length]; + if (avoid.Contains(file)) continue; + _sampleCursor = (_sampleCursor + i + 1) % SampleDocuments.Length; + user.LastSeen = Now; + return AddJob(userId, user.DisplayName, file, pages, Now, JobStatus.Held); + } + } + return null; + } + } + + /// Removes demo sandboxes nobody has used for . + public int Sweep() + { + lock (_gate) + { + var cutoff = Now - IdleLifetime; + var idle = _users.Values + .Where(u => u.SandboxId != DefaultSandbox) + .GroupBy(u => u.SandboxId) + .Where(g => g.Max(u => u.LastSeen) < cutoff) + .Select(g => g.Key) + .ToList(); + foreach (var sandbox in idle) RemoveSandbox(sandbox); + return idle.Count; + } + } + + /// How many demo sandboxes exist right now. + public int SandboxCount + { + get + { + lock (_gate) + return _users.Values.Where(u => u.SandboxId != DefaultSandbox).Select(u => u.SandboxId).Distinct().Count(); + } + } + + private void EvictOldestSandboxes(int keep) + { + var oldestFirst = _users.Values + .Where(u => u.SandboxId != DefaultSandbox) + .GroupBy(u => u.SandboxId) + .OrderBy(g => g.Max(u => u.LastSeen)) + .Select(g => g.Key) + .ToList(); + for (var i = 0; i < oldestFirst.Count - keep; i++) RemoveSandbox(oldestFirst[i]); + } + + private void RemoveSandbox(string sandbox) + { + var ids = _users.Values.Where(u => u.SandboxId == sandbox).Select(u => u.Id).ToHashSet(); + foreach (var id in ids) _users.Remove(id); + _jobs.RemoveAll(j => ids.Contains(j.UserId)); + _printers.Remove(sandbox); + _defaultQuota.Remove(sandbox); + } + } +} diff --git a/backend/services/UserService.cs b/backend/services/UserService.cs deleted file mode 100644 index cefb8a0..0000000 --- a/backend/services/UserService.cs +++ /dev/null @@ -1,17 +0,0 @@ -using PullPrintingBackend.Models; - -namespace PullPrintingBackend.Services -{ - public class UserService - { - private List _users = new(); - - public User GetUserById(string id) => _users.FirstOrDefault(u => u.Id == id); - - public void UpdateQuota(string userId, int quota) - { - var user = GetUserById(userId); - if (user != null) user.PrintQuota = quota; - } - } -} diff --git a/backend/services/WorkspaceOptions.cs b/backend/services/WorkspaceOptions.cs new file mode 100644 index 0000000..9166f12 --- /dev/null +++ b/backend/services/WorkspaceOptions.cs @@ -0,0 +1,126 @@ +using System.Security.Claims; + +namespace PullPrintingBackend.Services +{ + /// + /// Connects the server to the organisation's work accounts, Microsoft Entra ID or Google Workspace. + /// People sign in with their normal work account; the server decides who may do what. + /// + public class WorkspaceOptions + { + /// Microsoft or Google. Leave empty for demo-only. + public string? Provider { get; set; } + + public string? ClientId { get; set; } + public string? ClientSecret { get; set; } + + /// Microsoft only: the tenant (directory) id. + public string? TenantId { get; set; } + + /// + /// Google: the Workspace domain, required. Microsoft: optional extra limit to one email domain. + /// + public string? Domain { get; set; } + + /// Email addresses of administrators, separated by commas, semicolons or spaces. + public string? Admins { get; set; } + + /// Microsoft only: an app role that also makes someone an administrator. + public string AdminRole { get; set; } = "PullPrint.Admin"; + + /// Pages a month for a person who signs in for the first time. + public int DefaultQuota { get; set; } = 50; + + /// Overrides the provider's sign-in address. Only for tests and special set-ups. + public string? Authority { get; set; } + + public bool RequireHttpsMetadata { get; set; } = true; + + public bool IsMicrosoft => string.Equals(Provider, "Microsoft", StringComparison.OrdinalIgnoreCase); + public bool IsGoogle => string.Equals(Provider, "Google", StringComparison.OrdinalIgnoreCase); + public bool IsConfigured => !string.IsNullOrWhiteSpace(Provider); + + /// Plain-words reasons the settings cannot be used. Empty means ready. + public IReadOnlyList Problems() + { + var problems = new List(); + if (!IsConfigured) return problems; + if (!IsMicrosoft && !IsGoogle) + problems.Add($"Workspace__Provider is \"{Provider}\". Use Microsoft or Google."); + if (string.IsNullOrWhiteSpace(ClientId)) problems.Add("Workspace__ClientId is missing."); + if (string.IsNullOrWhiteSpace(ClientSecret)) problems.Add("Workspace__ClientSecret is missing."); + if (IsMicrosoft && string.IsNullOrWhiteSpace(TenantId)) problems.Add("Workspace__TenantId is missing."); + if (IsGoogle && string.IsNullOrWhiteSpace(Domain)) + problems.Add("Workspace__Domain is missing. Without it any Google account could sign in."); + if (DefaultQuota < 0) problems.Add("Workspace__DefaultQuota cannot be negative."); + return problems; + } + + public bool Enabled => IsConfigured && Problems().Count == 0; + + public string? ProviderName => IsMicrosoft ? "Microsoft" : IsGoogle ? "Google" : null; + + /// The address the person is sent to in order to sign in. + public string EffectiveAuthority => + !string.IsNullOrWhiteSpace(Authority) ? Authority! + : IsMicrosoft ? $"https://login.microsoftonline.com/{TenantId}/v2.0" + : "https://accounts.google.com"; + + public IReadOnlySet AdminEmails => + (Admins ?? "") + .Split(new[] { ',', ';', ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries) + .Select(e => e.Trim().ToLowerInvariant()) + .ToHashSet(); + } + + public record WorkspaceUser(string Id, string Name, string? Email, bool IsAdmin); + + /// Why a work account was turned away, in words for the person. + public record WorkspaceDenied(string Code, string Message); + + /// Turns what the provider says about a person into who they are here, or says why not. + public static class WorkspaceIdentity + { + public static (WorkspaceUser? User, WorkspaceDenied? Denied) Map(WorkspaceOptions options, ClaimsPrincipal principal) + { + string? Claim(string type) => principal.FindFirstValue(type); + + var email = (Claim("email") ?? Claim("preferred_username") ?? Claim("upn"))?.Trim().ToLowerInvariant(); + var domain = options.Domain?.Trim().TrimStart('@').ToLowerInvariant(); + var name = Claim("name") ?? email ?? "Signed-in user"; + + string? id; + if (options.IsGoogle) + { + id = Claim("sub"); + if (id is null) return (null, new("no_identity", "The sign-in did not say who you are.")); + if (!string.Equals(Claim("email_verified"), "true", StringComparison.OrdinalIgnoreCase)) + return (null, new("unverified_email", "Your email address is not verified with Google.")); + if (domain is not null && + !string.Equals(Claim("hd"), domain, StringComparison.OrdinalIgnoreCase)) + return (null, NotInDomain(domain)); + id = "g-" + id; + } + else + { + id = Claim("oid") ?? Claim("sub"); + if (id is null) return (null, new("no_identity", "The sign-in did not say who you are.")); + var tenant = Claim("tid"); + if (options.TenantId is { Length: > 0 } && tenant is not null && + !string.Equals(tenant, options.TenantId, StringComparison.OrdinalIgnoreCase)) + return (null, new("wrong_account", "That account belongs to a different organisation.")); + id = "m-" + id; + } + + if (domain is not null && (email is null || !email.EndsWith("@" + domain, StringComparison.Ordinal))) + return (null, NotInDomain(domain)); + + var isAdmin = (email is not null && options.AdminEmails.Contains(email)) || + (options.IsMicrosoft && principal.FindAll("roles").Any(c => c.Value == options.AdminRole)); + return (new WorkspaceUser(id, name, email, isAdmin), null); + } + + private static WorkspaceDenied NotInDomain(string domain) => + new("wrong_account", $"That account is not part of {domain}. Sign in with your work account."); + } +} diff --git a/docs/01-product-brief.md b/docs/01-product-brief.md new file mode 100644 index 0000000..bc82a76 --- /dev/null +++ b/docs/01-product-brief.md @@ -0,0 +1,45 @@ +# 01 Product brief + +## The one job + +A person has sent a document to print. They walk to a printer, prove who they are, and get their pages. **Everything in the design serves that walk-up moment.** Sending a file and administering quotas matter, but they are not where speed is won or lost. + +## Who uses it + +| User | What they want | Where | +|---|---|---| +| Staff member | Collect their printing quickly and leave | At a printer panel, sometimes on their phone | +| Administrator | See all jobs, set page quotas, spot failures | Desktop browser | + +A staff member is usually standing, often carrying things, and has no patience for menus. Design for that person, not for someone sitting at a desk. + +## Speed targets + +These are targets to design and test against, not measurements. + +| Task | Target | +|---|---| +| Sign in at the printer to seeing own documents | Under 5 seconds with a card, under 15 with a phone code | +| Seeing own documents to pages printing | One tap (documents are pre-selected) | +| Whole walk-up visit | Under 10 seconds with a card | +| Taps needed to print everything waiting | 1 after sign-in | + +## Principles + +1. **One obvious action per screen.** The Print button is the largest thing on the release screen. +2. **Pre-select everything.** Most people want all their waiting documents. Unticking is the exception. +3. **Show only what is theirs.** No other person's file names, ever. This is the point of the product. +4. **Say how many pages and how many are left.** Quota surprises are the main thing that stops a print. +5. **Big touch targets.** At least 44 px on phone and web, at least 64 px on the printer panel. +6. **Sign out for them.** The panel signs out automatically so the next person never sees the last user's list. +7. **Plain words.** No jargon such as "release", "held" or "spool" in user-facing text. See [wording](03-screen-specs.md#wording). + +## Scope of the mockups + +In scope: phone sign-in, phone job list, phone confirmation, printer panel sign-in, release and confirmation, admin jobs and quotas. + +Out of scope for now: how a file reaches the server (no submission path exists in the code yet), printer settings such as duplex or colour, card reader hardware, notifications. + +## What exists in the code today + +The Flutter app has a login screen, a held-jobs list and an admin list. The .NET API has release and set-quota endpoints. See the [README status](../README.md#current-status) for what does not work yet. The mockups are the target design; they do not describe current behaviour. diff --git a/docs/02-user-flows.md b/docs/02-user-flows.md new file mode 100644 index 0000000..068fc25 --- /dev/null +++ b/docs/02-user-flows.md @@ -0,0 +1,60 @@ +# 02 User flows + +Diagrams use Mermaid, which GitHub renders in the page. + +## Flow A: print at the printer panel (main flow) + +```mermaid +flowchart LR + A[Send file to Pull Print
from any computer] --> B[Server keeps it waiting] + B --> C[Walk up to a printer] + C --> D[K1 Sign in] + D --> E[K2 Your documents
all ticked] + E -->|Print| F[K3 Printing] + F -->|Sign out or 20 s timeout| D + E -->|Untick some, Print| F +``` + +Screens: [K1](03-screen-specs.md#k1-printer-panel--sign-in), [K2](03-screen-specs.md#k2-printer-panel--your-documents), [K3](03-screen-specs.md#k3-printer-panel--printing). + +| Step | User does | Screen shows | System does | +|---|---|---|---| +| 1 | Walks up | Sign-in with phone code (card later) | Requests a device code from Microsoft | +| 2 | Enters code on phone, taps confirm | Documents list, all ticked, total pages and pages left | Fetches only this user's waiting jobs | +| 3 | Taps Print | Printing confirmation, pages left | Sends jobs to the printer, reduces quota by pages printed | +| 4 | Leaves | Auto sign-out after 20 seconds | Clears the session on the panel | + +## Flow B: print from the phone + +```mermaid +flowchart LR + P1[P1 Sign in] --> P2[P2 Waiting to print
pick jobs and printer] + P2 -->|Print| P3[P3 Sent to printer] + P3 -->|Back to my jobs| P2 +``` + +This flow lets someone release from their phone without using the panel. See [open decision 3](05-open-decisions.md#3-should-phone-release-require-being-at-the-printer): it weakens the "only when you are at the printer" rule unless the app confirms the person is near it. + +## Flow C: administrator + +```mermaid +flowchart LR + L[Sign in as admin] --> J[A1 Jobs] + J --> Q[Users and quotas] + Q -->|Edit number, Save| Q + J -->|Filter by status or search| J +``` + +## Error and edge cases + +Each needs a designed screen or message before build. Wording is in [03](03-screen-specs.md#states-to-design-next). + +| Case | What the person should see | What they can do | +|---|---|---| +| No documents waiting | "Nothing waiting to print" | Sign out | +| Selection is over quota | Print disabled, how many pages over | Untick documents, or ask admin | +| Quota is zero | "You have no pages left this month" | Sign out, contact admin | +| Printer offline or out of paper | Printer name and the problem | Try another printer, which keeps the jobs waiting | +| Sign-in code expired | "That code has expired" and a new code | Get a new code | +| Network lost | "Cannot reach the print server" | Retry | +| Job failed | Job marked as failed with reason | Try again; the job stays waiting | diff --git a/docs/03-screen-specs.md b/docs/03-screen-specs.md new file mode 100644 index 0000000..1b1e920 --- /dev/null +++ b/docs/03-screen-specs.md @@ -0,0 +1,133 @@ +# 03 Screen specs + +Seven screens. Images are the mockups in [`design/screens/`](design/screens/). + +> The pictures below are the **mockups** the app was built from. For pictures of the screens as built, see [Getting started](Getting%20started.md). + +## Wording + +| Avoid | Use | +|---|---| +| Release | Print | +| Held job, spooled | Waiting to print, "Your documents" | +| Quota | Pages left this month | +| Authenticate, credentials | Sign in | +| Error: 403 | A sentence that says what happened and what to do | + +--- + +## P1 Phone: sign in + +![Phone sign in](design/screens/01-phone-sign-in.png) + +**Purpose:** get the person signed in, and tell a first-time user what the product does in three lines. + +- Dark hero with the printer illustration (a sheet feeds out of it, animated). White sheet below holds the heading and three step cards. +- One button: **Sign in with Microsoft** or **Sign in with Google**, whichever your organisation uses (the server says which), in that company's button style. In the demo it is the Microsoft button and signs in to sample data. +- Under the button, one line says who can sign in, for example "Use your @example.com account. No new password." +- If an account is turned away, a red box above the button says why in plain words and stays until the next try. +- "How it works" is three numbered steps. This is the in-app guide for new users. +- No registration, no password field. Identity comes from the work account. + +## P2 Phone: waiting to print + +![Phone job list](design/screens/02-phone-my-jobs.png) + +**Purpose:** see own waiting documents and print the ones wanted. + +- Pages-left bar at the top. +- Dark header with greeting and a ring showing pages left. +- Each job is a whole row that toggles a checkbox. Shows a document thumbnail with file-type strip, file name, page count, when it was sent. Selecting updates the button and totals live; over quota disables the button and says by how many pages. +- Selected rows have a thick blue border and a tick, so selection is not shown by colour alone. +- Bottom bar: chosen printer and one button that states what it will do, "Print 2 jobs · 15 pages". Tap the printer to pick another when there is more than one. With none set up it says "No printer available" and Print stays off. +- Sign-out is an icon button with an accessible label. + +## P3 Phone: sent to printer + +![Phone confirmation](design/screens/03-phone-sent.png) + +**Purpose:** confirm it worked and show pages left. + +- Tick, "Sent to Level 3 East", the list of what was sent, and the new pages-left figure. +- One secondary button: **Back to my jobs**. + +## K1 Printer panel: sign in + +![Panel sign in](design/screens/04-panel-sign-in.png) + +**Purpose:** identify the person at the printer. Screen is 1024 × 600, touch. + +- Left: dark panel with logo, heading, reassurance line and the printer illustration. +- Right, primary: sign in with phone. A short code is shown large; the person enters it at `microsoft.com/devicelogin` on their own phone, then taps **I have entered the code**. This is the standard Microsoft device-code sign-in, so no keyboard is needed on the panel. +- Right, secondary: tap staff card, marked "Coming later". This becomes the fast path once readers exist. +- Header shows the printer name and status so people know which printer they are at. + +## K2 Printer panel: your documents + +![Panel release](design/screens/05-panel-release.png) + +**Purpose:** print everything with one tap. The most important screen. + +- Header: name, pages left, **Sign out** (always visible). +- Documents are cards with large thumbnails, 4 across; the whole card toggles. Documents sent today are ticked by default. +- Footer: running total ("2 documents · 15 pages"), pages left after printing, and the **Print** button (300 × 72 px, largest element). +- If the selection is over quota, the footer says by how many pages and Print is disabled. + +## K3 Printer panel: printing + +![Panel printing](design/screens/06-panel-printing.png) + +**Purpose:** confirm and clear the session. + +- "Printing 15 pages", "Collect your documents from the tray", pages left. +- **Print more** returns to K2. **Sign out** returns to K1. +- Signs out automatically after 20 seconds, with a visible message saying so. + +## A1 Admin: setup, printers, people and jobs + +![Admin](design/screens/07-admin.png) + +**Purpose:** set the system up once, keep printers and page limits right, find failed jobs. + +- **Setup** card first: "Setup is complete", or "Finish setting up" with each thing still to do in plain words, and (for Microsoft or Google) the exact sign-in address to register with a **Copy** button. +- Four counts: waiting, printed today, failed, people out of quota. +- **Printers**: add, rename, switch off and remove. **Copy panel link** gives the address to open on that printer's own screen, which fixes it to that printer. +- **People and quotas**: **New people start with** (a default), **Give everyone** (asks to confirm, because it replaces every limit), then one row per person with an editable number and **Save**. People appear the first time they sign in. +- **All jobs** table with search and status filter. Status is a text label, with a failure reason where there is one. +- Layout is fluid. Tables scroll sideways inside their box on narrow screens. + +--- + +## States and how they are handled + +Each is built in the app and covered by a test. Wording is exact. + +| Screen | State | What happens | +|---|---|---| +| P2, K2 | Select all | The button above the list ticks every document, then reads **Clear** | +| P2, K2 | One document longer than the pages left | "This document needs 28 pages. You have 8 left." Print is off | +| P2, K2 | More than one document, over quota | "Over your limit by 5 pages. Untick one." | +| P2, K2 | No pages left | "No pages left this month." | +| P3, K3 | Only some documents printed | The ones that printed are listed, and "1 document could not be printed and is still waiting." | +| P2, K2 | Nothing printed | A message, and the person stays on their list | +| P2, K2 | The list was out of date | "Those documents are not waiting to print. Your list has been refreshed." | +| K2 | No touch for 60 seconds | Signed out, with "You were signed out because the screen was idle." | +| any | Session ended (server restart, 8 hours) | Back to sign-in with "Your session has ended. Please sign in again." | +| any | Too many requests | "Too many requests. Please wait a minute and try again." | +| any, demo | Banner | "Demo: nothing is really printed." and **What is this?**, which has **Start over** | + +Already built and not repeated above: "Nothing waiting to print." with **Send sample documents** (demo) or "Send a file to Pull Print from your computer.", "Cannot reach the print server." with **Try again**, and "No jobs match." with **Clear filters** on the administrator screen. + +Not built yet, described for when they are: + +| Screen | State | Message | +|---|---|---| +| K1 | Phone code expired | "That code has expired." Button: "Get a new code" | +| K3 | Printer problem | "The printer is out of paper. Your documents are still waiting." | + +## Accessibility checks applied + +- Controls are real buttons, links, inputs and labels. +- Text contrast is at least 4.5:1 against its background. +- Touch targets: 44 px minimum on phone and web, 64 px on the panel. +- Selected and status states use a label, shape or border as well as colour. diff --git a/docs/04-design-guidelines.md b/docs/04-design-guidelines.md new file mode 100644 index 0000000..1d0080e --- /dev/null +++ b/docs/04-design-guidelines.md @@ -0,0 +1,70 @@ +# 04 Design guidelines + +The visual style is deliberately plain: a utility people use in ten seconds and forget. + +## Imagery and logos + +**Not used:** AI-generated images or mascots, stock photos, emoji, gradient washes, glow or glass effects. + +**Used:** + +| Item | Source | Notes | +|---|---|---| +| Microsoft logo on the sign-in button | Microsoft's published four-square mark and sign-in button rules | Required for "Sign in with Microsoft". Colours `#F25022 #7FBA00 #00A4EF #FFB900`, white button, grey border, grey text. Replace the drawn copy with the asset from Microsoft's branding page before release. | +| Pull Print mark | Our own, a document with text lines on the primary blue | Placeholder until the organisation supplies its own logo. | +| Printer illustration | Our own flat vector, two blues, one animated sheet | Used on sign-in and confirmation screens. Replace with a photo of the real printer once available. | +| Document thumbnails | Drawn from the file type: page with title bar and text lines, a file-type strip (PDF, DOCX, PNG) | In the build, replace with a real first-page preview from the server. | +| Avatars | Initials on a flat colour | Replace with the Microsoft profile photo if available. | + +Only outline icons where text cannot do the job (sign out, printer, status). Each has a text or accessible label. + +Guide images: the mockups in [`design/screens/`](design/screens/) for now. After build, use real screenshots with numbered callouts and a photo of the actual printer panel. + +## Colour + +| Role | Value | Use | +|---|---|---| +| Background | `#F4F6F8` | Screen background | +| Surface | `#FFFFFF` | Cards, header, footer | +| Text | `#16212C` | Body and headings | +| Muted text | `#4A5866` | Secondary text (7:1 on white) | +| Border | `#D5DBE1` | Card and field outlines | +| Primary | `#0B5CAD` | Print button, selection | +| Hero navy | `#0E2A47` | Headers, sign-in and confirmation backgrounds | +| Waiting | text on `#FFF0D1`, text `#6B4200` | Status label | +| Failed | text on `#FBE3E3`, text `#7A1F1F` | Status label | + +One accent colour. Status is always a word, never colour alone. + +## Type + +Inter, falling back to the system font. Sizes in px. + +| Use | Phone and web | Printer panel | +|---|---|---| +| Screen heading | 20–32 | 28–44 | +| Row title | 16 | 20 | +| Secondary text | 14 | 16–18 | +| Primary button | 17 | 24 | + +Minimum text size is 13 px on phone and web, 16 px on the panel. + +## Sizing and spacing + +- Touch targets: 44 px minimum, 64 px on the panel. +- Rows are whole-row tap targets. +- Spacing steps: 8, 12, 16, 24, 32. +- Corner radius: 10–12 px on controls and cards. +- Primary button is the largest element on the screen. + +## Mapping to Flutter + +`frontend/lib/utils/theme.dart` currently uses `Colors.blue` and a blue app bar. Replace it with a `ThemeData` built from the table above (`ColorScheme.fromSeed` is not enough on its own, set the values explicitly). Keep `JobCard` as the row widget but make it a checkbox row with the sizes above, and make `QuotaIndicator` read "38 of 50 pages left" rather than "used / total pages". + +## Checklist before a screen is done + +- One primary action, visible without scrolling. +- Works at 390 px wide (phone) or 1024 × 600 (panel). +- Contrast checked, targets measured. +- Empty, over-quota and error states exist. +- Wording matches the [word list](03-screen-specs.md#wording). diff --git a/docs/05-open-decisions.md b/docs/05-open-decisions.md new file mode 100644 index 0000000..b934472 --- /dev/null +++ b/docs/05-open-decisions.md @@ -0,0 +1,53 @@ +# 05 Open decisions + +Questions that change the design. Each has a recommendation, but the answer is yours. + +## 1. Is quota counted in pages or in jobs? + +The README says quota "goes down by one" per print, which reads as per job. `QuotaIndicator` and the mockups use pages. Pages is fairer and matches paper cost, but it needs the server to know the page count of every job. + +**Recommendation:** pages. The mockups assume it. + +## 2. How does someone sign in at the printer? + +Built so far: the person signs in with their work account (Microsoft or Google) in the browser on the panel. Still open: the phone-code screen from the mockups (the person enters a short code on their own phone, so nobody types a password on a shared screen), and staff cards. Card is faster, but needs readers and a mapping from card to user. + +**Recommendation:** add the phone code next, since it keeps passwords off a shared screen. Add card when hardware exists. Card would then be the 5-second path. + +## 2b. Quotas by group? + +Pages are per person today, with a default for new people and one number for everyone. Real organisations want "students 30, staff 200". That needs the directory (Microsoft Graph groups or Google organisational units). + +**Recommendation:** after real-tenant testing, map one or two groups to quotas. Keep the per-person override. + +## 3. Should phone release require being at the printer? + +The product promise is that jobs print only when you are standing at the printer. If the phone can release to any printer, someone can print to a printer in another room and leave it in the tray. + +Options: (a) phone view only shows jobs and sends people to the panel, (b) the phone must scan a code shown on the panel, (c) allow it, accept the risk. + +**Recommendation:** (b). P2 would swap "Printer: Level 3 East" for a scan step. + +## 4. What happens to jobs nobody collects? + +Waiting jobs stay on the server. Options: expire after a set time (for example 24 hours) and say so on screen, or keep until deleted. + +**Recommendation:** expire after 24 hours and show "Deleted after 24 hours" under each job. This is also better for privacy. + +## 5. What happens when selection exceeds quota? + +Drawn as: Print disabled and the shortfall shown. Alternative: print as many whole documents as fit. + +**Recommendation:** as drawn. It is predictable. + +## 6. How do files reach the server? + +Nothing in the code creates a waiting job. This sets the whole front of the flow: a Windows print driver or print queue, email-to-print, a web upload page, or the phone app. It is not designed here. + +**Recommendation:** decide before building the panel, because it determines the file types and the page-count source. + +## 7. Does the panel run the Flutter app? + +K1–K3 are sized for a 1024 × 600 touch screen. Running the same Flutter app in a kiosk mode on a small Windows or Linux device is the shortest route, and Flutter has Windows and Linux targets in this repo. + +**Recommendation:** yes, with a kiosk route that has no back navigation and auto sign-out. diff --git a/docs/06-demo-hosting.md b/docs/06-demo-hosting.md new file mode 100644 index 0000000..d9f00f0 --- /dev/null +++ b/docs/06-demo-hosting.md @@ -0,0 +1,67 @@ +# 06 Hosting the demo + +How to put the demo online for free so anyone with the link can try it. + +## What you get + +One address that serves the web app and the API together. Each visitor signs in to a private sandbox with sample documents. Nothing is printed, nothing is kept for long, and nobody can see anyone else's documents. + +## Option 1: Render (free plan) + +1. Create a free account at [render.com](https://render.com) and connect your GitHub account. +2. Choose **New**, then **Blueprint**, and pick this repository. Render reads `render.yaml` and sets everything up: one web service, built from the `Dockerfile`, with a generated signing key. +3. Wait for the first build. It builds the web app and the API, so it takes several minutes. +4. Open the address Render gives you. Share it. + +To update the demo, push to the branch Render watches. It rebuilds on its own (`autoDeploy`). + +## Option 2: any host that runs a Docker image + +The `Dockerfile` works anywhere that runs a container and tells it which port to use through the `PORT` environment variable. + +```bash +docker build -t pull-print-demo . +docker run -p 8080:8080 -e Auth__SigningKey="$(openssl rand -base64 48)" pull-print-demo +``` + +Then open `http://localhost:8080`. + +## Settings + +Set these as environment variables on the host. Double underscores stand for the colon in the setting name. + +| Variable | Default | What it does | +|---|---|---| +| `Demo__Enabled` | `true` in the image | Lets visitors sign in to a sandbox. `false` turns demo sign-in off and invalidates demo tokens | +| `Auth__SigningKey` | random at start | At least 32 characters. Set it so visitors stay signed in when the server restarts. The Render blueprint generates one | +| `RateLimit__LoginPerMinute` | `20` | Sign-ins per minute from one address | +| `RateLimit__PerMinute` | `300` | All requests per minute from one address | +| `Workspace__*` | empty | Turns on Microsoft or Google work-account sign-in. See [09](09-connecting-your-workspace.md) | +| `Cors__AllowAnyOrigin` | `false` | Only needed if the web app is served from a different address | + +## What to expect from a free host + +- **It sleeps when idle.** Free plans usually stop a service after a quiet period. The first visitor afterwards waits a minute or so while it wakes up. The banner and sign-in screen load first, and sign-in works once it is up. +- **It forgets when it sleeps or restarts.** Data is in memory. A visitor who comes back after a restart is signed in again with fresh sample documents, or sees "Your session has ended" and signs in again. That is expected. +- **Limits can change.** Check the host's current free-plan terms before relying on it. + +## Checking it works + +Open `/healthz` on your address. It should answer `{"status":"ok"}`. Then open the address, sign in, and press Print. The pages-left figure should go down. + +## Things to know before sharing the link widely + +- Anyone with the link can sign in. That is the point of a demo, so keep real data out of it. +- Sign-in and request limits are per address. Many people behind one office or school network share a limit, which is generous for normal use but can be hit by a classroom all signing in at once. +- The app trusts the host's proxy to say who is calling, which is right for Render and similar hosts. If you put it behind something else, check that it sets `X-Forwarded-For`. +- The Microsoft and Google logos on the sign-in buttons are drawn to their rules. Replace them with the companies' own assets before any public launch. +- This page is about the sample-data demo. To use real accounts, printers and quotas, see [09 Connecting your workspace](09-connecting-your-workspace.md) and switch the demo off. + +## Option 3: Vercel (static, no server) + +The simplest free option needs no server at all. In this mode the app runs on its built-in sample data inside the visitor's browser, so every visitor already has their own private copy and nothing sleeps. + +- `vercel.json` and `scripts/vercel-build.sh` build the web app with `USE_MOCK=true`. Connect the repository to a Vercel project and it builds on every push. +- Data lives in the browser tab and resets when the page is reloaded. +- There is no API in this mode, so nothing can be shared between visitors and the administrator view only shows the built-in sample people. +- Use Option 1 or 2 when you want to show the real API. diff --git a/docs/08-review-and-fixes.md b/docs/08-review-and-fixes.md new file mode 100644 index 0000000..14a85e4 --- /dev/null +++ b/docs/08-review-and-fixes.md @@ -0,0 +1,72 @@ +# 08 Review and fixes + +A review of the demo from each kind of user's point of view, what went wrong or could go wrong, and what was done about it. "How it was found" says whether the problem came from reading the code, from an automated test, or from running the real app in a browser. + +## Fixed + +### First-time visitor +| What went wrong | Why it mattered | How it was found | Fix | +|---|---|---|---| +| The web page was still the Flutter template: tab title "pull_printing_app", description "A new Flutter project.", Flutter's icons | The first thing every visitor sees, and what link previews show | Reading the deployed page | Real title, description, link preview text, brand icons and manifest (`web/`) | +| A blank white page for several seconds while about 8 MB loads | Looks broken | Reading the page source | A branded loading screen that disappears at the first frame | +| The manifest locked the app to portrait | The printer panel is landscape | Reading the manifest | `orientation: any` | +| "Sign in with Microsoft" in the demo suggested a Microsoft account is needed | Visitors may hesitate or give up | Review | "No account needed. You get your own sample documents, and nothing is really printed." | +| A visitor who printed everything had no way back to the start | Stuck with an empty list | Review | **Start over** in the "What is this?" dialog | + +### Large text and small screens +| What went wrong | How it was found | Fix | +|---|---|---| +| At 1.5 times text size on a phone, **the Sign in button was pushed below the screen** with nothing to say it was there | Automated test at 1.5x text | Sign-in layout shrinks the printer picture, drops the step cards and adapts to text size | +| The Microsoft button text, the pages-left ring, the confirmation row and the panel's left column overflowed at large text | Same test, then 2x and the panel at 1.3x | Text wraps or scales down inside fixed shapes; document cards grow with text size | +| A 360 by 640 phone with the demo banner pushed Sign in off screen | Automated test | Compact sign-in layout | + +### Someone using the printer panel +| What went wrong | Fix | +|---|---| +| A person could walk away leaving their documents on a shared screen | The panel signs out after 60 seconds without a touch, with a message saying why. Any touch restarts the count | + +### Someone with a long document or few pages left +| What went wrong | Fix | +|---|---| +| "Untick one" when only one document is chosen made no sense | "This document needs 28 pages. You have 8 left." | +| Zero pages left gave the same message as being a few pages over | "No pages left this month." | +| Ticking each document by hand to print everything | **Select all** and **Clear** | +| Nowhere to go from a quota block in the demo | A demo tip points to the administrator demo, where limits can be raised | + +### When printing does not go as expected +| What went wrong | How it was found | Fix | +|---|---|---| +| The app assumed every chosen document printed, even if the server said only some did | Review of the API contract | The app uses the server's list of what printed, and says which documents are still waiting | +| If nothing printed, the person got a raw error | Review | A plain message, and they stay on their list | +| A list that was out of date ("documents are not waiting") left the person confused | Review | The message says the list was refreshed, and it is | +| Hitting the rate limit showed "error 429" | Review | "Too many requests. Please wait a minute and try again." | +| A session that ended (server restart, 8 hours) looked like "cannot reach the server" | Browser run | The person is signed out with "Your session has ended" | + +### Privacy and safety +| What went wrong | How it was found | Fix | +|---|---|---| +| The demo administrator's list showed **every visitor's documents**, against the promise that nobody else can see yours | Browser run with two visitors and an administrator | Every demo administrator gets a private copy of the sample people, and can only reach their own group | +| An unexpected server error could return details | Review | Always a short JSON error, details only in the server log | +| No basic security headers | Review | `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `frame-ancestors 'none'` | +| No limit on request size or on how many documents one request names | Review | 16 KB bodies, at most 50 documents, repeats counted once | +| A sample document that was just printed came straight back as the next sample | Browser run | New documents first | + +## Known and not fixed + +Each one is a GitHub issue. + +- Work-account sign-in (Microsoft and Google) has not been run against a real tenant. [#2](https://github.com/Hikki-dev/pull_printing_app/issues/2) +- Data is in memory only. [#3](https://github.com/Hikki-dev/pull_printing_app/issues/3) +- There is no way to send your own file. [#4](https://github.com/Hikki-dev/pull_printing_app/issues/4) +- Nothing is really printed. [#5](https://github.com/Hikki-dev/pull_printing_app/issues/5) +- Staff-card sign-in and the phone code sign-in from the mockups are not built. [#6](https://github.com/Hikki-dev/pull_printing_app/issues/6) +- The Pull Print mark, printer picture, thumbnails and Microsoft and Google marks are placeholders. [#7](https://github.com/Hikki-dev/pull_printing_app/issues/7) +- The browser Back button leaves the demo instead of going to the previous screen. [#8](https://github.com/Hikki-dev/pull_printing_app/issues/8) +- The app is light-only, English-only, and has not been checked with a screen reader on a real device. [#9](https://github.com/Hikki-dev/pull_printing_app/issues/9) +- Limits are per address, so a whole room behind one network address shares them. (Noted in [SECURITY.md](../SECURITY.md).) + +## How to repeat this review + +1. `dotnet test backend.Tests` and `flutter test` (the large-text, small-screen and idle tests are in `test/widget_test.dart`). +2. Build the web app, serve it, and click through it in a browser as a visitor, a visitor who runs out of pages, and an administrator. +3. Try 1.5 times and 2 times text size on a phone, and the panel at 1024 by 600. diff --git a/docs/09-connecting-your-workspace.md b/docs/09-connecting-your-workspace.md new file mode 100644 index 0000000..4345c8b --- /dev/null +++ b/docs/09-connecting-your-workspace.md @@ -0,0 +1,149 @@ +# 09 Connecting your workspace + +How to make Pull Print use your organisation's own accounts, so people sign in with the work account they already have, and you control the printers and each person's pages from one screen. + +Pick the one you use. It takes about ten minutes, and you do it once. + +> **Honest status.** The sign-in is built and tested against a **simulated** Microsoft/Google sign-in (the whole round trip, including refusing the wrong organisation). It has **not been run against a real tenant**, because that needs your account. Follow the steps below on a test tenant first. If something does not work, see [Fixing problems](Fixing%20problems.md); the **Setup** card on the administrator screen says what is missing, and [issue #2](https://github.com/Hikki-dev/pull_printing_app/issues/2) is where to report it. + +## How it works, in one picture + +![Six steps: press Sign in, sent to the provider, sign in there, the server checks, added if new, back in the app](images/sign-in-flow.svg) + +In short: + +``` +Person ──▶ "Sign in with Microsoft / Google" ──▶ their normal work sign-in + │ +Pull Print server ◀── who they are (checked here) ─────┘ + │ + ├─ is this person from our organisation? no ─▶ turned away, with a reason + ├─ new here? ─▶ added, with the default pages a month + ├─ on the administrators list? ─▶ gets the administrator screen + └─ shows only their own documents; prints only on printers you added +``` + +Two things live on the server, so there is one place to manage them: + +- **Printers.** You add each printer once (name and place). People pick one, or the printer's own screen is fixed to it. +- **People and pages.** Everyone appears the first time they sign in with the default pages a month. You change one person, or everyone, from the administrator screen. Pages start again on the 1st of each month (UTC). + +## What you need + +| | Microsoft 365 / Entra ID | Google Workspace | +|---|---|---| +| An account that can register apps | Application Administrator, or Global Administrator | Super admin of a Google Cloud project | +| The address people use | `https://` | `https://` | +| What you copy out | Application (client) ID, Directory (tenant) ID, a client secret | Client ID and client secret, and your domain such as `example.com` | + +`` is where you run the server (for example the Render address, or your own domain). It must be **https**. + +## Microsoft 365 (Entra ID) + +1. Open the **Microsoft Entra admin centre**, then **App registrations**, **New registration**. +2. Name it `Pull Print`. Under supported account types choose **Accounts in this organizational directory only**. +3. Under **Redirect URI** choose **Web** and enter `https:///api/auth/callback`. Register. +4. On the overview page copy the **Application (client) ID** and the **Directory (tenant) ID**. +5. Go to **Certificates & secrets**, **New client secret**, and copy the secret's **Value** now (it is shown once). +6. *(Optional, to make administrators without a list)* Under **App roles** create a role with value `PullPrint.Admin` for **Users/Groups**, then assign it to your administrators under **Enterprise applications**, **Users and groups**. +7. Set these on the server (see [Settings](#settings)): + + ``` + Workspace__Provider=Microsoft + Workspace__TenantId= + Workspace__ClientId= + Workspace__ClientSecret= + Workspace__Admins=you@yourcompany.com + ``` + +Only accounts from that tenant can sign in. To allow just one email domain inside it, also set `Workspace__Domain=yourcompany.com`. + +## Google Workspace + +1. Open the **Google Cloud console**, create or pick a project, then **APIs & Services**, **OAuth consent screen**. Choose **Internal** (only your Workspace organisation can sign in). Fill in the app name `Pull Print` and your support email. +2. Go to **Credentials**, **Create credentials**, **OAuth client ID**. Type **Web application**. +3. Under **Authorized redirect URIs** add `https:///api/auth/callback`. Create. +4. Copy the **Client ID** and **Client secret**. +5. Set these on the server: + + ``` + Workspace__Provider=Google + Workspace__ClientId= + Workspace__ClientSecret= + Workspace__Domain=example.com + Workspace__Admins=you@example.com + ``` + +`Workspace__Domain` is **required** for Google. Without it any Google account could sign in, so the server refuses to turn Google sign-in on. + +## Settings + +Set these as environment variables on the host. Double underscores stand for the colon. + +| Setting | Needed | What it does | +|---|---|---| +| `Workspace__Provider` | yes | `Microsoft` or `Google`. Leave empty for the demo only | +| `Workspace__ClientId` | yes | From the app registration or OAuth client | +| `Workspace__ClientSecret` | yes | Keep it secret. Never put it in the app or in Git | +| `Workspace__TenantId` | Microsoft | The directory (tenant) id | +| `Workspace__Domain` | Google: yes. Microsoft: optional | Only addresses ending `@domain` get in | +| `Workspace__Admins` | recommended | Email addresses of administrators, separated by commas or spaces | +| `Workspace__AdminRole` | no | Microsoft app role that also makes an administrator. Default `PullPrint.Admin` | +| `Workspace__DefaultQuota` | no | Pages a month for someone signing in for the first time. Default 50. Changeable on the administrator screen | +| `Auth__SigningKey` | **yes for real use** | At least 32 random characters. Without it everyone is signed out whenever the server restarts | +| `Demo__Enabled` | set to `false` | Turns the sample-data demo off. Leaving it on lets anyone on the internet open a sandbox | + +Generate a signing key with `openssl rand -base64 48`. + +## First sign-in: set up in four steps + +1. Open `https://` and sign in with an account in `Workspace__Admins`. You land on the **administrator** screen. +2. Read the **Setup** card at the top. It lists anything still to do in plain words, and shows the exact sign-in address to register. When nothing is left it says **Setup is complete**. +3. **Printers**: press **Add a printer** for each one (name, and where it is). Use **Copy panel link** to get that printer's own address. +4. **People and quotas**: set **New people start with** to your usual pages a month. People appear in the list as they first sign in. Use **Give everyone** to set the same number for the whole organisation at once, or set one person on their row. + +## At the printer + +Open the printer's **panel link** (`https:///?printer=`) on the screen next to the printer, in full screen. It is fixed to that printer, so people sign in, see their documents, and press **Print**, with no question about which printer. It signs people out after 60 seconds without a touch, and asks which account to use each time so the next person is never signed in as the last. + +On a phone, the same address without `?printer=` lets the person pick a printer. + +## What people and administrators see + +The sign-in button changes to match, and says who can use it: + +![Google](images/workspace-google-phone.png) ![Microsoft](images/workspace-microsoft-phone.png) + +Administrators get a Setup card. It lists what is still to do and shows the exact address to register in step 3 of the guides above: + +![Setup card with the sign-in address to register](images/setup-2-register-address.png) + +When nothing is left it says **Setup is complete**. Every screen is shown in [Getting started](Getting%20started.md). + +## When someone cannot sign in + +![A red box says That account is not allowed here](images/workspace-turned-away.png) + +| They see | Why | What to do | +|---|---|---| +| "That account is not allowed here" | Wrong organisation or domain, or a personal account | Sign in with the work account. Check `Workspace__TenantId` / `Workspace__Domain` | +| "Your email address is not verified" | Google says the address is not verified | Verify it in the Google account | +| "Your account did not tell us who you are" | The provider sent no identity | Check the app registration, then ask support | +| "Sign-in did not work" | The provider or the server failed | Try again. Check the server log and that the redirect address matches exactly | +| Sign-in button missing, only a demo | Settings incomplete | Open the server's `/api/auth/config`, or read the log: it names the missing setting | + +## Security notes + +- The provider's sign-in happens on Microsoft's or Google's own page. Pull Print never sees a password. +- The server then issues its own 8-hour session token. It reaches the app in the address after `#` and is removed from the address bar before the app starts, so it is not left in the browser history. +- The client secret stays on the server. +- Only your organisation can sign in. People only ever see their own documents, and quota is checked on the server. +- Administrators are decided by the server (the `Workspace__Admins` list or the app role). The app cannot grant it. +- Someone who is removed from your organisation can still use a session already issued, for up to 8 hours. Removing them from `Workspace__Admins` takes effect at their next sign-in. + +## What is not built yet + +- **Groups and departments.** Quotas are per person, with a default and "everyone". Setting pages by group (for example a Microsoft 365 group or a Google Workspace organisational unit) needs the directory APIs. Tracked in an issue. +- **Real printers and sending files.** Printers here are names the server prints to through `IPrintDispatcher`, which is simulated. See [05](05-open-decisions.md) and the open issues. +- **Native phone sign-in** with the platform's own account picker. The web app works on phones today. +- **A database.** People, printers and quotas are held in memory and are lost when the server restarts. Production needs `IPrintStore` backed by a database (issue #3). diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..b873e9c --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,17 @@ +# Questions and answers + +Short answers. For error messages and what to do about them, read [Fixing problems](Fixing%20problems.md). + +**Is anything really printed?** Not yet. Printing goes through `IPrintDispatcher`, which is simulated. A real printer needs a real dispatcher ([issue #5](https://github.com/Hikki-dev/pull_printing_app/issues/5)). + +**Can I send my own file?** Not yet. The demo makes sample documents. See [issue #4](https://github.com/Hikki-dev/pull_printing_app/issues/4). + +**When do page limits start again?** On the 1st of every month, UTC. + +**What is the difference between the live demo and the full stack?** The live demo on Vercel runs entirely in your browser on sample data. The full stack runs the real server, with its sign-in, printers and limits. See [Hosting the demo](06-demo-hosting.md). + +**Do I lose my data if the server restarts?** Yes, for now. People, printers, limits and documents are held in memory until a database backs `IPrintStore` ([issue #3](https://github.com/Hikki-dev/pull_printing_app/issues/3)). Sign-in sessions survive a restart only if `Auth__SigningKey` is set. + +**Who can see my documents?** Only you. The server ignores any document that is not yours and waiting. + +**Is this a finished product?** No. It is a working demo and a prototype of the idea. See the Limits in the [README](../README.md#limits). diff --git a/docs/Fixing problems.md b/docs/Fixing problems.md new file mode 100644 index 0000000..f999503 --- /dev/null +++ b/docs/Fixing problems.md @@ -0,0 +1,60 @@ +# Fixing problems + +Quick answers first, then fixes. If your problem is not here, [open an issue](https://github.com/Hikki-dev/pull_printing_app/issues/new/choose) and say what you pressed, what you saw, and what you expected. + +## Quick answers + +The short ones are in [Questions and answers](FAQ.md). The fixes are below. + +## People printing + +| You see | Why | What to do | +|---|---|---| +| **Over your limit by N pages. Untick one.** | The documents ticked need more pages than you have left | Untick a document. Your limit starts again on the 1st | +| **No pages left this month.** | You have used your pages | Ask your administrator for more, or wait for the 1st | +| **No printer available** | No printer is set up, or all are switched off | Ask your administrator to add one | +| **The printer could not print your documents. They are still waiting.** | The printer rejected them | Try again, or pick another printer. You were not charged | +| **Your list has been refreshed.** | The list on screen was out of date (for example you printed on another device) | Check the list and press Print again | +| **Your session has ended. Please sign in again.** | The session ran out (8 hours), or the server restarted | Sign in again | +| **Cannot reach the print server.** | No connection, or a free host is waking up | Wait a minute and press **Try again** | +| **Nothing waiting to print.** | You have no documents | In the demo, press **Send sample documents** | + +## People signing in + +| You see | Why | What to do | +|---|---|---| +| **That account is not allowed here** | Wrong organisation, wrong domain, or a personal account | Sign in with your work account | +| **Your email address is not verified** | Google says the address is not verified | Verify it in your Google account | +| **Your account did not tell us who you are** | The provider sent no identity | Tell your administrator | +| **Sign-in did not work. Please try again.** | The provider or the server failed, or you cancelled | Try again. Administrators: see below | +| Only a demo button, no work sign-in | Work sign-in is not set up, or its settings are incomplete | Administrators: see below | + +## Administrators + +| Problem | What to check | +|---|---| +| The Setup card lists things to do | Each line says what. They map to the settings in [Connecting your workspace](09-connecting-your-workspace.md#settings) | +| Sign-in shows only the demo | Open `/api/auth/config`. If `provider` is `none`, a `Workspace__*` setting is missing. The server log names the missing one | +| The provider says "redirect URI mismatch" | The address registered with Microsoft or Google must match exactly. The Setup card shows it, with a **Copy** button. It must be `https` | +| Everyone is signed out whenever the server restarts | Set `Auth__SigningKey` to 32 or more random characters | +| Someone who should be an administrator is not | Their email must be in `Workspace__Admins`, written as their work email. Microsoft: or assign the `PullPrint.Admin` app role. They must sign in again | +| A printer's own screen asks which printer | Open the **Copy panel link** address, not the plain address. It ends with `?printer=` and the printer's id | +| A panel link says No printer available | The printer in the link was removed or switched off | +| A person is missing from the list | People appear the first time they sign in | +| "Give everyone" changed someone I set by hand | It replaces every limit. Set their row again afterwards | +| Quota boxes refuse a number | Whole numbers from 0 to 10000 only | + +## Running it + +| Problem | What to do | +|---|---| +| `flutter run` shows sample data only | That is the default. For a real server pass `--dart-define=USE_MOCK=false` ([README](../README.md#run-it-yourself)) | +| The web app cannot reach the API | Build with `--dart-define=API_BASE_URL=...`, or serve the web build from the API's `wwwroot` so they share an address | +| `dotnet run` says demo sign-in is off | Set `Demo__Enabled=true`, or run with `ASPNETCORE_ENVIRONMENT=Development` | +| Sign-in works but you are bounced to sign-in at once | The signing key changed, or the server restarted. Set `Auth__SigningKey` | +| First visit to a free host is slow | Free hosts sleep when idle and take about a minute to wake | +| Tests fail on a fresh checkout | Run `flutter pub get`, then `flutter test` and `dotnet test backend.Tests`. CI runs the same | + +## Still stuck? + +Open an issue with the template. Say what you tried, and attach the server log with any secret removed. For anything about security, read [SECURITY.md](../SECURITY.md) first. diff --git a/docs/Getting started.md b/docs/Getting started.md new file mode 100644 index 0000000..6abe5a3 --- /dev/null +++ b/docs/Getting started.md @@ -0,0 +1,136 @@ +# Getting started + +This page walks through Pull Print one screen at a time, for the three kinds of people who use it: someone printing, someone at a printer's own screen, and an administrator. Every picture was taken from the running app. + +Click any picture on GitHub to open it full size. + +## Before you start + +You can try everything with nothing installed: open the [live demo](https://pull-print-demo.vercel.app). It runs on sample data, so nothing is really printed and no account is needed. + +To run your own copy, see the [README](../README.md#run-it-yourself). To use your organisation's accounts, see [Connecting your workspace](09-connecting-your-workspace.md). + +## If you are printing + +### Sign in + +![Phone sign in](images/phone-1-sign-in.png) + +Press the one button. There is no registration and no password: you sign in with your work account. In the demo, the same button opens a private sandbox and the banner at the top says so. + +Not sure what the demo is? Press **What is this?** in the banner. + +![About the demo](images/phone-1b-about-demo.png) + +### Choose what to print + +![Your documents](images/phone-2-documents.png) + +* Only **your own** documents are listed, newest first. +* The newest ones are ticked for you, stopping before anything goes over your limit. +* The ring shows how many pages you have left **this month**. It starts again on the 1st. +* Tap a document to tick or untick it. Tick **Select all** to choose everything. + +If you tick too much, Print switches off and says what to do: + +![Over the limit](images/phone-3-over-limit.png) + +Untick a document until the button works again. Nothing is charged until a document really prints. + +### Pick a printer + +If more than one printer is set up, tap the printer name at the bottom. + +![Pick a printer](images/phone-4-pick-printer.png) + +If you opened a printer's own link, the printer is already chosen and the name is not a button. + +### Print + +![Printed](images/phone-5-printed.png) + +The confirmation names the printer, lists what printed and shows your pages left. If the printer rejected some documents, they are named and stay on your list, and you are not charged for them. + +## If you are at a printer's own screen + +An administrator opens each printer's **panel link** on the screen next to the printer. It is fixed to that printer, so there is no question about where to print. + +![Printer screen sign in](images/panel-1-sign-in.png) + +Sign in with your work account (the staff-card option is drawn but not built yet). + +![Printer screen documents](images/panel-2-documents.png) + +Tap a document to include or leave it out, then press the large **Print** button. The printer's name and your pages left are at the top. + +![Printer screen over the limit](images/panel-2b-over-limit.png) + +Over the limit, the button is switched off and says so, the same as on a phone. + +![Printer screen printing](images/panel-3-printing.png) + +The screen signs you out 20 seconds after printing, and after 60 seconds without a touch, so the next person never sees your documents. You can always press **Sign out**. + +## If you are an administrator + +Sign in with an account on your administrators list. You land on the administrator screen, which has everything in the order you need it. + +![Administrator screen](images/admin-1-overview.png) + +### 1. Check the setup + +The first card says **Setup is complete**, or **Finish setting up** and lists each thing still to do in plain words. + +![Finish setting up](images/setup-1-finish.png) + +With Microsoft or Google it also shows the exact sign-in address to register, with a **Copy** button. + +![Sign-in address to register](images/setup-2-register-address.png) + +### 2. Add your printers + +![Printers](images/admin-2-printers.png) + +Press **Add a printer**, enter a name and where it is. + +![Add a printer](images/admin-5-add-printer.png) + +For each printer you can switch it **On or Off**, edit it, remove it, or press **Copy panel link**. Open the panel link on the screen next to that printer, in full screen. A switched-off printer is hidden from everyone but administrators, and nobody can print there. + +### 3. Set page limits + +![People and quotas](images/admin-3-people.png) + +* **New people start with** is the pages a month for anyone who signs in from now on. +* **Give everyone** sets the same number for the whole organisation. It asks first, because it replaces every limit: + + ![Apply to everyone](images/admin-6-apply-to-everyone.png) + +* Each person has a row. Change the number and press **Save**. The bar shows pages used this month, and turns red when none are left. +* People appear in the list the first time they sign in. + +### 4. Watch the jobs + +![All jobs](images/admin-4-jobs.png) + +Search by person or file, and filter by status. A failed job says why, for example "printer offline". + +## Signing in with a work account + +When the server is set up for Microsoft 365 or Google Workspace, the button changes to match and says who can use it. + +![Google](images/workspace-google-phone.png) ![Microsoft](images/workspace-microsoft-phone.png) + +Someone who is not allowed in sees the reason, and can try again: + +![Turned away](images/workspace-turned-away.png) + +If the demo is still on, a **Try the demo instead** link is shown too. Turn the demo off for real use (`Demo__Enabled=false`). + +![Work account with the demo on](images/workspace-with-demo.png) + +## What next + +* Something not working? See [Fixing problems](Fixing%20problems.md). +* Connect your own accounts: [Connecting your workspace](09-connecting-your-workspace.md). +* How the pieces fit and every route: [How it works](How%20it%20works.md). diff --git a/docs/How it works.md b/docs/How it works.md new file mode 100644 index 0000000..97496b5 --- /dev/null +++ b/docs/How it works.md @@ -0,0 +1,213 @@ +# How it works + +How the pieces fit, what the server decides, and every route with an example. + +## The pieces + +![A person sends a document, the server holds it, they sign in at the printer and press Print, the server checks their pages and sends it to the printer](images/how-it-fits.svg) + +In detail: + +``` +Visitor's browser or phone + │ + ▼ +Flutter app (frontend/lib) + screens ── PrintRepository ─┬─ MockPrintRepository sample data inside the app (offline demo, tests) + └─ HttpPrintRepository ──▶ ApiService ──▶ HTTPS + │ +ASP.NET Core API (backend) ▼ + controllers: Auth · Printers · Jobs · Admin ── PrintStore (in memory) ── IPrintDispatcher (simulated) + sign-in: demo sandbox, or Microsoft / Google work account (OpenID Connect, done by the server) + session: one kind of server-signed token, whichever way the person signed in + limits: rate limits, size limits, sandbox caps +``` + +There are two ways to run the demo: + +| | Static (Vercel) | Full stack (Docker, for example Render) | +|---|---|---| +| What runs | The Flutter web app on built-in sample data | The API and the web app together | +| Where data lives | In the visitor's browser tab | In the server's memory, one private sandbox per visitor | +| Resets when | The page is reloaded | The server restarts, or 2 hours without use | +| Needs a server | No | Yes | +| Shows the real API and its rules | No | Yes | + +## Who decides what + +The app only shows things. **The server decides** who may do what, so a changed or hand-made request cannot get around the rules. + +| Rule | Where it is enforced | +|---|---| +| You need a valid, unexpired, correctly signed token | `Program.cs` (JWT bearer authentication) | +| Admin routes need the Admin role | `AdminController`, `JobsController.All` (policy `Admin`) | +| You only ever see and print your own waiting documents | `PrintStore.HeldJobs`, `PrintStore.Release` | +| Printing never takes you over your page quota | `PrintStore.Release` (all or nothing) | +| An administrator only reaches people in their own group | `PrintStore.AllJobs`, `Users`, `SetQuota` | +| Quota changes are between 0 and 10000 pages | `AdminController` (`set-quota`, `default-quota`, `set-quota-all`) | +| Only people from your organisation sign in | `WorkspaceIdentity.Map` (tenant, domain, verified email) | +| Administrators are decided by the server | `Workspace__Admins`, or the Microsoft app role; never by the app | +| Pages start again each month | `PrintStore` (period = UTC year and month) | +| Printing only goes to a printer in your own group that is on | `PrintStore.Release` | +| At most 50 documents per print, 12 waiting per person | `JobsController.Release`, `PrintStore.AddSample` | + +## Data + +- **PrintJob**: `id`, `userId`, `userName`, `fileName`, `pages`, `submittedAt`, `status` (`Held`, `Printed` or `Failed`), `failureReason`, `printerName` (once printed). +- **User**: id (`g-…` for Google, `m-…` for Microsoft), display name, email, whether an administrator, page quota, pages used and the month they belong to, last seen, and a **sandbox id**. +- **Printer**: `id`, `name`, `location`, `enabled`. Kept per sandbox, so a work organisation has one list and each demo visitor has their own three. +- **Sandbox**: who can see and manage whom. Everyone who signs in for real shares the `default` group. Each demo visitor, and each demo administrator, gets a private one. A demo administrator's sandbox holds a private copy of four sample people. + +## Signing in + +**Demo.** `POST /api/auth/demo-login` creates a sandbox and returns a token signed by the server. It exists only when `Demo__Enabled` is true, and its tokens stop working the moment that is switched off. + +**Work account (Microsoft 365 or Google Workspace).** When the `Workspace__*` settings are complete the server does the whole sign-in, so the app holds no secrets: + +1. The app sends the browser to `GET /api/auth/login?returnTo=/…`. The server redirects to Microsoft or Google (authorization code flow with PKCE, `prompt=select_account`). +2. The provider sends the browser back to `/api/auth/callback`. The server exchanges the code, then checks who it is (`WorkspaceIdentity.Map`): the right organisation, a verified email for Google, the right domain. +3. `GET /api/auth/complete` adds the person if new (default pages a month), decides if they are an administrator, issues the server's own token and redirects to `returnTo#token=…`. A refused account goes to `returnTo#error=` with `wrong_account`, `unverified_email`, `no_identity` or `sign_in_failed`. +4. The page keeps the fragment for the app and removes it from the address bar before the app starts. `returnTo` must be a path on this site, so sign-in cannot be used to send people elsewhere. + +Whatever way someone signed in, the token carries the same claims (`uid`, `name`, `role`, `kind`) and nothing else in the server cares which it was. Turning work sign-in or demo sign-in off makes that kind of token stop working at once. Setup steps: [09](09-connecting-your-workspace.md). + +## Errors + +Errors are JSON: `{ "error": "", "message": "", "pagesOver": }`. + +| Status | `error` | When | +|---|---|---| +| 400 | `no_jobs`, `too_many`, `bad_request` | Nothing chosen, more than 50 documents, an invalid quota | +| 401 | | No token, or one that is wrong or expired. The app signs the person out with a message | +| 403 | | Signed in but not allowed, for example a normal user on an admin route | +| 404 | `not_found` | Documents that are not yours or not waiting, an unknown person, or demo sign-in switched off | +| 409 | `quota_exceeded` | The documents need more pages than the person has left. Nothing prints | +| 409 | `no_printer`, `printer_unavailable` | No printer is set up, or the chosen one is off or unknown. Nothing prints | +| 409 | `too_many` | At most 50 printers | +| 409 | `no_more_samples` | Demo only: twelve documents are already waiting, or all sample documents are in use | +| 429 | | Too many requests from one address in a minute | +| 500 | `server_error` | Something unexpected. The details stay in the server log | + +## Routes + +All routes except sign-in and `/healthz` need `Authorization: Bearer `. + +### `GET /api/auth/config` +No token. What the sign-in screen offers. +```json +{ "provider": "google", "providerName": "Google", "domain": "example.com", "demo": false } +``` +`provider` is `microsoft`, `google` or `none`. + +### `POST /api/auth/demo-login` +```json +// request +{ "admin": false } +// 200 +{ "token": "eyJ…", "userId": "demo-3f9a1c2b", "name": "Alice Tan", "isAdmin": false } +``` + +### `GET /api/auth/me` +```json +{ "userId": "demo-3f9a1c2b", "name": "Alice Tan", "isAdmin": false, "email": null } +``` + +### `GET /api/printers` +```json +[ { "id": "a190fbb8", "name": "Level 3 East", "location": "Third floor, east wing", "enabled": true } ] +``` +Switched-off printers are listed only for administrators. + +### `GET /api/jobs/held` +Your waiting documents, newest first. +```json +[ { "id": "a1b2c3d4", "userId": "demo-3f9a1c2b", "userName": "Alice Tan", + "fileName": "Q3 budget review.pdf", "pages": 12, + "submittedAt": "2026-10-22T09:00:00+00:00", "status": "Held", "failureReason": null } ] +``` + +### `GET /api/jobs/quota` +```json +{ "used": 12, "total": 50, "left": 38 } +``` + +### `POST /api/jobs/release` +```json +// request: send jobIds (a single jobId is also accepted). printerId is optional; +// without it the first printer that is on is used +{ "jobIds": ["a1b2c3d4", "e5f6a7b8"], "printerId": "a190fbb8" } +// 200: only the documents that really printed are listed +{ "printed": ["a1b2c3d4", "e5f6a7b8"], "pages": 15, "quota": { "used": 27, "total": 50, "left": 23 }, "printerName": "Level 3 East" } +// 409: nothing printed, nothing charged +{ "error": "quota_exceeded", "message": "Over your limit by 6 pages.", "pagesOver": 6 } +``` + +### `POST /api/jobs/sample` (demo only) +Adds one sample document to your list and returns it. 409 `no_more_samples` when there are no more to add. + +### `GET /api/jobs` (administrators) +Every job in the administrator's own group, newest first. + +### `GET /api/admin/setup` (administrators) +What the **Setup** card shows. +```json +{ "provider": "Google", "providerName": "Google", "domain": "example.com", "demoEnabled": false, + "defaultQuota": 50, "people": 12, "printers": 0, + "redirectUri": "https://print.example.com/api/auth/callback", + "warnings": ["No printers yet. Add one so people can print."] } +``` +`redirectUri` is the address to register with Microsoft or Google. `warnings` is empty when nothing is left to do. + +### `GET /api/admin/users` (administrators) +```json +[ { "userId": "…", "name": "Priya Nair", "email": null, "quota": { "used": 8, "total": 200, "left": 192 } } ] +``` + +### `POST /api/admin/set-quota` (administrators) +```json +{ "userId": "…", "quota": 80 } +``` +200 on success, 404 if that person is not in the administrator's group, 400 if the number is outside 0 to 10000. + +### `POST /api/admin/default-quota`, `POST /api/admin/set-quota-all` (administrators) +```json +{ "quota": 80 } +``` +`default-quota` sets the pages a month for people who sign in from now on. `set-quota-all` gives everyone in the group the same pages and replies `{ "changed": 12 }`. Both are 400 outside 0 to 10000. + +### `POST /api/admin/printers`, `PUT /api/admin/printers/{id}`, `DELETE /api/admin/printers/{id}` (administrators) +```json +{ "name": "Level 3 East", "location": "Third floor", "enabled": true } +``` +`name` is required (up to 60 characters). `enabled` applies to `PUT`. Up to 50 printers. 404 for an unknown printer. + +### `GET /healthz` +`{ "status": "ok" }`, no token needed. Used by hosts to check the server is up. + +## Settings + +Environment variables, with double underscores for the colon in a setting name. + +| Variable | Default | What it does | +|---|---|---| +| `Demo__Enabled` | `false` (`true` in the Docker image) | Allows demo sign-in and sample documents | +| `Auth__SigningKey` | random at start | 32 or more characters. Set it so tokens survive a restart | +| `Workspace__Provider` | empty | `Microsoft` or `Google`. Turns on work-account sign-in | +| `Workspace__ClientId`, `__ClientSecret` | empty | From the app registration or OAuth client | +| `Workspace__TenantId` | empty | Microsoft only: the directory id | +| `Workspace__Domain` | empty | Required for Google. Optional for Microsoft: limits sign-in to one email domain | +| `Workspace__Admins` | empty | Administrator email addresses, separated by commas or spaces | +| `Workspace__AdminRole` | `PullPrint.Admin` | Microsoft app role that also makes an administrator | +| `Workspace__DefaultQuota` | `50` | Pages a month for a first sign-in. Changeable on the administrator screen | +| `RateLimit__LoginPerMinute` | `20` | Demo sign-ins a minute from one address | +| `RateLimit__PerMinute` | `300` | All requests a minute from one address | +| `Cors__AllowAnyOrigin` | `false` | Only for running the web app from a different address | + +Other limits are fixed in code: 300 sandboxes at once, sandboxes deleted after 2 hours idle, 16 KB request bodies. + +## Replacing the in-memory parts + +- **A database:** implement `IPrintStore` (`backend/services/PrintStore.cs`) and register it in `Program.cs`. The tests in `backend.Tests` describe the behaviour to keep. +- **A real printer:** implement `IPrintDispatcher` (`backend/services/PrintDispatcher.cs`). Throw from `Print` to mark a job as failed; the message becomes the reason shown to administrators. +- **Groups and directory:** quotas are per person. Per-group limits would read the Microsoft Graph or Google Admin SDK and are not built. +- **Sending files:** nothing creates a waiting job except the demo sample route. Real submission is an open decision in [05](05-open-decisions.md). diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..3da33d6 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,29 @@ +# Documentation + +Guides for using and setting up Pull Print, and the design documents behind it. Start with **Getting started** if you are new. + +| Document | What it covers | +|---|---| +| [Getting started](Getting%20started.md) | Every screen with pictures: printing, the printer's own screen, administrators, work-account sign-in | +| [09 Connecting your workspace](09-connecting-your-workspace.md) | Sign in with Microsoft 365 or Google Workspace, add printers, set page limits: the ten-minute setup | +| [Fixing problems](Fixing%20problems.md) | Quick answers and what to do when something does not work | +| [Questions and answers](FAQ.md) | Short answers: is anything printed, who sees my documents, what happens on restart | +| [01 Product brief](01-product-brief.md) | Who uses it, the one job it must do fast, speed targets, scope | +| [02 User flows](02-user-flows.md) | Step-by-step flows for printing, releasing and administering | +| [03 Screen specs](03-screen-specs.md) | Each mockup with its purpose, contents, states and exact wording | +| [04 Design guidelines](04-design-guidelines.md) | Colours, type, sizes, accessibility, and what we will not use | +| [05 Open decisions](05-open-decisions.md) | Questions that change the design and need an answer | +| [06 Hosting the demo](06-demo-hosting.md) | Putting the demo online for free, settings, what to expect | +| [How it works](How%20it%20works.md) | How the pieces fit, who decides what, every route with an example | +| [08 Review and fixes](08-review-and-fixes.md) | What went wrong from each user's point of view, how it was found, and the fix | + +## Pictures + +The screenshots and diagrams in `images/` are taken from the running app. [`tools/screenshots`](../tools/screenshots/README.md) explains how to make them again. + +## Mockups + +- Images used in the documents: [`design/screens/`](design/screens/) (PNG, 2x). +- Editable source for each screen: [`design/source/`](design/source/) (`.dc.html`, one per screen). These come from the Claude Design canvas and open in it. Opened directly in a browser they render as a flat screen. + +The screens are mockups, not Flutter code. Sample names and numbers are made up. diff --git a/docs/design/screens/01-phone-sign-in.png b/docs/design/screens/01-phone-sign-in.png new file mode 100644 index 0000000..d179936 Binary files /dev/null and b/docs/design/screens/01-phone-sign-in.png differ diff --git a/docs/design/screens/02-phone-my-jobs.png b/docs/design/screens/02-phone-my-jobs.png new file mode 100644 index 0000000..cace01c Binary files /dev/null and b/docs/design/screens/02-phone-my-jobs.png differ diff --git a/docs/design/screens/03-phone-sent.png b/docs/design/screens/03-phone-sent.png new file mode 100644 index 0000000..17fbe4f Binary files /dev/null and b/docs/design/screens/03-phone-sent.png differ diff --git a/docs/design/screens/04-panel-sign-in.png b/docs/design/screens/04-panel-sign-in.png new file mode 100644 index 0000000..737e8f2 Binary files /dev/null and b/docs/design/screens/04-panel-sign-in.png differ diff --git a/docs/design/screens/05-panel-release.png b/docs/design/screens/05-panel-release.png new file mode 100644 index 0000000..0cd4aa9 Binary files /dev/null and b/docs/design/screens/05-panel-release.png differ diff --git a/docs/design/screens/06-panel-printing.png b/docs/design/screens/06-panel-printing.png new file mode 100644 index 0000000..45e34da Binary files /dev/null and b/docs/design/screens/06-panel-printing.png differ diff --git a/docs/design/screens/07-admin.png b/docs/design/screens/07-admin.png new file mode 100644 index 0000000..e660be7 Binary files /dev/null and b/docs/design/screens/07-admin.png differ diff --git a/docs/design/source/Admin.dc.html b/docs/design/source/Admin.dc.html new file mode 100644 index 0000000..6e6d76e --- /dev/null +++ b/docs/design/source/Admin.dc.html @@ -0,0 +1,117 @@ + + + + +Admin jobs and quotas + + + + + + + +
+ +
+
+
+ + + Pull Print Admin + + +
+ YHAdministrator +
+
+ +
+ +
+
+ +
Waiting to print
14
+
+
+ +
Printed today
96
+
+
+ +
Failed today
2
+
+
+ +
Users out of quota
3
+
+
+ +
+
+

All jobs

+
+ + +
+
+
+ + + + + + + + +
UserDocumentPagesSentStatus
ATAlice TanPDFQ3 budget review.pdf12Today 9:02Waiting
BRBob ReyesDOCXreport.docx3Today 8:55Printed
PNPriya NairPDFSafety audit.pdf41Today 8:31Waiting
MLMarcus LeePDFInvoice 2291.pdf2YesterdayFailed: printer offline
+
+
+ +
+

Users and quotas

+
+ + + + + + + +
UserUsed this monthMonthly quota (pages)
ATAlice Tan
12 of 50
Save
BRBob Reyes
50 of 50 · none left
Save
PNPriya Nair
8 of 200
Save
+
+
+
+
+
+ + + diff --git a/docs/design/source/Kiosk-Done.dc.html b/docs/design/source/Kiosk-Done.dc.html new file mode 100644 index 0000000..1441942 --- /dev/null +++ b/docs/design/source/Kiosk-Done.dc.html @@ -0,0 +1,70 @@ + + + + +Printer panel printing + + + + + + + +
+
+
+ +
+
+ +
+

Printing 15 pages

+

Collect your documents from the tray.
You have 23 pages left this month.

+ +
+
Signing out automatically
+
+
+
+ +
+ + + + + + + + + + + + + + +
+
+
+ + + diff --git a/docs/design/source/Kiosk-Jobs.dc.html b/docs/design/source/Kiosk-Jobs.dc.html new file mode 100644 index 0000000..b3ef2b8 --- /dev/null +++ b/docs/design/source/Kiosk-Jobs.dc.html @@ -0,0 +1,126 @@ + + + + +Printer panel release jobs + + + + + + + +
+ +
+
+ + Alice Tan + {{leftNow}} pages left this month +
+ + + Sign out + +
+ +
+

Your documents

+ Tap a document to include or leave it out +
+ +
+ + + +
+ +
+
+
{{summary}}
+
{{afterText}}
+
+ + + + Print + + + + + +
+
+
+ + + diff --git a/docs/design/source/Kiosk-SignIn.dc.html b/docs/design/source/Kiosk-SignIn.dc.html new file mode 100644 index 0000000..3c59aba --- /dev/null +++ b/docs/design/source/Kiosk-SignIn.dc.html @@ -0,0 +1,83 @@ + + + + +Printer panel sign in + + + + + + + +
+ +
+
+
+ + Pull Print +
+

Sign in to collect your prints

+

You will only see your own documents.

+
+ + + + + + + + + + + + + +
+
+ +
+
+ Level 3 East + Ready +
+ +
+
+
+ + Sign in with your phone +
+
On your phone, open microsoft.com/devicelogin and enter this code
+
K7QH 4M2B
+ I have entered the code +
+
+ + Tap your staff card + Coming later +
+
+
+
+
+ + + diff --git a/docs/design/source/Main.dc.html b/docs/design/source/Main.dc.html new file mode 100644 index 0000000..da76919 --- /dev/null +++ b/docs/design/source/Main.dc.html @@ -0,0 +1,87 @@ + + + + +Phone sign in + + + + + + + +
+ +
+
+ +
+ + Pull Print +
+ +
+ + + + + + + + + + + + + + +
+ +
+

Print now.
Collect at any printer.

+

Your documents wait safely until you are at the printer and tap Print.

+ +
+
+ 1 + Send a file +
+
+ 2 + Walk up and sign in +
+
+ 3 + Tap Print +
+
+ +
+ + + + Sign in with Microsoft + +
Use your work account. No new password.
+
+
+
+ + + diff --git a/docs/design/source/Phone-Done.dc.html b/docs/design/source/Phone-Done.dc.html new file mode 100644 index 0000000..d33f1a4 --- /dev/null +++ b/docs/design/source/Phone-Done.dc.html @@ -0,0 +1,77 @@ + + + + +Phone sent to printer + + + + + + + +
+
+ +
+
+ +
+

Printing at Level 3 East

+

Collect your pages from the tray.

+
+ +
+ + + + + + + + + + + + + +
+ +
+
+
+ Q3 budget review.pdf + 12 pages +
+
+ Site visit notes.docx + 3 pages +
+
+ Pages left this month + 23 of 50 +
+
+
+ Back to my documents +
+
+
+ + + diff --git a/docs/design/source/Phone-Jobs.dc.html b/docs/design/source/Phone-Jobs.dc.html new file mode 100644 index 0000000..cea3a8e --- /dev/null +++ b/docs/design/source/Phone-Jobs.dc.html @@ -0,0 +1,146 @@ + + + + +Phone held jobs + + + + + + + +
+ +
+
+
+ + Pull Print +
+ + + +
+
+
+
Good morning
+
Alice Tan
+
{{waitingText}}
+
+
+ + + + +
+ {{leftNow}} + pages left +
+
+
+
+ +
+
+

Waiting to print

+ Tap to select +
+ +
+ + + +
+ +
+
+ + + Printer + + Level 3 East +
+ + {{buttonText}} + + + + +
+
+
+
+ + + diff --git a/docs/images/admin-1-overview.png b/docs/images/admin-1-overview.png new file mode 100644 index 0000000..7266b32 Binary files /dev/null and b/docs/images/admin-1-overview.png differ diff --git a/docs/images/admin-2-printers.png b/docs/images/admin-2-printers.png new file mode 100644 index 0000000..e48178d Binary files /dev/null and b/docs/images/admin-2-printers.png differ diff --git a/docs/images/admin-3-people.png b/docs/images/admin-3-people.png new file mode 100644 index 0000000..850518f Binary files /dev/null and b/docs/images/admin-3-people.png differ diff --git a/docs/images/admin-4-jobs.png b/docs/images/admin-4-jobs.png new file mode 100644 index 0000000..843003b Binary files /dev/null and b/docs/images/admin-4-jobs.png differ diff --git a/docs/images/admin-5-add-printer.png b/docs/images/admin-5-add-printer.png new file mode 100644 index 0000000..38f1fde Binary files /dev/null and b/docs/images/admin-5-add-printer.png differ diff --git a/docs/images/admin-6-apply-to-everyone.png b/docs/images/admin-6-apply-to-everyone.png new file mode 100644 index 0000000..687a789 Binary files /dev/null and b/docs/images/admin-6-apply-to-everyone.png differ diff --git a/docs/images/demo.gif b/docs/images/demo.gif new file mode 100644 index 0000000..306db72 Binary files /dev/null and b/docs/images/demo.gif differ diff --git a/docs/images/how-it-fits.svg b/docs/images/how-it-fits.svg new file mode 100644 index 0000000..3978037 --- /dev/null +++ b/docs/images/how-it-fits.svg @@ -0,0 +1,55 @@ + + How Pull Print fits together + A person sends a document. The Pull Print server holds it. At the printer the person signs in with their work account, sees only their own documents and presses Print. The server checks their page limit and sends the job to the printer you chose. + + + + + + + + + + + + A person + The printer's + The printer + + + sends a document + from anywhere + screen or their phone: + sign in, tick, Print + paper comes out + only now + + + Pull Print server + + holds the document (Waiting) + checks who is signed in + shows only their own files + checks their pages this month + keeps printers and page limits + + + + + + + + + + 1 send + 2 sign in + 3 Print + 4 print + + + + Microsoft 365 or Google Workspace + + + proves who the person is + diff --git a/docs/images/panel-1-sign-in.png b/docs/images/panel-1-sign-in.png new file mode 100644 index 0000000..f3febc5 Binary files /dev/null and b/docs/images/panel-1-sign-in.png differ diff --git a/docs/images/panel-2-documents.png b/docs/images/panel-2-documents.png new file mode 100644 index 0000000..4aa322b Binary files /dev/null and b/docs/images/panel-2-documents.png differ diff --git a/docs/images/panel-2b-over-limit.png b/docs/images/panel-2b-over-limit.png new file mode 100644 index 0000000..ee6bb18 Binary files /dev/null and b/docs/images/panel-2b-over-limit.png differ diff --git a/docs/images/panel-3-printing.png b/docs/images/panel-3-printing.png new file mode 100644 index 0000000..62801ec Binary files /dev/null and b/docs/images/panel-3-printing.png differ diff --git a/docs/images/phone-1-sign-in.png b/docs/images/phone-1-sign-in.png new file mode 100644 index 0000000..038a662 Binary files /dev/null and b/docs/images/phone-1-sign-in.png differ diff --git a/docs/images/phone-1b-about-demo.png b/docs/images/phone-1b-about-demo.png new file mode 100644 index 0000000..2f2bb27 Binary files /dev/null and b/docs/images/phone-1b-about-demo.png differ diff --git a/docs/images/phone-2-documents.png b/docs/images/phone-2-documents.png new file mode 100644 index 0000000..f954bd4 Binary files /dev/null and b/docs/images/phone-2-documents.png differ diff --git a/docs/images/phone-3-over-limit.png b/docs/images/phone-3-over-limit.png new file mode 100644 index 0000000..362aa1c Binary files /dev/null and b/docs/images/phone-3-over-limit.png differ diff --git a/docs/images/phone-4-pick-printer.png b/docs/images/phone-4-pick-printer.png new file mode 100644 index 0000000..8aa75d6 Binary files /dev/null and b/docs/images/phone-4-pick-printer.png differ diff --git a/docs/images/phone-5-printed.png b/docs/images/phone-5-printed.png new file mode 100644 index 0000000..c1d0b49 Binary files /dev/null and b/docs/images/phone-5-printed.png differ diff --git a/docs/images/setup-1-finish.png b/docs/images/setup-1-finish.png new file mode 100644 index 0000000..b94e42e Binary files /dev/null and b/docs/images/setup-1-finish.png differ diff --git a/docs/images/setup-2-register-address.png b/docs/images/setup-2-register-address.png new file mode 100644 index 0000000..d4642e5 Binary files /dev/null and b/docs/images/setup-2-register-address.png differ diff --git a/docs/images/sign-in-flow.svg b/docs/images/sign-in-flow.svg new file mode 100644 index 0000000..0a86578 --- /dev/null +++ b/docs/images/sign-in-flow.svg @@ -0,0 +1,57 @@ + +What happens when someone signs in with a work account +Six steps. The person presses Sign in. The server sends them to Microsoft or Google. They sign in there. The server checks they belong to your organisation. It adds them if they are new, then returns them to the app with a session. The page keeps the session and removes it from the address bar. If the account is not allowed, the person sees the reason and can try again. + + + +1 +Press Sign in +Microsoft or Google, +whichever you +set up + + +2 +Sent to provider +The server starts the +sign-in. The app +holds no secrets + + +3 +Sign in there +On their own page. +Pull Print never +sees a password + + +4 +Server checks +Right organisation? +Right domain? Email +verified? + + +5 +Added if new +Gets the default +pages a month. +Admins: your list + + +6 +Back in the app +The session is kept, +then removed from +the address bar + +Signed in +They see only their own documents, and only the printers you added. +The session lasts 8 hours. A printer screen signs out after 60 seconds idle. + +Turned away? +Wrong organisation, a personal account, or an unverified email. +The person sees the reason in a red box and can try again. + + + \ No newline at end of file diff --git a/docs/images/social-preview.png b/docs/images/social-preview.png new file mode 100644 index 0000000..9864806 Binary files /dev/null and b/docs/images/social-preview.png differ diff --git a/docs/images/workspace-google-panel.png b/docs/images/workspace-google-panel.png new file mode 100644 index 0000000..cd85dbc Binary files /dev/null and b/docs/images/workspace-google-panel.png differ diff --git a/docs/images/workspace-google-phone.png b/docs/images/workspace-google-phone.png new file mode 100644 index 0000000..04ec122 Binary files /dev/null and b/docs/images/workspace-google-phone.png differ diff --git a/docs/images/workspace-microsoft-phone.png b/docs/images/workspace-microsoft-phone.png new file mode 100644 index 0000000..17dbed0 Binary files /dev/null and b/docs/images/workspace-microsoft-phone.png differ diff --git a/docs/images/workspace-turned-away.png b/docs/images/workspace-turned-away.png new file mode 100644 index 0000000..d66c14c Binary files /dev/null and b/docs/images/workspace-turned-away.png differ diff --git a/docs/images/workspace-with-demo.png b/docs/images/workspace-with-demo.png new file mode 100644 index 0000000..9b5b6c6 Binary files /dev/null and b/docs/images/workspace-with-demo.png differ diff --git a/frontend/db.json b/frontend/db.json deleted file mode 100644 index 8cc974f..0000000 --- a/frontend/db.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "jobs": [ - { - "id": "1", - "userId": "u1", - "userName": "Alice", - "fileName": "document.pdf", - "pages": 5, - "submittedAt": "2025-08-14T07:00:00Z", - "status": "Held" - }, - { - "id": "2", - "userId": "u2", - "userName": "Bob", - "fileName": "report.docx", - "pages": 3, - "submittedAt": "2025-08-14T08:00:00Z", - "status": "Released" - } - ] -} - diff --git a/frontend/lib/main.dart b/frontend/lib/main.dart index bc23430..7bac911 100644 --- a/frontend/lib/main.dart +++ b/frontend/lib/main.dart @@ -1,19 +1,48 @@ import 'package:flutter/material.dart'; +import 'package:flutter_web_plugins/url_strategy.dart'; +import 'package:provider/provider.dart'; import 'screens/login_screen.dart'; +import 'services/http_print_repository.dart'; +import 'services/mock_print_repository.dart'; +import 'services/print_repository.dart'; +import 'utils/constants.dart'; +import 'utils/theme.dart'; void main() { - runApp(const MyApp()); + // Plain addresses, so the sign-in token in `#token=...` is not mistaken for a page. + usePathUrlStrategy(); + runApp(PullPrintingApp( + repository: + Constants.useMockData ? MockPrintRepository() : HttpPrintRepository(), + )); } -class MyApp extends StatelessWidget { - const MyApp({super.key}); +class PullPrintingApp extends StatelessWidget { + final PrintRepository repository; + + /// Only set by tests, which load a real font so text is measured realistically. + final String? fontFamily; + + const PullPrintingApp({super.key, required this.repository, this.fontFamily}); @override Widget build(BuildContext context) { - return MaterialApp( - title: 'Pull Printing', - theme: ThemeData(primarySwatch: Colors.blue), - home: const LoginScreen(), + return Provider.value( + value: repository, + child: MaterialApp( + title: Constants.appName, + debugShowCheckedModeBanner: false, + theme: fontFamily == null + ? AppTheme.light + : AppTheme.build(fontFamily: fontFamily), + // Always start at the sign-in screen, whatever the address says. The browser can + // arrive with `/?printer=...#token=...`, which is not a route. + onGenerateRoute: (_) => _signInRoute(), + onGenerateInitialRoutes: (_) => [_signInRoute()], + ), ); } -} \ No newline at end of file + + static Route _signInRoute() => + MaterialPageRoute(builder: (_) => const LoginScreen()); +} diff --git a/frontend/lib/models/print_job.dart b/frontend/lib/models/print_job.dart index 044262a..b0fd510 100644 --- a/frontend/lib/models/print_job.dart +++ b/frontend/lib/models/print_job.dart @@ -1,11 +1,12 @@ class PrintJob { final String id; final String userId; - final String userName; // who sent it - final String fileName; // which file + final String userName; // who sent it + final String fileName; // which file final int pages; final DateTime submittedAt; - final String status; // Held | Released | Printed | Failed + final String status; // Held | Released | Printed | Failed + final String? failureReason; const PrintJob({ required this.id, @@ -15,8 +16,30 @@ class PrintJob { required this.pages, required this.submittedAt, required this.status, + this.failureReason, }); + bool get isHeld => status == 'Held'; + bool get isFailed => status == 'Failed'; + bool get isPrinted => status == 'Printed' || status == 'Released'; + + /// Lower-case file extension without the dot, or '' when there is none. + String get extension { + final dot = fileName.lastIndexOf('.'); + return dot < 0 ? '' : fileName.substring(dot + 1).toLowerCase(); + } + + PrintJob copyWith({String? status, String? failureReason}) => PrintJob( + id: id, + userId: userId, + userName: userName, + fileName: fileName, + pages: pages, + submittedAt: submittedAt, + status: status ?? this.status, + failureReason: failureReason ?? this.failureReason, + ); + factory PrintJob.fromJson(Map j) { return PrintJob( id: j['id'] as String, @@ -26,16 +49,18 @@ class PrintJob { pages: (j['pages'] as num).toInt(), submittedAt: DateTime.parse(j['submittedAt'] as String), status: j['status'] as String, + failureReason: j['failureReason'] as String?, ); } Map toJson() => { - 'id': id, - 'userId': userId, - 'userName': userName, - 'fileName': fileName, - 'pages': pages, - 'submittedAt': submittedAt.toIso8601String(), - 'status': status, - }; + 'id': id, + 'userId': userId, + 'userName': userName, + 'fileName': fileName, + 'pages': pages, + 'submittedAt': submittedAt.toIso8601String(), + 'status': status, + if (failureReason != null) 'failureReason': failureReason, + }; } diff --git a/frontend/lib/models/printer.dart b/frontend/lib/models/printer.dart index ef1db7b..0820e3d 100644 --- a/frontend/lib/models/printer.dart +++ b/frontend/lib/models/printer.dart @@ -1,11 +1,21 @@ +/// A printer people can collect their documents from. class Printer { final String id; final String name; final String location; + final bool enabled; - Printer({ + const Printer({ required this.id, required this.name, - required this.location, + this.location = '', + this.enabled = true, }); + + factory Printer.fromJson(Map j) => Printer( + id: j['id'] as String, + name: j['name'] as String, + location: j['location'] as String? ?? '', + enabled: j['enabled'] as bool? ?? true, + ); } diff --git a/frontend/lib/models/session.dart b/frontend/lib/models/session.dart new file mode 100644 index 0000000..d67bedf --- /dev/null +++ b/frontend/lib/models/session.dart @@ -0,0 +1,97 @@ +/// Who is signed in and the token to call the API with. +class Session { + final String token; + final String userId; + final String name; + final bool isAdmin; + + /// True for the private sample sandbox, false for a real work account. + final bool demo; + + const Session({ + required this.token, + required this.userId, + required this.name, + this.isAdmin = false, + this.demo = true, + }); +} + +/// Pages used and allowed this month. A total of 0 means "not known". +class QuotaInfo { + final int used; + final int total; + + const QuotaInfo({required this.used, required this.total}); + + static const unknown = QuotaInfo(used: 0, total: 0); + + bool get known => total > 0; + int get left => total > used ? total - used : 0; +} + +/// One row of the admin "People and quotas" table. +class UserQuota { + final String userId; + final String name; + final String? email; + final QuotaInfo quota; + + const UserQuota({ + required this.userId, + required this.name, + required this.quota, + this.email, + }); +} + +/// How people sign in on this server, known before anyone is signed in. +class AuthConfig { + /// `microsoft`, `google` or `none`. + final String provider; + + /// Domain people must belong to, such as `contoso.com`. Empty when any is allowed. + final String? domain; + + /// True when anyone can open a private sample sandbox. + final bool demo; + + const AuthConfig({this.provider = 'none', this.domain, this.demo = true}); + + /// Sample data only, no work accounts. + static const demoOnly = AuthConfig(); + + bool get hasWorkspace => provider == 'microsoft' || provider == 'google'; + + /// `Microsoft` or `Google`, as shown on the button. + String get providerName => provider == 'google' ? 'Google' : 'Microsoft'; +} + +/// What the administrator's setup check shows. +class SetupInfo { + final String provider; + final String? domain; + final bool demoEnabled; + final int defaultQuota; + final int people; + final int printers; + + /// The address to register with Microsoft or Google as the sign-in redirect. + final String redirectUri; + + /// Things still to do, in plain words. Empty when the setup is complete. + final List warnings; + + const SetupInfo({ + required this.provider, + required this.demoEnabled, + required this.defaultQuota, + required this.people, + required this.printers, + required this.redirectUri, + required this.warnings, + this.domain, + }); + + bool get hasWorkspace => provider == 'Microsoft' || provider == 'Google'; +} diff --git a/frontend/lib/models/user.dart b/frontend/lib/models/user.dart deleted file mode 100644 index c7ed549..0000000 --- a/frontend/lib/models/user.dart +++ /dev/null @@ -1,13 +0,0 @@ -class User { - final String id; - final String name; - final int quota; - final int used; - - User({ - required this.id, - required this.name, - required this.quota, - required this.used, - }); -} diff --git a/frontend/lib/screens/admin_dashboard_screen.dart b/frontend/lib/screens/admin_dashboard_screen.dart index 0b61d8d..3ec9a9f 100644 --- a/frontend/lib/screens/admin_dashboard_screen.dart +++ b/frontend/lib/screens/admin_dashboard_screen.dart @@ -1,49 +1,1038 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; import '../models/print_job.dart'; -import '../services/api_service.dart'; -import '../widgets/job_card.dart'; +import '../models/printer.dart'; +import '../models/session.dart'; +import '../services/print_repository.dart'; +import '../utils/constants.dart'; +import '../utils/format.dart'; +import '../utils/theme.dart'; +import '../widgets/app_button.dart'; +import '../widgets/brand_mark.dart'; +import '../widgets/demo_banner.dart'; +import '../widgets/doc_thumbnail.dart'; +import 'login_screen.dart'; +/// All jobs and per-user quotas, for administrators. class AdminDashboardScreen extends StatefulWidget { - const AdminDashboardScreen({super.key}); + final Session session; + const AdminDashboardScreen({required this.session, super.key}); @override State createState() => _AdminDashboardScreenState(); } class _AdminDashboardScreenState extends State { - final _api = ApiService(); - late Future> _jobs; - final String token = 'your_token_here'; // get from login/auth + bool _loading = true; + Object? _error; + List _jobs = const []; + List _users = const []; + List _printers = const []; + SetupInfo? _setup; + final _defaultQuotaField = TextEditingController(); + final _everyoneQuotaField = TextEditingController(); + String _search = ''; + String _status = 'All'; + final Map _quotaFields = {}; + + static const _statuses = ['All', 'Waiting', 'Printed', 'Failed']; + static const _avatarColors = [ + Color(0xFF0B5CAD), + Color(0xFF7A4FA3), + Color(0xFF0F6B63), + Color(0xFF9A5B13), + ]; @override void initState() { super.initState(); - _jobs = _api.fetchAllJobs(token: token); + _load(); } + @override + void dispose() { + _defaultQuotaField.dispose(); + _everyoneQuotaField.dispose(); + for (final c in _quotaFields.values) { + c.dispose(); + } + super.dispose(); + } + + Future _load() async { + final repo = context.read(); + setState(() { + _loading = true; + _error = null; + }); + try { + final results = await Future.wait([ + repo.allJobs(widget.session), + repo.users(widget.session), + repo.printers(widget.session), + repo.setup(widget.session), + ]); + if (!mounted) return; + final users = results[1] as List; + final setup = results[3] as SetupInfo; + _defaultQuotaField.text = '${setup.defaultQuota}'; + for (final u in users) { + final text = '${u.quota.total}'; + final existing = _quotaFields[u.userId]; + if (existing == null) { + _quotaFields[u.userId] = TextEditingController(text: text); + } else { + existing.text = text; + } + } + setState(() { + _jobs = results[0] as List; + _users = users; + _printers = results[2] as List; + _setup = setup; + _loading = false; + }); + } on SessionExpiredException catch (e) { + _signOut(message: e.message); + } catch (e) { + if (!mounted) return; + setState(() { + _error = e; + _loading = false; + }); + } + } + + Future _saveQuota(UserQuota user) async { + final repo = context.read(); + final messenger = ScaffoldMessenger.of(context); + final value = int.tryParse(_quotaFields[user.userId]!.text.trim()); + if (value == null || value < 0) { + messenger.showSnackBar( + const SnackBar(content: Text('Enter a whole number of pages.'))); + return; + } + try { + await repo.setQuota(widget.session, user.userId, value); + if (!mounted) return; + messenger.showSnackBar(SnackBar( + content: Text('Quota for ${user.name} set to $value pages.'))); + _load(); + } on SessionExpiredException catch (e) { + _signOut(message: e.message); + } catch (e) { + if (!mounted) return; + messenger.showSnackBar(SnackBar(content: Text('Could not save: $e'))); + } + } + + // ---- setup, printers, quotas -------------------------------------------- + + void _say(String text) { + if (!mounted) return; + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(text))); + } + + /// Runs a change on the server, then reloads. Says why when it did not work. + Future _change(Future Function() action) async { + try { + final done = await action(); + if (done != null) _say(done); + if (mounted) _load(); + } on SessionExpiredException catch (e) { + _signOut(message: e.message); + } catch (e) { + _say('Could not save: $e'); + } + } + + Future _copy(String text, String what) async { + await Clipboard.setData(ClipboardData(text: text)); + _say('$what copied.'); + } + + int? _pages(String text) { + final value = int.tryParse(text.trim()); + if (value == null || value < 0 || value > 100000) { + _say('Enter a whole number of pages, from 0 to 100000.'); + return null; + } + return value; + } + + Future _saveDefaultQuota() async { + final value = _pages(_defaultQuotaField.text); + if (value == null) return; + final repo = context.read(); + await _change(() async { + await repo.setDefaultQuota(widget.session, value); + return 'New people will start with $value pages a month.'; + }); + } + + Future _applyToEveryone() async { + final value = _pages(_everyoneQuotaField.text); + if (value == null) return; + final repo = context.read(); + final ok = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Give everyone $value pages a month?'), + content: const Text( + 'This replaces the limit of every person, including anyone you set by hand.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel')), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Apply to everyone')), + ], + ), + ); + if (ok != true) return; + await _change(() async { + final n = await repo.setQuotaForAll(widget.session, value); + _everyoneQuotaField.clear(); + return n == 1 + ? '1 person now has $value pages.' + : '$n people now have $value pages.'; + }); + } + + /// Asks for a printer's name and place. Returns null when cancelled. + Future<(String, String)?> _askPrinter({Printer? existing}) { + final name = TextEditingController(text: existing?.name ?? ''); + final place = TextEditingController(text: existing?.location ?? ''); + return showDialog<(String, String)>( + context: context, + builder: (context) => AlertDialog( + title: Text(existing == null ? 'Add a printer' : 'Edit printer'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: name, + autofocus: true, + maxLength: 60, + decoration: const InputDecoration( + labelText: 'Name', hintText: 'Level 3 East'), + ), + TextField( + controller: place, + maxLength: 80, + decoration: const InputDecoration( + labelText: 'Where is it? (optional)', + hintText: 'Level 3, by the lifts'), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel')), + FilledButton( + onPressed: () { + if (name.text.trim().isEmpty) return; + Navigator.pop(context, (name.text.trim(), place.text.trim())); + }, + child: Text(existing == null ? 'Add printer' : 'Save'), + ), + ], + ), + ); + } + + Future _addPrinter() async { + final repo = context.read(); + final answer = await _askPrinter(); + if (answer == null) return; + await _change(() async { + await repo.addPrinter(widget.session, answer.$1, answer.$2); + return '${answer.$1} added.'; + }); + } + + Future _editPrinter(Printer p) async { + final repo = context.read(); + final answer = await _askPrinter(existing: p); + if (answer == null) return; + await _change(() async { + await repo.updatePrinter( + widget.session, + Printer( + id: p.id, + name: answer.$1, + location: answer.$2, + enabled: p.enabled)); + return 'Saved.'; + }); + } + + Future _togglePrinter(Printer p, bool on) { + final repo = context.read(); + return _change(() async { + await repo.updatePrinter(widget.session, + Printer(id: p.id, name: p.name, location: p.location, enabled: on)); + return on + ? '${p.name} is on.' + : '${p.name} is off. Nobody can print there.'; + }); + } + + Future _deletePrinter(Printer p) async { + final repo = context.read(); + final ok = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Remove ${p.name}?'), + content: const Text( + 'Nobody will be able to print there. Waiting documents are kept.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Cancel')), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Remove')), + ], + ), + ); + if (ok != true) return; + await _change(() async { + await repo.deletePrinter(widget.session, p.id); + return '${p.name} removed.'; + }); + } + + String _origin(SetupInfo setup) => + setup.redirectUri.replaceFirst('/api/auth/callback', ''); + + Widget _setupSection(SetupInfo setup) { + final ready = setup.warnings.isEmpty; + final signIn = setup.hasWorkspace + ? '${setup.provider} work accounts' + '${setup.domain == null || setup.domain!.isEmpty ? '' : ' (@${setup.domain})'}' + : 'Sample accounts only (demo)'; + return _card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + ready ? Icons.check_circle_outline : Icons.info_outline, + color: ready ? AppColors.printedText : AppColors.waitingText, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + ready ? 'Setup is complete' : 'Finish setting up', + style: const TextStyle( + fontSize: 18, fontWeight: FontWeight.w700), + ), + ), + ], + ), + const SizedBox(height: 8), + Text('People sign in with: $signIn.', + style: const TextStyle(color: AppColors.muted)), + for (final w in setup.warnings) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.only(top: 2, right: 8), + child: Icon(Icons.arrow_right, + size: 18, color: AppColors.waitingText), + ), + Expanded(child: Text(w)), + ], + ), + ), + if (setup.hasWorkspace) ...[ + const SizedBox(height: 12), + Wrap( + spacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + const Text('Sign-in address to register:', + style: TextStyle(color: AppColors.muted)), + SelectableText(setup.redirectUri, + style: const TextStyle(fontWeight: FontWeight.w600)), + TextButton.icon( + onPressed: () => _copy(setup.redirectUri, 'Address'), + icon: const Icon(Icons.copy, size: 16), + label: const Text('Copy'), + ), + ], + ), + ], + ], + ), + ), + ); + } + + Widget _printersSection() { + final setup = _setup; + return _card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Wrap( + spacing: 12, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + alignment: WrapAlignment.spaceBetween, + children: [ + const Text('Printers', + style: + TextStyle(fontSize: 18, fontWeight: FontWeight.w700)), + AppButton( + label: 'Add a printer', + icon: Icons.add, + height: 44, + fontSize: 15, + radius: 10, + expand: false, + onPressed: _addPrinter, + ), + ], + ), + ), + if (_printers.isEmpty) + const Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 24), + child: Text( + 'No printers yet. Add the printers people collect their documents from.', + style: TextStyle(color: AppColors.muted)), + ), + for (final p in _printers) + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + decoration: const BoxDecoration( + border: Border(top: BorderSide(color: AppColors.lineSoft)), + ), + child: Wrap( + spacing: 16, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + SizedBox( + width: 240, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(p.name, + style: + const TextStyle(fontWeight: FontWeight.w600)), + if (p.location.isNotEmpty) + Text(p.location, + style: const TextStyle( + fontSize: 13, color: AppColors.muted)), + ], + ), + ), + Row(mainAxisSize: MainAxisSize.min, children: [ + Switch( + value: p.enabled, + onChanged: (on) => _togglePrinter(p, on), + ), + Text(p.enabled ? 'On' : 'Off'), + ]), + if (setup != null) + TextButton.icon( + onPressed: () => _copy( + '${_origin(setup)}/?printer=${Uri.encodeQueryComponent(p.id)}', + 'Panel link'), + icon: const Icon(Icons.link, size: 18), + label: const Text('Copy panel link'), + ), + IconButton( + tooltip: 'Edit ${p.name}', + onPressed: () => _editPrinter(p), + icon: const Icon(Icons.edit_outlined), + ), + IconButton( + tooltip: 'Remove ${p.name}', + onPressed: () => _deletePrinter(p), + icon: const Icon(Icons.delete_outline), + ), + ], + ), + ), + if (_printers.isNotEmpty) + const Padding( + padding: EdgeInsets.fromLTRB(16, 4, 16, 16), + child: Text( + 'Open a panel link on the printer\'s screen so it prints there without asking which printer.', + style: TextStyle(fontSize: 13, color: AppColors.muted)), + ), + ], + ), + ); + } + + Widget _quotaRule( + {required String title, + required String hint, + required TextEditingController controller, + required String button, + required VoidCallback onPressed}) { + return Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: const BoxDecoration( + border: Border(top: BorderSide(color: AppColors.lineSoft)), + ), + child: Wrap( + spacing: 16, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + SizedBox( + width: 240, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, + style: const TextStyle(fontWeight: FontWeight.w600)), + Text(hint, + style: + const TextStyle(fontSize: 13, color: AppColors.muted)), + ], + ), + ), + SizedBox( + width: 190, + child: TextField( + controller: controller, + keyboardType: TextInputType.number, + decoration: InputDecoration( + labelText: 'Pages per month', semanticCounterText: title), + ), + ), + AppButton( + label: button, + height: 44, + fontSize: 15, + radius: 10, + expand: false, + onPressed: onPressed, + ), + ], + ), + ); + } + + void _signOut({String? message}) { + if (!mounted) return; + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => LoginScreen(message: message)), + (_) => false, + ); + } + + String _label(PrintJob j) => + j.isHeld ? 'Waiting' : (j.isFailed ? 'Failed' : 'Printed'); + + List get _visibleJobs { + final q = _search.trim().toLowerCase(); + return _jobs.where((j) { + if (_status != 'All' && _label(j) != _status) return false; + if (q.isEmpty) return true; + return j.userName.toLowerCase().contains(q) || + j.fileName.toLowerCase().contains(q); + }).toList(); + } + + bool _isToday(DateTime d) { + final n = DateTime.now(); + final l = d.toLocal(); + return l.year == n.year && l.month == n.month && l.day == n.day; + } + + Color _avatarColor(String name) => _avatarColors[ + name.codeUnits.fold(0, (a, b) => a + b) % _avatarColors.length]; + @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: const Text('Admin Dashboard')), - body: FutureBuilder>( - future: _jobs, - builder: (context, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Center(child: CircularProgressIndicator()); - } - if (snap.hasError) { - return Center(child: Text('Error: ${snap.error}')); - } - final jobs = snap.data!; - if (jobs.isEmpty) { - return const Center(child: Text('No jobs found.')); - } - return ListView.builder( - itemCount: jobs.length, - itemBuilder: (context, i) => JobCard(job: jobs[i]), - ); - }, + backgroundColor: AppColors.background, + body: DemoShell( + child: Column( + children: [ + _topBar(), + Expanded( + child: _loading + ? const Center(child: CircularProgressIndicator()) + : _error != null + ? _errorView() + : RefreshIndicator( + onRefresh: _load, + child: SingleChildScrollView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.all(24), + child: Center( + child: ConstrainedBox( + constraints: + const BoxConstraints(maxWidth: 1200), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.stretch, + children: [ + if (_setup != null) ...[ + _setupSection(_setup!), + const SizedBox(height: 24), + ], + _stats(), + const SizedBox(height: 24), + _printersSection(), + const SizedBox(height: 24), + _quotaSection(), + const SizedBox(height: 24), + _jobsSection(), + ], + ), + ), + ), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _errorView() => Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Cannot load the dashboard.', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.w800)), + const SizedBox(height: 8), + Text('$_error', style: const TextStyle(color: AppColors.muted)), + const SizedBox(height: 16), + AppButton(label: 'Try again', expand: false, onPressed: _load), + ], + ), + ); + + Widget _topBar() { + return Container( + color: AppColors.navy, + child: SafeArea( + bottom: false, + child: Container( + constraints: const BoxConstraints(minHeight: 68), + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8), + child: Row( + children: [ + const BrandMark(size: 32), + const SizedBox(width: 10), + const Expanded( + child: Text( + '${Constants.appName} Admin', + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.w700), + ), + ), + AppButton( + label: 'Sign out', + icon: Icons.logout, + style: AppButtonStyle.onNavy, + height: 44, + fontSize: 15, + radius: 10, + expand: false, + onPressed: () => _signOut(), + ), + ], + ), + ), + ), + ); + } + + Widget _card({required Widget child}) => Container( + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: AppColors.line), + ), + clipBehavior: Clip.antiAlias, + child: child, + ); + + Widget _stats() { + final waiting = _jobs.where((j) => j.isHeld).length; + final printed = + _jobs.where((j) => j.isPrinted && _isToday(j.submittedAt)).length; + final failed = _jobs.where((j) => j.isFailed).length; + final out = _users.where((u) => u.quota.known && u.quota.left == 0).length; + + Widget stat(String label, int value, IconData icon, Color bg, Color fg) => + _card( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18), + child: Row( + children: [ + Container( + width: 48, + height: 48, + decoration: BoxDecoration( + color: bg, borderRadius: BorderRadius.circular(12)), + child: Icon(icon, color: fg), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, + style: const TextStyle( + fontSize: 14, color: AppColors.muted)), + Text('$value', + style: const TextStyle( + fontSize: 30, + fontWeight: FontWeight.w800, + height: 1.1)), + ], + ), + ), + ], + ), + ), + ); + + return LayoutBuilder(builder: (context, c) { + final cols = c.maxWidth >= 900 ? 4 : (c.maxWidth >= 520 ? 2 : 1); + final w = (c.maxWidth - 16 * (cols - 1)) / cols; + final cards = [ + stat('Waiting to print', waiting, Icons.schedule, + AppColors.waitingBackground, AppColors.waitingText), + stat('Printed today', printed, Icons.print_outlined, + AppColors.printedBackground, AppColors.printedText), + stat('Failed', failed, Icons.warning_amber_rounded, + AppColors.failedBackground, AppColors.failedText), + stat('People out of quota', out, Icons.person_outline, + const Color(0xFFE6EEF7), const Color(0xFF0B4A8A)), + ]; + return Wrap( + spacing: 16, + runSpacing: 16, + children: [for (final s in cards) SizedBox(width: w, child: s)], + ); + }); + } + + Widget _pill(PrintJob j) { + final label = _label(j); + final (bg, fg) = switch (label) { + 'Waiting' => (AppColors.waitingBackground, AppColors.waitingText), + 'Failed' => (AppColors.failedBackground, AppColors.failedText), + _ => (AppColors.printedBackground, AppColors.printedText), + }; + final text = j.isFailed && j.failureReason != null + ? 'Failed: ${j.failureReason}' + : label; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: + BoxDecoration(color: bg, borderRadius: BorderRadius.circular(999)), + child: Text(text, + style: + TextStyle(color: fg, fontSize: 13, fontWeight: FontWeight.w600)), + ); + } + + Widget _avatar(String name) => Container( + width: 32, + height: 32, + alignment: Alignment.center, + decoration: + BoxDecoration(color: _avatarColor(name), shape: BoxShape.circle), + child: Text(initials(name), + style: const TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.w700)), + ); + + Widget _jobsSection() { + final jobs = _visibleJobs; + // Stretch the table to the card on wide screens; scroll sideways on narrow ones. + final tableWidth = + (MediaQuery.sizeOf(context).width - 48).clamp(760.0, 1200.0); + return _card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Wrap( + spacing: 12, + runSpacing: 12, + crossAxisAlignment: WrapCrossAlignment.end, + alignment: WrapAlignment.spaceBetween, + children: [ + const Text('All jobs', + style: + TextStyle(fontSize: 18, fontWeight: FontWeight.w700)), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + SizedBox( + width: 240, + child: TextField( + decoration: const InputDecoration( + labelText: 'Search user or file', + prefixIcon: Icon(Icons.search), + ), + onChanged: (v) => setState(() => _search = v), + ), + ), + SizedBox( + width: 140, + child: DropdownButtonFormField( + initialValue: _status, + decoration: const InputDecoration(labelText: 'Status'), + items: [ + for (final s in _statuses) + DropdownMenuItem(value: s, child: Text(s)), + ], + onChanged: (v) => setState(() => _status = v ?? 'All'), + ), + ), + ], + ), + ], + ), + ), + if (jobs.isEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), + child: Row( + children: [ + const Text('No jobs match.', + style: TextStyle(color: AppColors.muted)), + const SizedBox(width: 12), + TextButton( + onPressed: () => setState(() { + _search = ''; + _status = 'All'; + }), + child: const Text('Clear filters'), + ), + ], + ), + ) + else + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: ConstrainedBox( + constraints: BoxConstraints(minWidth: tableWidth), + child: DataTable( + headingRowColor: + const WidgetStatePropertyAll(Color(0xFFF9FAFB)), + headingTextStyle: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: AppColors.muted), + dataRowMinHeight: 60, + dataRowMaxHeight: 60, + columnSpacing: 32, + columns: const [ + DataColumn(label: Text('User')), + DataColumn(label: Text('Document')), + DataColumn(label: Text('Pages'), numeric: true), + DataColumn(label: Text('Sent')), + DataColumn(label: Text('Status')), + ], + rows: [ + for (final j in jobs) + DataRow(cells: [ + DataCell(Row(children: [ + _avatar(j.userName), + const SizedBox(width: 10), + Text(j.userName, + style: + const TextStyle(fontWeight: FontWeight.w600)), + ])), + DataCell(Row(children: [ + _FileStrip(j.fileName), + const SizedBox(width: 10), + Text(j.fileName), + ])), + DataCell(Text('${j.pages}')), + DataCell(Text(whenLabel(j.submittedAt.toLocal()))), + DataCell(_pill(j)), + ]), + ], + ), + ), + ), + ], ), ); } + + Widget _quotaSection() { + return _card( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.all(16), + child: Text('People and quotas', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700)), + ), + _quotaRule( + title: 'New people start with', + hint: 'Used the first time someone signs in.', + controller: _defaultQuotaField, + button: 'Save', + onPressed: _saveDefaultQuota, + ), + _quotaRule( + title: 'Give everyone', + hint: 'Replaces every limit, including ones set by hand.', + controller: _everyoneQuotaField, + button: 'Apply to everyone', + onPressed: _applyToEveryone, + ), + if (_users.isEmpty) + const Padding( + padding: EdgeInsets.fromLTRB(16, 0, 16, 24), + child: Text( + 'Nobody has signed in yet. People appear here the first time they sign in.', + style: TextStyle(color: AppColors.muted)), + ), + for (final u in _users) + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: const BoxDecoration( + border: Border(top: BorderSide(color: AppColors.lineSoft)), + ), + child: Wrap( + spacing: 24, + runSpacing: 12, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + SizedBox( + width: 200, + child: Row(children: [ + _avatar(u.name), + const SizedBox(width: 10), + Expanded( + child: Text(u.name, + overflow: TextOverflow.ellipsis, + style: + const TextStyle(fontWeight: FontWeight.w600)), + ), + ]), + ), + SizedBox( + width: 280, + child: Row(children: [ + Expanded( + child: ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: u.quota.total == 0 + ? 0 + : (u.quota.used / u.quota.total) + .clamp(0.0, 1.0), + minHeight: 8, + backgroundColor: AppColors.lineSoft, + color: u.quota.left == 0 + ? AppColors.pdf + : AppColors.primary, + ), + ), + ), + const SizedBox(width: 10), + Text( + u.quota.left == 0 + ? '${u.quota.used} of ${u.quota.total} · none left' + : '${u.quota.used} of ${u.quota.total}', + style: TextStyle( + fontSize: 14, + fontWeight: u.quota.left == 0 + ? FontWeight.w600 + : FontWeight.w400, + color: u.quota.left == 0 + ? AppColors.failedText + : AppColors.muted, + ), + ), + ]), + ), + SizedBox( + width: 150, + child: TextField( + controller: _quotaFields[u.userId], + keyboardType: TextInputType.number, + decoration: InputDecoration( + labelText: 'Pages per month', + semanticCounterText: 'Quota for ${u.name}', + ), + ), + ), + AppButton( + label: 'Save', + height: 44, + fontSize: 15, + radius: 10, + expand: false, + onPressed: () => _saveQuota(u), + ), + ], + ), + ), + ], + ), + ); + } +} + +/// Small file-type tile used in the admin table. +class _FileStrip extends StatelessWidget { + final String fileName; + const _FileStrip(this.fileName); + + @override + Widget build(BuildContext context) { + final (label, color) = DocThumbnail.kind(fileName); + return Container( + width: 34, + height: 42, + alignment: Alignment.center, + decoration: + BoxDecoration(color: color, borderRadius: BorderRadius.circular(3)), + child: Text(label, + style: const TextStyle( + color: Colors.white, + fontSize: 8, + fontWeight: FontWeight.w700, + letterSpacing: 0.4)), + ); + } } diff --git a/frontend/lib/screens/login_screen.dart b/frontend/lib/screens/login_screen.dart index 06273fa..c91de5a 100644 --- a/frontend/lib/screens/login_screen.dart +++ b/frontend/lib/screens/login_screen.dart @@ -1,49 +1,557 @@ import 'package:flutter/material.dart'; -import '../services/MsAuthService.dart'; +import 'package:provider/provider.dart'; +import '../models/session.dart'; +import '../services/print_repository.dart'; +import '../utils/constants.dart'; +import '../utils/theme.dart'; +import '../widgets/app_button.dart'; +import '../widgets/brand_mark.dart'; +import '../widgets/demo_banner.dart'; +import '../widgets/google_logo.dart'; +import '../widgets/microsoft_logo.dart'; +import '../widgets/printer_illustration.dart'; +import 'admin_dashboard_screen.dart'; import 'release_jobs_screen.dart'; class LoginScreen extends StatefulWidget { - const LoginScreen({super.key}); + /// Shown once on arrival, for example "Your session has ended". + final String? message; + const LoginScreen({super.key, this.message}); @override State createState() => _LoginScreenState(); } class _LoginScreenState extends State { - final _msalService = MsAuthService(); bool _loading = false; - Future _login() async { + /// How people sign in here. Null until the server has answered. + AuthConfig? _config; + bool _configFailed = false; + + /// Why the last work-account sign-in did not work. Stays until the next attempt. + String? _notice; + + @override + void initState() { + super.initState(); + final message = widget.message; + if (message != null) _notify(message); + _start(); + } + + void _notify(String message) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text(message))); + } + }); + } + + /// Finishes a work-account sign-in if the browser has just come back from one, + /// then finds out which sign-in options this server offers. + Future _start() async { + final repo = context.read(); + setState(() { + _configFailed = false; + _loading = true; + }); + try { + final session = await repo.resumeSignIn(); + if (!mounted) return; + if (session != null) { + _enter(session); + return; + } + } on PrintException catch (e) { + _notice = e.message; + } catch (_) { + _notice = 'Sign-in did not work. Please try again.'; + } + try { + final config = await repo.authConfig(); + if (!mounted) return; + Constants.demoMode = config.demo; + setState(() { + _config = config; + _loading = false; + }); + } catch (_) { + if (!mounted) return; + setState(() { + _configFailed = true; + _loading = false; + }); + } + } + + void _enter(Session session) { + Constants.demoMode = session.demo; + Navigator.of(context).pushReplacement(MaterialPageRoute( + builder: (_) => session.isAdmin + ? AdminDashboardScreen(session: session) + : ReleaseJobsScreen(session: session), + )); + } + + void _workspaceLogin() { + setState(() { + _notice = null; + _loading = true; + }); + context.read().startWorkspaceSignIn(); + } + + Future _login({bool asAdmin = false}) async { + final repo = context.read(); + final messenger = ScaffoldMessenger.of(context); setState(() => _loading = true); - final accessToken = await _msalService.login(); + Session? session; + String? failure; + try { + session = await repo.signIn(asAdmin: asAdmin); + } catch (e) { + session = null; + failure = e is PrintException ? e.message : null; + } + if (!mounted) return; setState(() => _loading = false); - if (accessToken != null) { - // Pass the token to the next screen - Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (_) => ReleaseJobsScreen(accessToken: accessToken), - ), + if (session == null) { + messenger.showSnackBar( + SnackBar(content: Text(failure ?? 'Sign-in failed. Please try again.')), ); + return; + } + _enter(session); + } + + /// The sign-in button and what goes with it, for the phone and the printer panel. + List _signInActions({required bool panel}) { + final config = _config; + final height = panel ? 64.0 : 56.0; + if (_configFailed) { + return [ + const Text('Cannot reach the print server.', + style: TextStyle(fontSize: 15, color: AppColors.failedText)), + const SizedBox(height: 12), + AppButton(label: 'Try again', onPressed: _start), + ]; + } + if (config == null) { + // Still asking the server; show a button that cannot be pressed yet. + return [ + MicrosoftSignInButton(onPressed: null, busy: true, height: height) + ]; + } + + final demoLinks = [ + if (config.demo && config.hasWorkspace) + panel + ? AppButton( + label: 'Try the demo', + style: AppButtonStyle.outline, + height: 48, + fontSize: 15, + onPressed: _loading ? null : _login, + ) + : Center( + child: TextButton( + onPressed: _loading ? null : _login, + child: const Text('Try the demo instead'), + ), + ), + if (config.demo) + panel + ? Padding( + padding: const EdgeInsets.only(top: 12), + child: AppButton( + label: 'Demo: sign in as administrator', + style: AppButtonStyle.outline, + height: 48, + fontSize: 15, + onPressed: _loading ? null : () => _login(asAdmin: true), + ), + ) + : Center( + child: TextButton( + onPressed: _loading ? null : () => _login(asAdmin: true), + child: const Text('Demo: sign in as administrator'), + ), + ), + ]; + + final Widget button; + if (!config.hasWorkspace) { + button = MicrosoftSignInButton( + onPressed: _login, busy: _loading, height: height); + } else if (config.provider == 'google') { + button = GoogleSignInButton( + onPressed: _workspaceLogin, busy: _loading, height: height); } else { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Login failed.')), - ); + button = MicrosoftSignInButton( + onPressed: _workspaceLogin, busy: _loading, height: height); } + + final domain = config.domain; + final hint = !config.hasWorkspace + ? 'No account needed. You get your own sample documents, and nothing is really printed.' + : (domain == null || domain.isEmpty + ? 'Use your work account. No new password.' + : 'Use your @$domain account. No new password.'); + final notice = _notice; + return [ + if (notice != null) ...[ + Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: AppColors.failedBackground, + borderRadius: BorderRadius.circular(10), + ), + child: Text(notice, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: AppColors.failedText)), + ), + const SizedBox(height: 12), + ], + button, + const SizedBox(height: 12), + Center( + child: Text(hint, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 13, color: AppColors.muted)), + ), + ...demoLinks, + ]; } @override Widget build(BuildContext context) { + final wide = MediaQuery.sizeOf(context).width >= AppTheme.panelBreakpoint; return Scaffold( - body: Center( - child: _loading - ? const CircularProgressIndicator() - : ElevatedButton( - onPressed: _login, - child: const Text('Sign in with Azure AD'), + backgroundColor: wide ? AppColors.background : AppColors.navy, + body: DemoShell(child: wide ? _panel() : _phone()), + ); + } + + Widget _circle(double size, Color color) => Container( + width: size, + height: size, + decoration: BoxDecoration(shape: BoxShape.circle, color: color), + ); + + Widget _phone() { + return LayoutBuilder(builder: (context, c) { + // On short phones drop the step cards and shrink the printer so the + // sign-in button stays on screen without scrolling. + // Large text takes more room, so the limit grows with it. + final textScale = MediaQuery.textScalerOf(context).scale(1); + final compact = c.maxHeight < 720 * (textScale > 1 ? textScale : 1); + final tiny = textScale >= 1.75; + return SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: c.maxHeight), + child: IntrinsicHeight( + child: Column( + children: [ + Stack( + children: [ + Positioned( + left: -60, + top: -80, + child: _circle(300, AppColors.navyLight)), + Positioned( + right: -90, + top: 120, + child: _circle(260, AppColors.navyDeep)), + SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(24, 20, 24, 8), + child: Column( + children: [ + const Row( + children: [ + BrandMark(size: 36), + SizedBox(width: 10), + Text( + Constants.appName, + style: TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.w700, + ), + ), + ], + ), + SizedBox(height: compact ? 12 : 32), + if (!tiny) + PrinterIllustration(width: compact ? 200 : 300), + ], + ), + ), + ), + ], + ), + Expanded( + child: Container( + width: double.infinity, + padding: const EdgeInsets.fromLTRB(24, 28, 24, 24), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius.vertical(top: Radius.circular(28)), + ), + child: SafeArea( + top: false, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Print now.\nCollect at any printer.', + style: TextStyle( + color: AppColors.navy, + fontSize: 28, + height: 1.15, + fontWeight: FontWeight.w800, + letterSpacing: -0.5, + ), + ), + const SizedBox(height: 14), + const Text( + 'Your documents wait safely until you are at the printer and tap Print.', + style: TextStyle( + fontSize: 15, + height: 1.5, + color: AppColors.muted), + ), + if (!compact) ...[ + const SizedBox(height: 16), + const IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded(child: _StepCard(1, 'Send a file')), + SizedBox(width: 8), + Expanded( + child: + _StepCard(2, 'Walk up and sign in')), + SizedBox(width: 8), + Expanded(child: _StepCard(3, 'Tap Print')), + ], + ), + ), + ], + const Spacer(), + const SizedBox(height: 20), + ..._signInActions(panel: false), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ); + }); + } + + Widget _panel() { + return Row( + children: [ + Container( + width: 440, + color: AppColors.navy, + child: Stack( + children: [ + Positioned( + left: -90, + bottom: -110, + child: _circle(360, AppColors.navyLight)), + const Padding( + padding: EdgeInsets.fromLTRB(40, 32, 40, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + BrandMark(size: 44), + SizedBox(width: 12), + Text( + Constants.appName, + style: TextStyle( + color: Colors.white, + fontSize: 24, + fontWeight: FontWeight.w700, + ), + ), + ], + ), + SizedBox(height: 48), + Text( + 'Sign in to collect your prints', + style: TextStyle( + color: Colors.white, + fontSize: 40, + height: 1.1, + fontWeight: FontWeight.w800, + letterSpacing: -0.8, + ), + ), + SizedBox(height: 12), + Text( + 'You will only see your own documents.', + style: TextStyle( + fontSize: 18, + height: 1.45, + color: AppColors.onNavyMuted), + ), + Expanded( + child: Center( + child: FittedBox( + fit: BoxFit.scaleDown, + child: PrinterIllustration(width: 300), + ), + ), + ), + ], + ), ), + ], + ), + ), + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(48, 28, 48, 32), + child: Column( + children: [ + const SizedBox(height: 24), + Expanded( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 520), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Container( + padding: const EdgeInsets.all(28), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: AppColors.primary, width: 2), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Sign in with your work account', + style: TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700), + ), + const SizedBox(height: 20), + ..._signInActions(panel: true), + ], + ), + ), + const SizedBox(height: 16), + Container( + height: 72, + padding: const EdgeInsets.symmetric(horizontal: 24), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: AppColors.line), + ), + child: Row( + children: [ + const Icon(Icons.badge_outlined, + size: 28, color: AppColors.muted), + const SizedBox(width: 16), + const Expanded( + child: Text( + 'Tap your staff card', + style: TextStyle( + fontSize: 18, color: AppColors.muted), + ), + ), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 4), + decoration: BoxDecoration( + border: Border.all(color: AppColors.line), + borderRadius: BorderRadius.circular(6), + ), + child: const Text( + 'Coming later', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: AppColors.muted, + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ], + ); + } +} + +class _StepCard extends StatelessWidget { + final int number; + final String label; + const _StepCard(this.number, this.label); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.fromLTRB(10, 12, 10, 12), + decoration: BoxDecoration( + color: AppColors.background, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 24, + height: 24, + alignment: Alignment.center, + decoration: const BoxDecoration( + color: AppColors.primary, shape: BoxShape.circle), + child: Text( + '$number', + style: const TextStyle( + color: Colors.white, + fontSize: 13, + fontWeight: FontWeight.w700), + ), + ), + const SizedBox(height: 6), + Text(label, + style: const TextStyle( + fontSize: 13, fontWeight: FontWeight.w600, height: 1.3)), + ], ), ); } -} \ No newline at end of file +} diff --git a/frontend/lib/screens/printed_screen.dart b/frontend/lib/screens/printed_screen.dart new file mode 100644 index 0000000..8b0f658 --- /dev/null +++ b/frontend/lib/screens/printed_screen.dart @@ -0,0 +1,368 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import '../models/print_job.dart'; +import '../models/session.dart'; +import '../utils/constants.dart'; +import '../utils/format.dart'; +import '../utils/theme.dart'; +import '../widgets/app_button.dart'; +import '../widgets/demo_banner.dart'; +import '../widgets/printer_illustration.dart'; +import 'login_screen.dart'; +import 'release_jobs_screen.dart'; + +/// Confirmation after printing. On the printer-panel layout it signs the user +/// out after [Constants.autoSignOutSeconds] so the next person never sees +/// this user's documents. +class PrintedScreen extends StatefulWidget { + final Session session; + final List printed; + + /// Where the documents are printing, such as "Level 3 East". + final String printerName; + + /// Documents that were chosen but did not print, and are still waiting. + final int notPrinted; + + /// Pages left after this print, or null when the quota is not known. + final int? pagesLeft; + final int totalPages; + + const PrintedScreen({ + super.key, + required this.session, + required this.printed, + required this.printerName, + this.notPrinted = 0, + required this.pagesLeft, + required this.totalPages, + }); + + @override + State createState() => _PrintedScreenState(); +} + +class _PrintedScreenState extends State { + Timer? _timer; + bool _timerStarted = false; + + int get _pages => widget.printed.fold(0, (n, j) => n + j.pages); + + String get _notPrintedText => widget.notPrinted == 1 + ? '1 document could not be printed and is still waiting.' + : '${widget.notPrinted} documents could not be printed and are still waiting.'; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final wide = MediaQuery.sizeOf(context).width >= AppTheme.panelBreakpoint; + if (wide && !_timerStarted) { + _timerStarted = true; + _timer = Timer( + const Duration(seconds: Constants.autoSignOutSeconds), _signOut); + } + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + void _signOut() { + _timer?.cancel(); + if (!mounted) return; + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => const LoginScreen()), + (_) => false, + ); + } + + void _backToDocuments() { + _timer?.cancel(); + Navigator.of(context).pushReplacement( + MaterialPageRoute( + builder: (_) => ReleaseJobsScreen(session: widget.session)), + ); + } + + @override + Widget build(BuildContext context) { + final wide = MediaQuery.sizeOf(context).width >= AppTheme.panelBreakpoint; + return Scaffold( + backgroundColor: AppColors.navy, + body: DemoShell(child: wide ? _panel() : _phone()), + ); + } + + Widget _tick(double size) => TweenAnimationBuilder( + tween: Tween(begin: 0.6, end: 1), + duration: const Duration(milliseconds: 500), + curve: Curves.easeOutBack, + builder: (context, v, child) => Transform.scale(scale: v, child: child), + child: Container( + width: size, + height: size, + decoration: const BoxDecoration( + color: AppColors.success, shape: BoxShape.circle), + child: Icon(Icons.check, color: Colors.white, size: size * 0.55), + ), + ); + + Widget _circle(double size, Color color) => Container( + width: size, + height: size, + decoration: BoxDecoration(shape: BoxShape.circle, color: color), + ); + + Widget _phone() { + return LayoutBuilder(builder: (context, c) { + return SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: c.maxHeight), + child: IntrinsicHeight( + child: Column( + children: [ + SizedBox( + width: double.infinity, + child: Stack( + children: [ + Positioned( + right: -70, + top: -60, + child: _circle(260, AppColors.navyLight)), + SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(24, 48, 24, 8), + child: SizedBox( + width: double.infinity, + child: Column( + children: [ + _tick(64), + const SizedBox(height: 20), + Text( + 'Printing at ${widget.printerName}', + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white, + fontSize: 28, + height: 1.15, + fontWeight: FontWeight.w800, + letterSpacing: -0.4, + ), + ), + const SizedBox(height: 10), + Text( + widget.session.demo + ? 'This is a demo, so nothing was really printed.' + : 'Collect your pages from the tray.', + textAlign: TextAlign.center, + style: const TextStyle( + fontSize: 15, + color: AppColors.onNavyMuted), + ), + const SizedBox(height: 24), + const PrinterIllustration(width: 240), + ], + ), + ), + ), + ), + ], + ), + ), + Expanded( + child: Container( + width: double.infinity, + padding: const EdgeInsets.fromLTRB(24, 20, 24, 24), + decoration: const BoxDecoration( + color: Colors.white, + borderRadius: + BorderRadius.vertical(top: Radius.circular(28)), + ), + child: SafeArea( + top: false, + child: Column( + children: [ + for (final j in widget.printed) + _row(j.fileName, pagesLabel(j.pages)), + if (widget.notPrinted > 0) + Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + _notPrintedText, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: AppColors.failedText), + ), + ), + if (widget.pagesLeft != null) + Padding( + padding: const EdgeInsets.only(top: 12), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + const Expanded( + child: Text('Pages left this month', + style: TextStyle( + fontSize: 15, + color: AppColors.muted)), + ), + const SizedBox(width: 12), + Text( + '${widget.pagesLeft} of ${widget.totalPages}', + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.w800, + color: AppColors.navy, + ), + ), + ], + ), + ), + const Spacer(), + const SizedBox(height: 16), + AppButton( + label: 'Back to my documents', + onPressed: _backToDocuments), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ); + }); + } + + Widget _row(String name, String pages) => Container( + padding: const EdgeInsets.symmetric(vertical: 10), + decoration: const BoxDecoration( + border: Border(bottom: BorderSide(color: AppColors.lineSoft)), + ), + child: Row( + children: [ + Expanded( + child: Text(name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 15, fontWeight: FontWeight.w600)), + ), + const SizedBox(width: 12), + Text(pages, + style: const TextStyle(fontSize: 15, color: AppColors.muted)), + ], + ), + ); + + Widget _panel() { + return Stack( + children: [ + Positioned( + left: -120, top: -120, child: _circle(420, AppColors.navyLight)), + Positioned( + right: -80, bottom: -140, child: _circle(400, AppColors.navyDeep)), + Row( + children: [ + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 56), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _tick(80), + const SizedBox(height: 18), + Text( + 'Printing ${pagesLabel(_pages)}', + style: const TextStyle( + color: Colors.white, + fontSize: 48, + height: 1.08, + fontWeight: FontWeight.w800, + letterSpacing: -1, + ), + ), + const SizedBox(height: 18), + Text( + '${widget.session.demo ? 'This is a demo, so nothing was really printed.' : 'Collect your documents from the tray.'}' + '${widget.notPrinted > 0 ? '\n$_notPrintedText' : ''}' + '${widget.pagesLeft == null ? '' : '\nYou have ${widget.pagesLeft} pages left this month.'}', + style: const TextStyle( + fontSize: 22, + height: 1.4, + color: AppColors.onNavyMuted), + ), + const SizedBox(height: 28), + Row( + children: [ + AppButton( + label: 'Print more', + style: AppButtonStyle.onNavy, + height: 64, + fontSize: 20, + radius: 14, + expand: false, + onPressed: _backToDocuments, + ), + const SizedBox(width: 16), + AppButton( + label: 'Sign out', + style: AppButtonStyle.light, + height: 64, + fontSize: 20, + radius: 14, + expand: false, + onPressed: _signOut, + ), + ], + ), + const SizedBox(height: 24), + SizedBox( + width: 360, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('Signing out automatically', + style: TextStyle( + fontSize: 15, color: AppColors.onNavyMuted)), + const SizedBox(height: 8), + ClipRRect( + borderRadius: BorderRadius.circular(3), + child: TweenAnimationBuilder( + tween: Tween(begin: 1, end: 0), + duration: const Duration( + seconds: Constants.autoSignOutSeconds), + builder: (context, v, _) => + LinearProgressIndicator( + value: v, + minHeight: 6, + backgroundColor: AppColors.ringTrack, + color: AppColors.ringFill, + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + const SizedBox( + width: 440, + child: Center(child: PrinterIllustration(width: 400)), + ), + ], + ), + ], + ); + } +} diff --git a/frontend/lib/screens/release_jobs_screen.dart b/frontend/lib/screens/release_jobs_screen.dart index 11bd7a7..68387bb 100644 --- a/frontend/lib/screens/release_jobs_screen.dart +++ b/frontend/lib/screens/release_jobs_screen.dart @@ -1,142 +1,725 @@ +import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import '../models/print_job.dart'; -import '../services/api_service.dart'; +import '../models/printer.dart'; +import '../models/session.dart'; +import '../services/print_repository.dart'; import '../utils/constants.dart'; +import '../utils/format.dart'; +import '../utils/theme.dart'; +import '../widgets/app_button.dart'; +import '../widgets/brand_mark.dart'; +import '../widgets/demo_banner.dart'; import '../widgets/job_card.dart'; +import '../widgets/quota_ring.dart'; import 'login_screen.dart'; +import 'printed_screen.dart'; +/// Lists the signed-in user's waiting documents and prints the ones chosen. +/// Phone layout below [AppTheme.panelBreakpoint], printer-panel layout above. class ReleaseJobsScreen extends StatefulWidget { - final String accessToken; - const ReleaseJobsScreen({required this.accessToken, super.key}); + final Session session; + const ReleaseJobsScreen({required this.session, super.key}); @override State createState() => _ReleaseJobsScreenState(); } class _ReleaseJobsScreenState extends State { - final _api = ApiService(); - late Future> _jobs; - bool _releasing = false; + bool _loading = true; + Object? _error; + List _jobs = const []; + QuotaInfo _quota = QuotaInfo.unknown; + Set _selected = {}; + List _printers = const []; + Printer? _printer; + + /// True when the address names a printer (`?printer=`), as on a printer's own panel. + bool _printerLocked = false; + bool _printing = false; + Timer? _idleTimer; + bool _idleStarted = false; @override void initState() { super.initState(); - _fetchJobs(); + _load(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // A printer panel is shared, so it signs out a person who walks away. + final wide = MediaQuery.sizeOf(context).width >= AppTheme.panelBreakpoint; + if (wide && !_idleStarted) { + _idleStarted = true; + _resetIdle(); + } + } + + @override + void dispose() { + _idleTimer?.cancel(); + super.dispose(); + } + + void _resetIdle() { + if (!_idleStarted) return; + _idleTimer?.cancel(); + _idleTimer = Timer( + const Duration(seconds: Constants.idleSignOutSeconds), + () => + _signOut(message: 'You were signed out because the screen was idle.'), + ); } - void _fetchJobs() { + Future _load() async { + final repo = context.read(); setState(() { - _jobs = _api.fetchMyHeldJobs(token: widget.accessToken); + _loading = true; + _error = null; }); + try { + final results = await Future.wait([ + repo.myHeldJobs(widget.session), + repo.myQuota(widget.session), + repo.printers(widget.session), + ]); + if (!mounted) return; + final jobs = results[0] as List; + final quota = results[1] as QuotaInfo; + final printers = + (results[2] as List).where((p) => p.enabled).toList(); + final fixed = repo.panelPrinterId; + Printer? chosen; + for (final p in printers) { + if (p.id == fixed) chosen = p; + } + chosen ??= printers.where((p) => p.id == _printer?.id).firstOrNull; + chosen ??= printers.firstOrNull; + setState(() { + _printers = printers; + _printer = chosen; + _printerLocked = fixed != null && chosen?.id == fixed; + _jobs = jobs; + _quota = quota; + _selected = _defaultSelection(jobs, quota); + _loading = false; + }); + } on SessionExpiredException catch (e) { + _signOut(message: e.message); + } catch (e) { + if (!mounted) return; + setState(() { + _error = e; + _loading = false; + }); + } } - Future _release(PrintJob job) async { - if (Constants.defaultPrinterId == null) { - if (!mounted) return; - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('No default printer configured.')), - ); + Future _sendSamples(int count) async { + final repo = context.read(); + final messenger = ScaffoldMessenger.of(context); + try { + await repo.sendSampleDocuments(widget.session, count: count); + } on SessionExpiredException catch (e) { + _signOut(message: e.message); return; + } on PrintException catch (e) { + messenger.showSnackBar(SnackBar(content: Text(e.message))); + } + if (mounted) _load(); + } + + /// Newest documents first, stopping at the first one that would go over quota. + Set _defaultSelection(List jobs, QuotaInfo quota) { + final picked = {}; + var pages = 0; + for (final j in jobs) { + if (quota.known && pages + j.pages > quota.left) break; + picked.add(j.id); + pages += j.pages; + } + return picked; + } + + int get _pages => _jobs + .where((j) => _selected.contains(j.id)) + .fold(0, (n, j) => n + j.pages); + int get _count => _selected.length; + bool get _over => _quota.known && _pages > _quota.left; + bool get _canPrint => _count > 0 && !_over && !_printing && _printer != null; + bool get _allSelected => _jobs.isNotEmpty && _selected.length == _jobs.length; + + void _toggleAll() { + setState(() { + _selected = _allSelected ? {} : _jobs.map((j) => j.id).toSet(); + }); + } + + /// Why the selection cannot be printed, in words that say what to do. + String get _overText { + final left = _quota.left; + if (left == 0) return 'No pages left this month.'; + if (_count == 1) { + return 'This document needs $_pages pages. You have $left left.'; } + return 'Over your limit by ${_pages - left} pages. Untick one.'; + } - setState(() => _releasing = true); + void _toggle(PrintJob job, bool on) { + setState(() => on ? _selected.add(job.id) : _selected.remove(job.id)); + } + Future _print() async { + final repo = context.read(); + final messenger = ScaffoldMessenger.of(context); + final navigator = Navigator.of(context); + final ids = _selected.toList(); + setState(() => _printing = true); try { - await _api.releaseJob( - token: widget.accessToken, - jobId: job.id, - ); + final printedIds = + await repo.release(widget.session, ids, printerId: _printer?.id); if (!mounted) return; - _fetchJobs(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Released: ${job.fileName}')), - ); + final printed = _jobs.where((j) => printedIds.contains(j.id)).toList(); + if (printed.isEmpty) { + messenger.showSnackBar(const SnackBar( + content: Text( + 'The printer could not print your documents. They are still waiting.'), + )); + setState(() => _printing = false); + _load(); + return; + } + final pagesPrinted = printed.fold(0, (n, j) => n + j.pages); + navigator.pushReplacement(MaterialPageRoute( + builder: (_) => PrintedScreen( + session: widget.session, + printed: printed, + printerName: _printer?.name ?? 'the printer', + notPrinted: ids.length - printed.length, + pagesLeft: _quota.known ? _quota.left - pagesPrinted : null, + totalPages: _quota.total, + ), + )); + } on QuotaExceededException catch (e) { + if (!mounted) return; + messenger.showSnackBar(SnackBar(content: Text(e.toString()))); + setState(() => _printing = false); + _load(); + } on SessionExpiredException catch (e) { + _signOut(message: e.message); + } on PrintException catch (e) { + // Often "those documents are not waiting": the list was out of date. + if (!mounted) return; + messenger.showSnackBar(SnackBar( + content: Text('${e.message} Your list has been refreshed.'))); + setState(() => _printing = false); + _load(); } catch (e) { if (!mounted) return; - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Release failed: $e')), + messenger.showSnackBar( + const SnackBar( + content: + Text('Could not print. Your documents are still waiting.')), ); - } finally { - if (mounted) setState(() => _releasing = false); + setState(() => _printing = false); } } + void _signOut({String? message}) { + if (!mounted) return; + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => LoginScreen(message: message)), + (_) => false, + ); + } + @override Widget build(BuildContext context) { + final wide = MediaQuery.sizeOf(context).width >= AppTheme.panelBreakpoint; + final content = DemoShell( + child: Column( + children: [ + wide ? _panelHeader() : _phoneHeader(), + Expanded(child: _body(wide)), + if (!_loading && _error == null && _jobs.isNotEmpty) _footer(wide), + ], + ), + ); return Scaffold( - appBar: AppBar( - title: const Text('My Print Jobs'), - elevation: 2, - actions: [ - IconButton( - icon: const Icon(Icons.logout), - onPressed: () => Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (_) => const LoginScreen()), + backgroundColor: AppColors.background, + body: wide + ? Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: (_) => _resetIdle(), + onPointerMove: (_) => _resetIdle(), + onPointerSignal: (_) => _resetIdle(), + child: content, + ) + : content, + ); + } + + // ---- headers --------------------------------------------------------- + + Widget _phoneHeader() { + return Column( + children: [ + Container( + color: AppColors.navy, + padding: const EdgeInsets.fromLTRB(20, 0, 20, 16), + child: SafeArea( + bottom: false, + child: Column( + children: [ + const SizedBox(height: 16), + Row( + children: [ + const BrandMark(size: 28), + const SizedBox(width: 8), + const Expanded( + child: Text( + Constants.appName, + style: TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.w700), + ), + ), + IconButton( + tooltip: 'Sign out', + onPressed: () => _signOut(), + style: IconButton.styleFrom( + backgroundColor: AppColors.navyChip, + foregroundColor: Colors.white, + minimumSize: const Size(44, 44), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + ), + icon: const Icon(Icons.logout), + ), + ], + ), + const SizedBox(height: 16), + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(greeting(), + style: const TextStyle( + fontSize: 14, color: AppColors.onNavyMuted)), + Text( + widget.session.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + color: Colors.white, + fontSize: 26, + fontWeight: FontWeight.w800, + letterSpacing: -0.4, + ), + ), + if (!_loading && _error == null) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text( + _jobs.length == 1 + ? '1 document waiting' + : '${_jobs.length} documents waiting', + style: const TextStyle( + fontSize: 14, color: AppColors.onNavyMuted), + ), + ), + ], + ), + ), + if (_quota.known) QuotaRing(quota: _quota), + ], + ), + ], ), ), + ), + // Rounded top edge of the content sheet. + Container( + height: 24, + color: AppColors.navy, + child: Container( + decoration: const BoxDecoration( + color: AppColors.background, + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + ), + ), + ], + ); + } + + Widget _panelHeader() { + return Container( + height: 72, + color: AppColors.navy, + padding: const EdgeInsets.symmetric(horizontal: 32), + child: Row( + children: [ + const BrandMark(size: 36), + const SizedBox(width: 16), + Text( + widget.session.name, + style: const TextStyle( + color: Colors.white, fontSize: 22, fontWeight: FontWeight.w800), + ), + const SizedBox(width: 16), + if (_printer != null) ...[ + const Icon(Icons.print_outlined, + size: 20, color: AppColors.onNavyMuted), + const SizedBox(width: 6), + Text(_printer!.name, + style: const TextStyle( + fontSize: 16, color: AppColors.onNavyMuted)), + const SizedBox(width: 16), + ], + if (_quota.known) + Text( + '${_quota.left} pages left this month', + style: + const TextStyle(fontSize: 16, color: AppColors.onNavyMuted), + ), + const Spacer(), + AppButton( + label: 'Sign out', + icon: Icons.logout, + style: AppButtonStyle.onNavy, + height: 48, + fontSize: 16, + expand: false, + onPressed: () => _signOut(), + ), ], ), - body: RefreshIndicator( - onRefresh: () async => _fetchJobs(), - child: Stack( + ); + } + + // ---- body -------------------------------------------------------------- + + Widget _body(bool wide) { + if (_loading) { + return const Center(child: CircularProgressIndicator()); + } + if (_error != null) { + return _message( + 'Cannot reach the print server.', + 'Check your connection and try again.', + action: AppButton( + label: 'Try again', + expand: false, + onPressed: _load, + ), + ); + } + if (_jobs.isEmpty) { + return _message( + 'Nothing waiting to print.', + widget.session.demo + ? 'This is a demo, so you can send yourself some sample documents.' + : 'Send a file to Pull Print from your computer.', + action: widget.session.demo + ? AppButton( + label: 'Send sample documents', + expand: false, + onPressed: () => _sendSamples(4), + ) + : AppButton( + label: 'Check again', + style: AppButtonStyle.outline, + expand: false, + onPressed: _load, + ), + ); + } + + final titleStyle = TextStyle( + fontSize: wide ? 28 : 18, + fontWeight: wide ? FontWeight.w800 : FontWeight.w700, + ); + final hint = TextStyle(fontSize: wide ? 16 : 14, color: AppColors.muted); + final pad = wide ? 32.0 : 20.0; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: EdgeInsets.fromLTRB(pad, wide ? 20 : 4, pad, wide ? 12 : 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Expanded( + child: Text(wide ? 'Your documents' : 'Waiting to print', + style: titleStyle), + ), + if (wide) + Text('Tap a document to include or leave it out', style: hint), + TextButton( + onPressed: _toggleAll, + style: + TextButton.styleFrom(minimumSize: Size(64, wide ? 48 : 44)), + child: Text(_allSelected ? 'Clear' : 'Select all'), + ), + ], + ), + ), + Expanded( + child: RefreshIndicator( + onRefresh: _load, + child: wide ? _grid(pad) : _list(pad), + ), + ), + if (widget.session.demo) + Padding( + padding: EdgeInsets.symmetric(horizontal: pad - 8), + child: TextButton.icon( + onPressed: () => _sendSamples(1), + icon: const Icon(Icons.add), + label: const Text('Send another sample document'), + ), + ), + ], + ); + } + + Widget _list(double pad) { + return ListView.separated( + physics: const AlwaysScrollableScrollPhysics(), + padding: EdgeInsets.fromLTRB(pad, 0, pad, 16), + itemCount: _jobs.length, + separatorBuilder: (_, __) => const SizedBox(height: 10), + itemBuilder: (context, i) => JobTile( + job: _jobs[i], + selected: _selected.contains(_jobs[i].id), + onChanged: (on) => _toggle(_jobs[i], on), + ), + ); + } + + Widget _grid(double pad) { + final textScale = MediaQuery.textScalerOf(context).scale(1); + return GridView.builder( + physics: const AlwaysScrollableScrollPhysics(), + padding: EdgeInsets.fromLTRB(pad, 4, pad, 16), + gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 260, + mainAxisExtent: 262 + 140 * (textScale > 1 ? textScale - 1 : 0), + crossAxisSpacing: 16, + mainAxisSpacing: 16, + ), + itemCount: _jobs.length, + itemBuilder: (context, i) => JobCard( + job: _jobs[i], + selected: _selected.contains(_jobs[i].id), + onChanged: (on) => _toggle(_jobs[i], on), + ), + ); + } + + Widget _message(String title, String detail, {required Widget action}) { + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, children: [ - FutureBuilder>( - future: _jobs, - builder: (context, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Center(child: CircularProgressIndicator()); - } - if (snap.hasError) { - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.error_outline, - size: 48, color: Colors.red), - const SizedBox(height: 16), - Text( - 'Error: ${snap.error}', - textAlign: TextAlign.center, - ), - ], - ), - ); - } - final jobs = snap.data ?? []; - if (jobs.isEmpty) { - return const Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.print_disabled, - size: 48, color: Colors.grey), - SizedBox(height: 16), - Text('No held jobs.'), - ], - ), - ); - } - return ListView.builder( - padding: const EdgeInsets.all(8), - itemCount: jobs.length, - itemBuilder: (context, i) => JobCard( - job: jobs[i], - onRelease: _releasing ? null : () => _release(jobs[i]), - ), - ); - }, + Text(title, + textAlign: TextAlign.center, + style: + const TextStyle(fontSize: 22, fontWeight: FontWeight.w800)), + const SizedBox(height: 8), + Text(detail, + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 16, color: AppColors.muted)), + const SizedBox(height: 20), + action, + ], + ), + ), + ); + } + + // ---- footer ------------------------------------------------------------ + + String get _summary => + '${_count == 1 ? '1 document' : '$_count documents'} · $_pages pages'; + + String? get _afterText { + if (!_quota.known) return null; + return _over + ? _overText + : '${_quota.left - _pages} pages left after printing'; + } + + String get _blockText => _printer == null + ? 'No printer available' + : _count == 0 + ? 'Select a document' + : (_quota.left == 0 ? 'No pages left' : 'Over your limit'); + + /// "Printer: Level 3 East" on the phone. Tap to pick another when there is a choice. + Widget _printerRow() { + final canPick = _printers.length > 1 && !_printerLocked && !_printing; + final row = Row( + children: [ + const Icon(Icons.print_outlined, size: 18, color: AppColors.muted), + const SizedBox(width: 8), + const Text('Printer', + style: TextStyle(fontSize: 14, color: AppColors.muted)), + const SizedBox(width: 12), + Expanded( + child: Text( + _printer?.name ?? 'None set up yet', + textAlign: TextAlign.end, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: _printer == null ? AppColors.failedText : null, ), - if (_releasing) - Container( - color: Colors.black.withOpacity(0.1), - child: const Center( - child: CircularProgressIndicator(), - ), + ), + ), + if (canPick) + const Icon(Icons.expand_more, size: 20, color: AppColors.muted), + ], + ); + if (!canPick) return row; + return InkWell( + onTap: _pickPrinter, + borderRadius: BorderRadius.circular(8), + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 44), + child: Align(alignment: Alignment.center, child: row), + ), + ); + } + + Future _pickPrinter() async { + final picked = await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (context) => SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.fromLTRB(24, 0, 24, 8), + child: Text('Print at', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w700)), + ), + for (final p in _printers) + ListTile( + minVerticalPadding: 12, + title: Text(p.name), + subtitle: p.location.isEmpty ? null : Text(p.location), + trailing: p.id == _printer?.id + ? const Icon(Icons.check, color: AppColors.primary) + : null, + onTap: () => Navigator.of(context).pop(p), ), ], ), ), ); + if (picked != null && mounted) setState(() => _printer = picked); + } + + Widget _footer(bool wide) { + const shadow = [ + BoxShadow(color: Color(0x0F0E2A47), blurRadius: 18, offset: Offset(0, -6)) + ]; + if (wide) { + return Container( + height: 104, + padding: const EdgeInsets.symmetric(horizontal: 32), + decoration: const BoxDecoration( + color: Colors.white, + border: Border(top: BorderSide(color: AppColors.line)), + boxShadow: shadow, + ), + child: Row( + children: [ + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(_summary, + style: const TextStyle( + fontSize: 22, fontWeight: FontWeight.w800)), + if (_afterText != null) + Text(_afterText!, + style: TextStyle( + fontSize: 16, + color: _over ? AppColors.failedText : AppColors.muted, + )), + ], + ), + ), + SizedBox( + width: 320, + child: AppButton( + label: _canPrint || _printing ? 'Print' : _blockText, + icon: _canPrint || _printing ? Icons.print_outlined : null, + height: 72, + fontSize: 26, + radius: 16, + busy: _printing, + onPressed: _canPrint ? _print : null, + ), + ), + ], + ), + ); + } + return Container( + decoration: const BoxDecoration( + color: Colors.white, + border: Border(top: BorderSide(color: AppColors.line)), + boxShadow: shadow, + ), + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(20, 14, 20, 12), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _printerRow(), + const SizedBox(height: 12), + AppButton( + label: _canPrint || _printing + ? 'Print ${_count == 1 ? '1 document' : '$_count documents'} · $_pages pages' + : (_printer == null + ? 'No printer available' + : (_over ? _overText : 'Select a document to print')), + busy: _printing, + onPressed: _canPrint ? _print : null, + ), + if (_over && widget.session.demo) + const Padding( + padding: EdgeInsets.only(top: 8), + child: Text( + 'Demo tip: go back to sign-in and choose the administrator demo to raise your limit.', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 13, color: AppColors.muted), + ), + ), + ], + ), + ), + ), + ); } } diff --git a/frontend/lib/services/MsAuthService.dart b/frontend/lib/services/MsAuthService.dart deleted file mode 100644 index a7528bc..0000000 --- a/frontend/lib/services/MsAuthService.dart +++ /dev/null @@ -1,25 +0,0 @@ -import 'package:msal_flutter/msal_flutter.dart'; -import 'package:flutter/foundation.dart'; - -class MsAuthService { - late final PublicClientApplication _pca; - - Future init() async { - _pca = await PublicClientApplication.createPublicClientApplication( - '880bec29-de8b-49b2-9911-e12da787f3f1', - authority: - 'https://login.microsoftonline.com/e0cb52e9-ea0c-4e1b-96e0-ada23537ba49', - redirectUri: 'msal880bec29-de8b-49b2-9911-e12da787f3f1://auth', - ); - } - - Future login() async { - try { - final token = await _pca.acquireToken(['User.Read']); - return token; // Access token - } catch (e) { - debugPrint('Login failed: $e'); - return null; - } - } -} diff --git a/frontend/lib/services/api_service.dart b/frontend/lib/services/api_service.dart index b95ac71..5639069 100644 --- a/frontend/lib/services/api_service.dart +++ b/frontend/lib/services/api_service.dart @@ -1,48 +1,215 @@ +import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; import '../models/print_job.dart'; +import '../models/printer.dart'; +import '../models/session.dart'; +import '../utils/constants.dart'; +import 'print_repository.dart'; +/// Thin client for the backend API (see backend/controllers). Turns HTTP errors +/// into [PrintException], [QuotaExceededException] and [SessionExpiredException]. class ApiService { - final String baseUrl = "http://localhost:3000"; - // Adjust the base URL as needed for your backend + ApiService({http.Client? client, String? baseUrl}) + : _client = client ?? http.Client(), + baseUrl = baseUrl ?? Constants.apiBaseUrl; - Future> fetchAllJobs({required String token}) async { - final response = await http.get( - Uri.parse('$baseUrl/jobs'), - headers: {'Authorization': 'Bearer $token'}, - ); + final http.Client _client; + final String baseUrl; + + static const _timeout = Duration(seconds: 20); + + Future _send( + String method, + String path, { + String? token, + Object? body, + }) async { + final request = http.Request(method, Uri.parse('$baseUrl$path')) + ..headers['Accept'] = 'application/json'; + if (token != null) request.headers['Authorization'] = 'Bearer $token'; + if (body != null) { + request.headers['Content-Type'] = 'application/json'; + request.body = jsonEncode(body); + } + + http.Response response; + try { + response = await http.Response.fromStream( + await _client.send(request).timeout(_timeout)); + } on TimeoutException { + throw const PrintException('The print server took too long to answer.'); + } on http.ClientException { + throw const PrintException('Cannot reach the print server.'); + } + + final decoded = response.body.isEmpty ? null : _tryDecode(response.body); + if (response.statusCode >= 200 && response.statusCode < 300) return decoded; + + if (response.statusCode == 401) throw const SessionExpiredException(); + if (response.statusCode == 429) { + throw const PrintException( + 'Too many requests. Please wait a minute and try again.'); + } + if (decoded is Map) { + if (response.statusCode == 409 && decoded['error'] == 'quota_exceeded') { + throw QuotaExceededException( + (decoded['pagesOver'] as num?)?.toInt() ?? 0); + } + final message = decoded['message']; + if (message is String && message.isNotEmpty) { + throw PrintException(message); + } + } + if (response.statusCode == 403) { + throw const PrintException('You do not have permission to do that.'); + } + throw PrintException( + 'The server could not do that (error ${response.statusCode}).'); + } - if (response.statusCode != 200) { - throw Exception('Failed to fetch jobs: ${response.statusCode}'); + static dynamic _tryDecode(String body) { + try { + return jsonDecode(body); + } on FormatException { + return null; } + } + + static Session _session(Map json, String token, + {required bool demo}) => + Session( + token: token, + userId: json['userId'] as String, + name: json['name'] as String, + isAdmin: json['isAdmin'] as bool? ?? false, + demo: demo, + ); - final List data = jsonDecode(response.body); - return data.map((json) => PrintJob.fromJson(json)).toList(); + static QuotaInfo _quota(Map json) => QuotaInfo( + used: (json['used'] as num).toInt(), + total: (json['total'] as num).toInt(), + ); + + /// Demo sign-in: a private sandbox with sample documents. + Future demoLogin({bool admin = false}) async { + final json = + await _send('POST', '/auth/demo-login', body: {'admin': admin}); + return _session(json as Map, json['token'] as String, + demo: true); + } + + /// Who the token belongs to, used after a work-account sign-in. + Future me(String token) async { + final json = await _send('GET', '/auth/me', token: token); + return _session(json as Map, token, demo: false); } - Future> fetchMyHeldJobs({required String token}) async { - final response = await http.get( - Uri.parse('$baseUrl/jobs/held'), - headers: {'Authorization': 'Bearer $token'}, + Future authConfig() async { + final json = await _send('GET', '/auth/config') as Map; + return AuthConfig( + provider: (json['provider'] as String? ?? 'none').toLowerCase(), + domain: json['domain'] as String?, + demo: json['demo'] as bool? ?? false, ); + } - if (response.statusCode != 200) { - throw Exception('Failed to fetch held jobs: ${response.statusCode}'); - } + Future> printers(String token) async { + final json = await _send('GET', '/printers', token: token) as List; + return json + .map((p) => Printer.fromJson(p as Map)) + .toList(); + } + + Future> heldJobs(String token) async { + final json = + await _send('GET', '/jobs/held', token: token) as List; + return json + .map((j) => PrintJob.fromJson(j as Map)) + .toList(); + } + + Future quota(String token) async => _quota( + await _send('GET', '/jobs/quota', token: token) as Map); - final List data = jsonDecode(response.body); - return data.map((json) => PrintJob.fromJson(json)).toList(); + /// Ids of the jobs that really printed. + Future> release(String token, List jobIds, + {String? printerId}) async { + final json = await _send('POST', '/jobs/release', token: token, body: { + 'jobIds': jobIds, + if (printerId != null) 'printerId': printerId, + }) as Map; + return (json['printed'] as List).cast(); } - Future releaseJob({required String token, required String jobId}) async { - final response = await http.post( - Uri.parse('$baseUrl/jobs/release'), - headers: {'Authorization': 'Bearer $token', 'Content-Type': 'application/json'}, - body: jsonEncode({'jobId': jobId}), + Future sendSample(String token) => + _send('POST', '/jobs/sample', token: token); + + Future> allJobs(String token) async { + final json = await _send('GET', '/jobs', token: token) as List; + return json + .map((j) => PrintJob.fromJson(j as Map)) + .toList(); + } + + Future> users(String token) async { + final json = + await _send('GET', '/admin/users', token: token) as List; + return json.map((u) { + final m = u as Map; + return UserQuota( + userId: m['userId'] as String, + name: m['name'] as String, + email: m['email'] as String?, + quota: _quota(m['quota'] as Map), + ); + }).toList(); + } + + Future setQuota(String token, String userId, int quota) => _send( + 'POST', + '/admin/set-quota', + token: token, + body: {'userId': userId, 'quota': quota}, + ); + + Future setup(String token) async { + final m = await _send('GET', '/admin/setup', token: token) + as Map; + return SetupInfo( + provider: m['provider'] as String? ?? 'None', + domain: m['domain'] as String?, + demoEnabled: m['demoEnabled'] as bool? ?? false, + defaultQuota: (m['defaultQuota'] as num).toInt(), + people: (m['people'] as num).toInt(), + printers: (m['printers'] as num).toInt(), + redirectUri: m['redirectUri'] as String? ?? '', + warnings: (m['warnings'] as List? ?? const []).cast(), ); + } - if (response.statusCode != 200) { - throw Exception('Failed to release job: ${response.statusCode}'); - } + Future setDefaultQuota(String token, int quota) => + _send('POST', '/admin/default-quota', + token: token, body: {'quota': quota}); + + Future setQuotaForAll(String token, int quota) async { + final m = await _send('POST', '/admin/set-quota-all', + token: token, body: {'quota': quota}) as Map; + return (m['changed'] as num?)?.toInt() ?? 0; } + + Future addPrinter( + String token, String name, String location) async => + Printer.fromJson(await _send('POST', '/admin/printers', + token: token, + body: {'name': name, 'location': location}) as Map); + + Future updatePrinter(String token, Printer p) => + _send('PUT', '/admin/printers/${Uri.encodeComponent(p.id)}', + token: token, + body: {'name': p.name, 'location': p.location, 'enabled': p.enabled}); + + Future deletePrinter(String token, String id) => + _send('DELETE', '/admin/printers/${Uri.encodeComponent(id)}', + token: token); } diff --git a/frontend/lib/services/auth_service.dart b/frontend/lib/services/auth_service.dart deleted file mode 100644 index f9ddf3c..0000000 --- a/frontend/lib/services/auth_service.dart +++ /dev/null @@ -1,20 +0,0 @@ -class AuthService { - String? _userId; - String? _displayName; - bool _isAdmin = false; - - /// Simulated login: replace with MSAL later - Future loginWithAzureAD({required bool asAdmin}) async { - await Future.delayed(const Duration(milliseconds: 400)); - _userId = asAdmin ? 'admin-id' : 'user-id'; - _displayName = asAdmin ? 'Admin User' : 'Regular User'; - _isAdmin = asAdmin; - return true; - } - - String? currentUserId() => _userId; - String? currentUserName() => _displayName; - bool get isAdmin => _isAdmin; - - Future getAccessTokenOrNull() async => null; // MSAL token later -} diff --git a/frontend/lib/services/http_print_repository.dart b/frontend/lib/services/http_print_repository.dart new file mode 100644 index 0000000..e0b8640 --- /dev/null +++ b/frontend/lib/services/http_print_repository.dart @@ -0,0 +1,140 @@ +import '../models/print_job.dart'; +import '../models/printer.dart'; +import '../models/session.dart'; +import '../utils/browser.dart' as browser; +import 'api_service.dart'; +import 'print_repository.dart'; + +/// Talks to the backend. People sign in with their Microsoft or Google work account +/// (the server does the sign-in and hands back a session token), or with a demo sandbox. +class HttpPrintRepository implements PrintRepository { + HttpPrintRepository({ + ApiService? api, + Uri Function()? location, + void Function(String url)? navigate, + String Function()? takeFragment, + }) : _api = api ?? ApiService(), + _location = location ?? (() => Uri.base), + _navigate = navigate ?? browser.goTo, + _takeFragment = takeFragment ?? browser.takeSignInFragment; + + final ApiService _api; + final Uri Function() _location; + final void Function(String url) _navigate; + final String Function() _takeFragment; + + /// What each reason the server gives for turning someone away means for the person. + static String signInProblem(String? code) => switch (code) { + 'wrong_account' => + 'That account is not allowed here. Sign in with your work account.', + 'unverified_email' => + 'Your email address is not verified, so you cannot sign in with it.', + 'no_identity' => + 'Your account did not tell us who you are. Ask your administrator.', + _ => 'Sign-in did not work. Please try again.', + }; + + @override + Future authConfig() => _api.authConfig(); + + @override + Future signIn({bool asAdmin = false}) => + _api.demoLogin(admin: asAdmin); + + @override + void startWorkspaceSignIn() { + final here = _location(); + final back = '/${here.hasQuery ? '?${here.query}' : ''}'; + _navigate( + '${_api.baseUrl}/auth/login?returnTo=${Uri.encodeQueryComponent(back)}'); + } + + @override + Future resumeSignIn() async { + final fragment = _takeFragment(); + if (fragment.isEmpty) return null; + Map values; + try { + values = Uri.splitQueryString(fragment); + } on FormatException { + return null; + } + final error = values['error']; + if (error != null) throw PrintException(signInProblem(error)); + final token = values['token']; + if (token == null || token.isEmpty) return null; + return _api.me(token); + } + + @override + String? get panelPrinterId { + final id = _location().queryParameters['printer']; + return id == null || id.isEmpty ? null : id; + } + + @override + Future> printers(Session session) => + _api.printers(session.token); + + @override + Future> myHeldJobs(Session session) => + _api.heldJobs(session.token); + + @override + Future myQuota(Session session) => _api.quota(session.token); + + @override + Future> release(Session session, List jobIds, + {String? printerId}) => + _api.release(session.token, jobIds, printerId: printerId); + + @override + Future> allJobs(Session session) => + _api.allJobs(session.token); + + @override + Future> users(Session session) => _api.users(session.token); + + @override + Future setQuota(Session session, String userId, int quota) => + _api.setQuota(session.token, userId, quota); + + @override + Future setup(Session session) => _api.setup(session.token); + + @override + Future setDefaultQuota(Session session, int quota) => + _api.setDefaultQuota(session.token, quota); + + @override + Future setQuotaForAll(Session session, int quota) => + _api.setQuotaForAll(session.token, quota); + + @override + Future addPrinter(Session session, String name, String location) => + _api.addPrinter(session.token, name, location); + + @override + Future updatePrinter(Session session, Printer printer) => + _api.updatePrinter(session.token, printer); + + @override + Future deletePrinter(Session session, String printerId) => + _api.deletePrinter(session.token, printerId); + + @override + void resetDemo() {} + + @override + Future sendSampleDocuments(Session session, {int count = 1}) async { + for (var i = 0; i < count; i++) { + try { + await _api.sendSample(session.token); + } on PrintException { + // The server says when there are no more samples; stop quietly after the first. + if (i == 0) rethrow; + return; + } + } + } +} diff --git a/frontend/lib/services/mock_print_repository.dart b/frontend/lib/services/mock_print_repository.dart new file mode 100644 index 0000000..b71bfa9 --- /dev/null +++ b/frontend/lib/services/mock_print_repository.dart @@ -0,0 +1,285 @@ +import '../models/print_job.dart'; +import '../models/printer.dart'; +import '../models/session.dart'; +import 'print_repository.dart'; + +/// In-memory sample data so the whole app can be tried without a server. +/// State resets when the app restarts. +class MockPrintRepository implements PrintRepository { + MockPrintRepository({ + this.latency = const Duration(milliseconds: 350), + DateTime? now, + }) : _startedAt = now { + resetDemo(); + } + + final Duration latency; + final DateTime? _startedAt; + late List _jobs; + late Map _used; + late Map _total; + late List _printers; + late int _defaultQuota; + + final Map _names = { + 'u1': 'Alice Tan', + 'u2': 'Bob Reyes', + 'u3': 'Priya Nair', + 'u4': 'Marcus Lee', + }; + + @override + void resetDemo() { + final t = _startedAt ?? DateTime.now(); + final yesterday = t.subtract(const Duration(days: 1)); + PrintJob job(String id, String uid, String name, String file, int pages, + DateTime at, String status, + [String? reason]) => + PrintJob( + id: id, + userId: uid, + userName: name, + fileName: file, + pages: pages, + submittedAt: at, + status: status, + failureReason: reason, + ); + _jobs = [ + job('1', 'u1', 'Alice Tan', 'Q3 budget review.pdf', 12, + t.subtract(const Duration(minutes: 20)), 'Held'), + job('2', 'u1', 'Alice Tan', 'Site visit notes.docx', 3, + t.subtract(const Duration(minutes: 40)), 'Held'), + job('3', 'u1', 'Alice Tan', 'Contract draft v4.pdf', 28, yesterday, + 'Held'), + job('4', 'u1', 'Alice Tan', 'Floor plan.png', 1, + yesterday.subtract(const Duration(hours: 1)), 'Held'), + job('5', 'u2', 'Bob Reyes', 'report.docx', 3, + t.subtract(const Duration(minutes: 30)), 'Printed'), + job('6', 'u3', 'Priya Nair', 'Safety audit.pdf', 41, + t.subtract(const Duration(hours: 1)), 'Held'), + job('7', 'u4', 'Marcus Lee', 'Invoice 2291.pdf', 2, yesterday, 'Failed', + 'printer offline'), + ]; + _used = {'u1': 12, 'u2': 50, 'u3': 8, 'u4': 20}; + _total = {'u1': 50, 'u2': 50, 'u3': 200, 'u4': 50}; + _printers = const [ + Printer(id: 'p1', name: 'Level 3 East', location: 'Level 3, east wing'), + Printer(id: 'p2', name: 'Reception', location: 'Ground floor'), + Printer(id: 'p3', name: 'Print room', location: 'Level 1'), + ]; + _defaultQuota = 50; + } + + void _requireAdmin(Session session) { + if (!session.isAdmin) throw const PrintException('Administrators only.'); + } + + @override + Future authConfig() async => AuthConfig.demoOnly; + + @override + void startWorkspaceSignIn() {} + + @override + Future resumeSignIn() async => null; + + @override + String? get panelPrinterId => null; + + @override + Future> printers(Session session) async { + await _wait(); + return session.isAdmin + ? [..._printers] + : _printers.where((p) => p.enabled).toList(); + } + + @override + Future setup(Session session) async { + await _wait(); + _requireAdmin(session); + return SetupInfo( + provider: 'Demo only', + demoEnabled: true, + defaultQuota: _defaultQuota, + people: _names.length, + printers: _printers.length, + redirectUri: 'https://example.com/api/auth/callback', + warnings: const [], + ); + } + + @override + Future setDefaultQuota(Session session, int quota) async { + await _wait(); + _requireAdmin(session); + if (quota < 0) throw const PrintException('Quota cannot be negative.'); + _defaultQuota = quota; + } + + @override + Future setQuotaForAll(Session session, int quota) async { + await _wait(); + _requireAdmin(session); + if (quota < 0) throw const PrintException('Quota cannot be negative.'); + for (final id in _names.keys) { + _total[id] = quota; + } + return _names.length; + } + + @override + Future addPrinter( + Session session, String name, String location) async { + await _wait(); + _requireAdmin(session); + final printer = Printer( + id: 'p${_printers.length + 10}', name: name, location: location); + _printers = [..._printers, printer]; + return printer; + } + + @override + Future updatePrinter(Session session, Printer printer) async { + await _wait(); + _requireAdmin(session); + _printers = [ + for (final p in _printers) p.id == printer.id ? printer : p, + ]; + } + + @override + Future deletePrinter(Session session, String printerId) async { + await _wait(); + _requireAdmin(session); + _printers = _printers.where((p) => p.id != printerId).toList(); + } + + Future _wait() => latency == Duration.zero + ? Future.value() + : Future.delayed(latency); + + @override + Future signIn({bool asAdmin = false}) async { + await _wait(); + return asAdmin + ? const Session( + token: 'demo-admin', + userId: 'admin', + name: 'Administrator', + isAdmin: true) + : const Session(token: 'demo-user', userId: 'u1', name: 'Alice Tan'); + } + + @override + Future> myHeldJobs(Session session) async { + await _wait(); + final mine = _jobs + .where((j) => j.userId == session.userId && j.isHeld) + .toList() + ..sort((a, b) => b.submittedAt.compareTo(a.submittedAt)); + return mine; + } + + @override + Future myQuota(Session session) async { + await _wait(); + return QuotaInfo( + used: _used[session.userId] ?? 0, + total: _total[session.userId] ?? 0, + ); + } + + @override + Future> release(Session session, List jobIds, + {String? printerId}) async { + await _wait(); + if (!_printers + .any((p) => p.enabled && (printerId == null || p.id == printerId))) { + throw const PrintException('That printer is not available.'); + } + final chosen = _jobs + .where((j) => + jobIds.contains(j.id) && j.userId == session.userId && j.isHeld) + .toList(); + if (chosen.isEmpty) throw const PrintException('Nothing to print.'); + final pages = chosen.fold(0, (n, j) => n + j.pages); + final left = (_total[session.userId] ?? 0) - (_used[session.userId] ?? 0); + if (pages > left) throw QuotaExceededException(pages - left); + _used[session.userId] = (_used[session.userId] ?? 0) + pages; + _jobs = [ + for (final j in _jobs) + if (chosen.any((c) => c.id == j.id)) + j.copyWith(status: 'Printed') + else + j, + ]; + return [for (final j in chosen) j.id]; + } + + @override + Future> allJobs(Session session) async { + await _wait(); + if (!session.isAdmin) throw const PrintException('Administrators only.'); + return [..._jobs]..sort((a, b) => b.submittedAt.compareTo(a.submittedAt)); + } + + @override + Future> users(Session session) async { + await _wait(); + if (!session.isAdmin) throw const PrintException('Administrators only.'); + return [ + for (final id in _names.keys) + UserQuota( + userId: id, + name: _names[id]!, + quota: QuotaInfo(used: _used[id] ?? 0, total: _total[id] ?? 0), + ), + ]; + } + + @override + Future sendSampleDocuments(Session session, {int count = 1}) async { + await _wait(); + const samples = [ + ('Meeting agenda.docx', 2), + ('Safety checklist.pdf', 6), + ('Onboarding guide.pdf', 18), + ('Site photo.png', 1), + ]; + final user = _names[session.userId] ?? session.name; + var added = 0; + for (final (file, pages) in samples) { + if (added >= count) break; + final waiting = _jobs.any( + (j) => j.userId == session.userId && j.isHeld && j.fileName == file); + if (waiting) continue; + _jobs = [ + ..._jobs, + PrintJob( + id: 's${_jobs.length + 1}', + userId: session.userId, + userName: user, + fileName: file, + pages: pages, + submittedAt: DateTime.now(), + status: 'Held', + ), + ]; + added++; + } + if (added == 0) { + throw const PrintException( + 'You already have plenty of documents waiting.'); + } + } + + @override + Future setQuota(Session session, String userId, int quota) async { + await _wait(); + if (!session.isAdmin) throw const PrintException('Administrators only.'); + if (quota < 0) throw const PrintException('Quota cannot be negative.'); + _total[userId] = quota; + } +} diff --git a/frontend/lib/services/msal_flutter.dart b/frontend/lib/services/msal_flutter.dart deleted file mode 100644 index d8a42cd..0000000 --- a/frontend/lib/services/msal_flutter.dart +++ /dev/null @@ -1,43 +0,0 @@ -import 'package:msal_flutter/msal_flutter.dart'; - -class MsalService { - late PublicClientApplication _publicClientApplication; - String? _accessToken; - - Future initialize() async { - try { - _publicClientApplication = await PublicClientApplication.createPublicClientApplication( - '880bec29-de8b-49b2-9911-e12da787f3f1 ', // Replace with your client ID - // Replace with your authority and redirect URI - // authority: 'https://login.microsoftonline.com/your-tenant-id', - // redirectUri: 'your-redirect-uri', - authority: 'https://login.microsoftonline.com/common', - redirectUri: 'your-redirect-uri', - ); - } catch (e) { - print('Error initializing MSAL: $e'); - } - } - - Future signIn() async { - try { - // acquireToken now returns a String (access token) - _accessToken = await _publicClientApplication.acquireToken(['user.read']); - print('Access Token: $_accessToken'); - } catch (e) { - print('Error during sign-in: $e'); - } - } - - Future signOut() async { - try { - await _publicClientApplication.logout(); - _accessToken = null; - } catch (e) { - print('Error during sign-out: $e'); - } - } - - String? get accessToken => _accessToken; - String? get clientId => '880bec29-de8b-49b2-9911-e12da787f3f1'; // Replace with your client ID -} diff --git a/frontend/lib/services/print_repository.dart b/frontend/lib/services/print_repository.dart new file mode 100644 index 0000000..577d24f --- /dev/null +++ b/frontend/lib/services/print_repository.dart @@ -0,0 +1,89 @@ +import '../models/print_job.dart'; +import '../models/printer.dart'; +import '../models/session.dart'; + +/// Everything the screens need from the server. The demo implementation keeps +/// data in memory; the HTTP one talks to the backend. +abstract class PrintRepository { + /// How people sign in on this server. Asked before anyone is signed in. + Future authConfig(); + + /// Demo sign-in: a private sandbox with sample documents. + Future signIn({bool asAdmin = false}); + + /// Takes the user to Microsoft or Google to sign in. The browser leaves the app and + /// comes back to the same address, where [resumeSignIn] finishes the job. + void startWorkspaceSignIn(); + + /// Finishes a work-account sign-in when the browser has just come back from it. + /// Returns null when it did not. Throws [PrintException] with a plain reason when + /// the account was turned away. + Future resumeSignIn(); + + /// The printer named in the address (`?printer=`) when this screen is a printer's panel. + String? get panelPrinterId; + + /// Printers people can pick from. Switched-off printers are included only for administrators. + Future> printers(Session session); + + /// The signed-in user's jobs that are waiting to print, newest first. + Future> myHeldJobs(Session session); + + Future myQuota(Session session); + + /// Prints the given jobs and reduces the quota by their page count. Returns the + /// ids that really printed, which can be fewer than were asked for when the + /// printer rejects one. Throws [QuotaExceededException] when they do not fit. + Future> release(Session session, List jobIds, + {String? printerId}); + + Future> allJobs(Session session); + + Future> users(Session session); + + Future setQuota(Session session, String userId, int quota); + + /// How this server is set up and what still needs attention. Administrators only. + Future setup(Session session); + + /// Pages a month that people start with the first time they sign in. + Future setDefaultQuota(Session session, int quota); + + /// Gives everyone the same pages a month. Returns how many people changed. + Future setQuotaForAll(Session session, int quota); + + Future addPrinter(Session session, String name, String location); + + Future updatePrinter(Session session, Printer printer); + + Future deletePrinter(Session session, String printerId); + + /// Demo only: adds up to [count] sample documents to the user's waiting list. + Future sendSampleDocuments(Session session, {int count = 1}); + + /// Demo only: puts the sample data back as it started. Does nothing when the + /// data lives on a server, where signing in again starts a fresh sandbox. + void resetDemo(); +} + +class QuotaExceededException implements Exception { + final int pagesOver; + const QuotaExceededException(this.pagesOver); + + @override + String toString() => 'Over your limit by $pagesOver pages.'; +} + +class PrintException implements Exception { + final String message; + const PrintException(this.message); + + @override + String toString() => message; +} + +/// The token is no longer valid, for example after the demo server restarted. +class SessionExpiredException extends PrintException { + const SessionExpiredException() + : super('Your session has ended. Please sign in again.'); +} diff --git a/frontend/lib/utils/browser.dart b/frontend/lib/utils/browser.dart new file mode 100644 index 0000000..3bb68be --- /dev/null +++ b/frontend/lib/utils/browser.dart @@ -0,0 +1 @@ +export 'browser_stub.dart' if (dart.library.js_interop) 'browser_web.dart'; diff --git a/frontend/lib/utils/browser_stub.dart b/frontend/lib/utils/browser_stub.dart new file mode 100644 index 0000000..7626e7a --- /dev/null +++ b/frontend/lib/utils/browser_stub.dart @@ -0,0 +1,5 @@ +/// Outside a browser there is no page to leave. +void goTo(String url) {} + +/// The sign-in result the page was opened with, once. Empty when there is none. +String takeSignInFragment() => ''; diff --git a/frontend/lib/utils/browser_web.dart b/frontend/lib/utils/browser_web.dart new file mode 100644 index 0000000..59d4a98 --- /dev/null +++ b/frontend/lib/utils/browser_web.dart @@ -0,0 +1,25 @@ +import 'dart:js_interop'; + +extension type _Location._(JSObject _) implements JSObject { + external void assign(String url); +} + +@JS('location') +external _Location get _location; + +@JS('pullPrintHash') +external String? get _hash; + +@JS('pullPrintHash') +external set _hash(String? value); + +/// Leaves the app for [url], for example the Microsoft or Google sign-in page. +void goTo(String url) => _location.assign(url); + +/// The `token=...` or `error=...` the page was opened with after signing in, once. +/// web/index.html moves it out of the address bar before the app starts. +String takeSignInFragment() { + final value = _hash ?? ''; + _hash = null; + return value; +} diff --git a/frontend/lib/utils/constants.dart b/frontend/lib/utils/constants.dart index 2f74a10..dbe8bdc 100644 --- a/frontend/lib/utils/constants.dart +++ b/frontend/lib/utils/constants.dart @@ -1,7 +1,30 @@ +import 'package:flutter/foundation.dart'; + class Constants { - static const String appName = 'Pull Printing App'; - // Point this at your backend when it’s up. For local .NET run, it’s often https://localhost:5001 - static const String apiBaseUrl = 'http://localhost:5000/api'; - // If you later need a default printer for quick release, set it here. - static const String? defaultPrinterId = null; + static const String appName = 'Pull Print'; + + /// Runs the whole app on in-memory sample data, no server needed. This is the + /// default for `flutter run`. Hosted builds pass `--dart-define=USE_MOCK=false`. + static const bool useMockData = + bool.fromEnvironment('USE_MOCK', defaultValue: true); + + /// True while the person is using sample data, so screens explain that nothing is + /// really printed. Set from the server's answer on the sign-in screen and from the + /// kind of session after signing in. + static bool demoMode = useMockData; + + /// Where the API lives. Set with `--dart-define=API_BASE_URL=...`. A web build + /// served by the backend uses its own address, which is what the hosted demo does. + static String get apiBaseUrl { + const configured = String.fromEnvironment('API_BASE_URL'); + if (configured.isNotEmpty) return configured; + return kIsWeb ? '${Uri.base.origin}/api' : 'http://localhost:5000/api'; + } + + /// Seconds before the printer panel signs the user out after printing. + static const int autoSignOutSeconds = 20; + + /// Seconds without a touch before the printer panel signs the user out, so a + /// person who walks away does not leave their documents on screen. + static const int idleSignOutSeconds = 60; } diff --git a/frontend/lib/utils/format.dart b/frontend/lib/utils/format.dart new file mode 100644 index 0000000..ee4045c --- /dev/null +++ b/frontend/lib/utils/format.dart @@ -0,0 +1,33 @@ +import 'package:intl/intl.dart'; +import '../models/print_job.dart'; + +String pagesLabel(int n) => n == 1 ? '1 page' : '$n pages'; + +/// "Today 9:02", "Yesterday" or "3 Oct". +String whenLabel(DateTime at, {DateTime? now}) { + final n = now ?? DateTime.now(); + final today = DateTime(n.year, n.month, n.day); + final day = DateTime(at.year, at.month, at.day); + final diff = today.difference(day).inDays; + if (diff == 0) return 'Today ${DateFormat('H:mm').format(at)}'; + if (diff == 1) return 'Yesterday'; + return DateFormat('d MMM').format(at); +} + +String jobMeta(PrintJob job, {DateTime? now}) => + '${pagesLabel(job.pages)} · ${whenLabel(job.submittedAt.toLocal(), now: now)}'; + +String greeting({DateTime? now}) { + final h = (now ?? DateTime.now()).hour; + if (h < 12) return 'Good morning'; + if (h < 18) return 'Good afternoon'; + return 'Good evening'; +} + +String initials(String name) { + final parts = + name.trim().split(RegExp(r'\s+')).where((p) => p.isNotEmpty).toList(); + if (parts.isEmpty) return '?'; + if (parts.length == 1) return parts.first[0].toUpperCase(); + return (parts.first[0] + parts.last[0]).toUpperCase(); +} diff --git a/frontend/lib/utils/theme.dart b/frontend/lib/utils/theme.dart index 7e9811e..8d3ae57 100644 --- a/frontend/lib/utils/theme.dart +++ b/frontend/lib/utils/theme.dart @@ -1,12 +1,66 @@ import 'package:flutter/material.dart'; +/// Colours from docs/04-design-guidelines.md. +class AppColors { + static const navy = Color(0xFF0E2A47); + static const navyLight = Color(0xFF143A62); + static const navyDeep = Color(0xFF123256); + static const navyChip = Color(0xFF183B63); + static const onNavyMuted = Color(0xFFB9CCE0); + static const ringTrack = Color(0xFF2A5282); + static const ringFill = Color(0xFF6CB4F5); + + static const primary = Color(0xFF0B5CAD); + static const background = Color(0xFFF4F6F8); + static const surface = Colors.white; + static const ink = Color(0xFF16212C); + static const muted = Color(0xFF4A5866); + static const line = Color(0xFFD5DBE1); + static const lineSoft = Color(0xFFE3E8ED); + static const thumbBackground = Color(0xFFEAF0F6); + static const success = Color(0xFF2E9E6B); + + static const pdf = Color(0xFFB3261E); + static const docx = Color(0xFF1F4E9C); + static const image = Color(0xFF0F6B63); + static const otherFile = Color(0xFF4A5866); + + static const waitingBackground = Color(0xFFFFF0D1); + static const waitingText = Color(0xFF6B4200); + static const printedBackground = Color(0xFFE3F1EA); + static const printedText = Color(0xFF14573A); + static const failedBackground = Color(0xFFFBE3E3); + static const failedText = Color(0xFF7A1F1F); +} + class AppTheme { - static final ThemeData lightTheme = ThemeData( - primarySwatch: Colors.blue, - scaffoldBackgroundColor: Colors.grey[100], - appBarTheme: const AppBarTheme( - backgroundColor: Colors.blue, - foregroundColor: Colors.white, - ), - ); + /// Width from which screens switch to the printer-panel layout. + static const double panelBreakpoint = 760; + + static ThemeData build({String? fontFamily}) => ThemeData( + useMaterial3: true, + fontFamily: fontFamily, + colorScheme: ColorScheme.fromSeed( + seedColor: AppColors.primary, + primary: AppColors.primary, + surface: AppColors.surface, + ), + scaffoldBackgroundColor: AppColors.background, + snackBarTheme: + const SnackBarThemeData(behavior: SnackBarBehavior.floating), + inputDecorationTheme: InputDecorationTheme( + isDense: true, + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 14), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: const BorderSide(color: Color(0xFF8A97A4)), + ), + ), + ); + + static final ThemeData light = build(); + + // Kept for code that referenced the old name. + static ThemeData get lightTheme => light; } diff --git a/frontend/lib/widgets/app_button.dart b/frontend/lib/widgets/app_button.dart new file mode 100644 index 0000000..dd91786 --- /dev/null +++ b/frontend/lib/widgets/app_button.dart @@ -0,0 +1,96 @@ +import 'package:flutter/material.dart'; +import '../utils/theme.dart'; + +enum AppButtonStyle { primary, onNavy, light, outline } + +/// Large, high-contrast button. Disabled when [onPressed] is null. +class AppButton extends StatelessWidget { + final String label; + final IconData? icon; + final VoidCallback? onPressed; + final AppButtonStyle style; + final double height; + final double fontSize; + final double radius; + final bool busy; + final bool expand; + + const AppButton({ + super.key, + required this.label, + required this.onPressed, + this.icon, + this.style = AppButtonStyle.primary, + this.height = 56, + this.fontSize = 17, + this.radius = 12, + this.busy = false, + this.expand = true, + }); + + @override + Widget build(BuildContext context) { + final (bg, fg, side) = switch (style) { + AppButtonStyle.primary => ( + AppColors.primary, + Colors.white, + BorderSide.none + ), + AppButtonStyle.onNavy => ( + AppColors.navyChip, + Colors.white, + const BorderSide(color: Color(0xFF3A5F8A)) + ), + AppButtonStyle.light => (Colors.white, AppColors.navy, BorderSide.none), + AppButtonStyle.outline => ( + Colors.white, + AppColors.ink, + const BorderSide(color: AppColors.ink) + ), + }; + final disabled = onPressed == null && !busy; + return FilledButton( + onPressed: busy ? null : onPressed, + style: FilledButton.styleFrom( + backgroundColor: bg, + foregroundColor: fg, + disabledBackgroundColor: busy ? bg : AppColors.lineSoft, + disabledForegroundColor: busy ? fg : AppColors.muted, + minimumSize: Size(expand ? double.infinity : 0, height), + padding: const EdgeInsets.symmetric(horizontal: 24), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(radius), + side: disabled ? BorderSide.none : side, + ), + textStyle: Theme.of(context) + .textTheme + .labelLarge + ?.copyWith(fontSize: fontSize, fontWeight: FontWeight.w700), + ), + child: busy + ? SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator(strokeWidth: 2.5, color: fg), + ) + : Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (icon != null) ...[ + Icon(icon, size: fontSize + 4), + const SizedBox(width: 10) + ], + Flexible( + child: Text( + label, + maxLines: 2, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ); + } +} diff --git a/frontend/lib/widgets/brand_mark.dart b/frontend/lib/widgets/brand_mark.dart new file mode 100644 index 0000000..d88a321 --- /dev/null +++ b/frontend/lib/widgets/brand_mark.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; +import '../utils/theme.dart'; + +/// The Pull Print mark: a page with text lines on the primary blue. +/// Placeholder until the organisation supplies its own logo. +class BrandMark extends StatelessWidget { + final double size; + const BrandMark({super.key, this.size = 36}); + + @override + Widget build(BuildContext context) { + return SizedBox( + width: size, + height: size, + child: CustomPaint(painter: _BrandMarkPainter()), + ); + } +} + +class _BrandMarkPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + canvas.scale(size.width / 36, size.height / 36); + canvas.drawRRect( + RRect.fromRectAndRadius( + const Rect.fromLTWH(0, 0, 36, 36), const Radius.circular(9)), + Paint()..color = AppColors.primary, + ); + const r = Radius.circular(1); + final page = Path() + ..moveTo(11, 8) + ..lineTo(21, 8) + ..lineTo(26, 13) + ..lineTo(26, 27) + ..arcToPoint(const Offset(25, 28), radius: r) + ..lineTo(11, 28) + ..arcToPoint(const Offset(10, 27), radius: r) + ..lineTo(10, 9) + ..arcToPoint(const Offset(11, 8), radius: r) + ..close(); + canvas.drawPath(page, Paint()..color = Colors.white); + final fold = Path() + ..moveTo(21, 8) + ..lineTo(21, 13) + ..lineTo(26, 13) + ..close(); + canvas.drawPath(fold, Paint()..color = const Color(0xFFB9D6F2)); + final line = Paint()..color = AppColors.primary; + for (final l in const [ + Rect.fromLTWH(13, 17, 10, 1.8), + Rect.fromLTWH(13, 21, 10, 1.8), + Rect.fromLTWH(13, 25, 6, 1.8), + ]) { + canvas.drawRRect( + RRect.fromRectAndRadius(l, const Radius.circular(0.9)), line); + } + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/frontend/lib/widgets/demo_banner.dart b/frontend/lib/widgets/demo_banner.dart new file mode 100644 index 0000000..f4dafe8 --- /dev/null +++ b/frontend/lib/widgets/demo_banner.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../screens/login_screen.dart'; +import '../services/print_repository.dart'; +import '../utils/constants.dart'; +import '../utils/theme.dart'; + +/// Wraps a screen so that, in demo mode, a slim banner above it says that the +/// data is sample data and opens "About this demo". Does nothing otherwise. +class DemoShell extends StatelessWidget { + final Widget child; + const DemoShell({super.key, required this.child}); + + @override + Widget build(BuildContext context) { + if (!Constants.demoMode) return child; + return Column( + children: [ + const DemoBanner(), + Expanded( + // The banner already covers the status bar, so the screen below must not pad for it again. + child: MediaQuery.removePadding( + context: context, removeTop: true, child: child), + ), + ], + ); + } +} + +class DemoBanner extends StatelessWidget { + const DemoBanner({super.key}); + + @override + Widget build(BuildContext context) { + return Material( + color: AppColors.waitingBackground, + child: SafeArea( + bottom: false, + child: InkWell( + onTap: () => showDemoInfo(context), + child: Container( + constraints: const BoxConstraints(minHeight: 44), + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), + child: const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.info_outline, + size: 18, color: AppColors.waitingText), + SizedBox(width: 8), + Flexible( + child: Text( + 'Demo: nothing is really printed.', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + color: AppColors.waitingText, + ), + ), + ), + SizedBox(width: 8), + Text( + 'What is this?', + style: TextStyle( + fontSize: 14, + color: AppColors.waitingText, + decoration: TextDecoration.underline, + ), + ), + ], + ), + ), + ), + ), + ); + } +} + +Future showDemoInfo(BuildContext context) { + final points = [ + 'Pull Print keeps your documents on a server until you are standing at a printer. This demo lets you try that.', + 'You get your own sample documents. Other visitors cannot see them.', + 'Print does not use a real printer. It marks your documents as printed and uses up pages from your quota.', + if (Constants.useMockData) + 'Everything resets when you reload the page or restart the app.' + else + 'Everything is deleted after 2 hours without use, and whenever the server restarts.', + 'Run out of documents? Use "Send sample documents" to get more.', + 'To see every job and change page limits, go back to sign-in and choose "Demo: sign in as administrator". You get your own sample people there too.', + ]; + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('About this demo'), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final p in points) + Padding( + padding: const EdgeInsets.only(bottom: 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.only(top: 7, right: 10), + child: SizedBox( + width: 6, + height: 6, + child: DecoratedBox( + decoration: BoxDecoration( + color: AppColors.primary, shape: BoxShape.circle), + ), + ), + ), + Expanded( + child: Text(p, + style: const TextStyle(fontSize: 15, height: 1.4))), + ], + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () { + context.read().resetDemo(); + // Back to sign-in; signing in again starts from fresh sample documents. + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute( + builder: (_) => const LoginScreen( + message: 'Started over with fresh sample documents.'), + ), + (_) => false, + ); + }, + child: const Text('Start over'), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Got it')), + ], + ), + ); +} diff --git a/frontend/lib/widgets/doc_thumbnail.dart b/frontend/lib/widgets/doc_thumbnail.dart new file mode 100644 index 0000000..539764e --- /dev/null +++ b/frontend/lib/widgets/doc_thumbnail.dart @@ -0,0 +1,132 @@ +import 'package:flutter/material.dart'; +import '../utils/theme.dart'; + +/// A drawn preview of a document: a page with a title bar and text lines (or a +/// plan outline for images) and a file-type strip. Replace with a real +/// first-page preview from the server when one exists. +class DocThumbnail extends StatelessWidget { + final String fileName; + final double width; + + const DocThumbnail({super.key, required this.fileName, this.width = 52}); + + static String _ext(String name) { + final dot = name.lastIndexOf('.'); + return dot < 0 ? '' : name.substring(dot + 1).toLowerCase(); + } + + /// Label and colour of the strip for a file name. + static (String, Color) kind(String fileName) { + switch (_ext(fileName)) { + case 'pdf': + return ('PDF', AppColors.pdf); + case 'doc': + case 'docx': + return ('DOCX', AppColors.docx); + case 'png': + case 'jpg': + case 'jpeg': + case 'gif': + return (_ext(fileName).toUpperCase(), AppColors.image); + default: + final e = _ext(fileName); + return (e.isEmpty ? 'FILE' : e.toUpperCase(), AppColors.otherFile); + } + } + + @override + Widget build(BuildContext context) { + final (label, accent) = kind(fileName); + final isImage = accent == AppColors.image; + final s = width / 120; // drawn at 120 x 156, scaled to [width] + const lineColor = Color(0xFFDCE3EA); + + Widget bar(double l, double t, double? r, double h, Color c, {double? w}) => + Positioned( + left: l * s, + top: t * s, + right: r == null ? null : r * s, + width: w == null ? null : w * s, + height: h * s, + child: DecoratedBox( + decoration: BoxDecoration( + color: c, borderRadius: BorderRadius.circular(3 * s)), + ), + ); + + return ExcludeSemantics( + child: Container( + width: width, + height: 156 * s, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + border: width < 80 ? Border.all(color: AppColors.line) : null, + boxShadow: const [ + BoxShadow( + color: Color(0x240E2A47), blurRadius: 6, offset: Offset(0, 2)), + ], + ), + clipBehavior: Clip.antiAlias, + child: Stack( + children: [ + if (!isImage) ...[ + bar(14, 18, null, 10, accent, w: 58), + bar(14, 42, 14, 6, lineColor), + bar(14, 56, 22, 6, lineColor), + bar(14, 70, 14, 6, lineColor), + bar(14, 84, 30, 6, lineColor), + bar(14, 98, 14, 6, lineColor), + ] else ...[ + Positioned( + left: 14 * s, + top: 18 * s, + right: 14 * s, + bottom: 44 * s, + child: DecoratedBox( + decoration: BoxDecoration( + border: Border.all(color: AppColors.muted, width: 3 * s), + ), + ), + ), + Positioned( + left: 58 * s, + top: 18 * s, + width: 3 * s, + height: 48 * s, + child: const ColoredBox(color: AppColors.muted), + ), + Positioned( + left: 14 * s, + top: 62 * s, + width: 44 * s, + height: 3 * s, + child: const ColoredBox(color: AppColors.muted), + ), + ], + Positioned( + left: 0, + right: 0, + bottom: 0, + height: 26 * s, + child: ColoredBox( + color: accent, + child: Center( + child: Text( + label, + style: TextStyle( + color: Colors.white, + fontSize: (12 * s).clamp(7.0, 14.0), + fontWeight: FontWeight.w700, + letterSpacing: 0.8 * s, + ), + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/frontend/lib/widgets/google_logo.dart b/frontend/lib/widgets/google_logo.dart new file mode 100644 index 0000000..e38c104 --- /dev/null +++ b/frontend/lib/widgets/google_logo.dart @@ -0,0 +1,109 @@ +import 'dart:math' as math; +import 'package:flutter/material.dart'; + +/// The four-colour Google "G", drawn from arcs. Swap for Google's own asset +/// before release. +class GoogleLogo extends StatelessWidget { + final double size; + const GoogleLogo({super.key, this.size = 21}); + + @override + Widget build(BuildContext context) => ExcludeSemantics( + child: SizedBox( + width: size, + height: size, + child: CustomPaint(painter: _GPainter()), + ), + ); +} + +class _GPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final w = size.width * 0.2; + final rect = Rect.fromCircle( + center: size.center(Offset.zero), + radius: size.width / 2 - w / 2, + ); + double rad(double deg) => deg * math.pi / 180; + void arc(Color color, double from, double to) => canvas.drawArc( + rect, + rad(from), + rad(to - from), + false, + Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = w, + ); + + // Angles run clockwise from 3 o'clock; the gap on the right is the mouth of the G. + arc(const Color(0xFFEA4335), 215, 315); + arc(const Color(0xFFFBBC05), 135, 215); + arc(const Color(0xFF34A853), 45, 135); + arc(const Color(0xFF4285F4), 0, 45); + canvas.drawRect( + Rect.fromLTWH(size.width / 2, size.height / 2 - w / 2, size.width / 2, w), + Paint()..color = const Color(0xFF4285F4), + ); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} + +/// "Sign in with Google" in Google's sign-in button style. +class GoogleSignInButton extends StatelessWidget { + final VoidCallback? onPressed; + final bool busy; + final double height; + + const GoogleSignInButton({ + super.key, + required this.onPressed, + this.busy = false, + this.height = 56, + }); + + @override + Widget build(BuildContext context) { + const ink = Color(0xFF1F1F1F); + return ConstrainedBox( + constraints: BoxConstraints(minHeight: height, minWidth: double.infinity), + child: OutlinedButton( + onPressed: busy ? null : onPressed, + style: OutlinedButton.styleFrom( + minimumSize: Size(double.infinity, height), + backgroundColor: Colors.white, + foregroundColor: ink, + disabledForegroundColor: ink, + side: const BorderSide(color: Color(0xFF747775)), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), + textStyle: Theme.of(context) + .textTheme + .labelLarge + ?.copyWith(fontSize: 16, fontWeight: FontWeight.w600), + ), + child: busy + ? const SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator(strokeWidth: 2.5, color: ink), + ) + : const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + GoogleLogo(), + SizedBox(width: 12), + Flexible( + child: Text( + 'Sign in with Google', + textAlign: TextAlign.center, + ), + ), + ], + ), + ), + ); + } +} diff --git a/frontend/lib/widgets/job_card.dart b/frontend/lib/widgets/job_card.dart index bec8073..25fb0be 100644 --- a/frontend/lib/widgets/job_card.dart +++ b/frontend/lib/widgets/job_card.dart @@ -1,32 +1,180 @@ import 'package:flutter/material.dart'; import '../models/print_job.dart'; +import '../utils/format.dart'; +import '../utils/theme.dart'; +import 'doc_thumbnail.dart'; +/// A job as a full-width row, for phones. The whole row toggles selection. +class JobTile extends StatelessWidget { + final PrintJob job; + final bool selected; + final ValueChanged onChanged; + + const JobTile({ + super.key, + required this.job, + required this.selected, + required this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return Semantics( + container: true, + child: AnimatedContainer( + duration: const Duration(milliseconds: 150), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: selected ? AppColors.primary : AppColors.lineSoft, + width: 2, + ), + boxShadow: selected + ? const [ + BoxShadow( + color: Color(0x240B5CAD), + blurRadius: 14, + offset: Offset(0, 4)) + ] + : const [], + ), + child: Material( + type: MaterialType.transparency, + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () => onChanged(!selected), + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 10, 14, 10), + child: Row( + children: [ + DocThumbnail(fileName: job.fileName, width: 52), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + job.fileName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 15, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 3), + Text( + jobMeta(job), + style: const TextStyle( + fontSize: 13, color: AppColors.muted), + ), + ], + ), + ), + Transform.scale( + scale: 1.3, + child: Checkbox( + value: selected, + onChanged: (v) => onChanged(v ?? false), + semanticLabel: 'Select ${job.fileName}', + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} + +/// A job as a card with a large preview, for the printer panel. class JobCard extends StatelessWidget { final PrintJob job; - final VoidCallback? onRelease; // null => no actions for users + final bool selected; + final ValueChanged onChanged; const JobCard({ super.key, required this.job, - this.onRelease, + required this.selected, + required this.onChanged, }); @override Widget build(BuildContext context) { - final subtitle = '${job.userName} • ${job.pages} pages • ${job.submittedAt.toLocal()}'; - - return Card( - margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), - child: ListTile( - leading: const Icon(Icons.print), - title: Text(job.fileName, maxLines: 1, overflow: TextOverflow.ellipsis), - subtitle: Text(subtitle), - trailing: onRelease == null - ? const SizedBox.shrink() - : ElevatedButton( - onPressed: onRelease, - child: const Text('Release'), + return AnimatedContainer( + duration: const Duration(milliseconds: 150), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: selected ? AppColors.primary : AppColors.lineSoft, + width: 3, + ), + boxShadow: selected + ? const [ + BoxShadow( + color: Color(0x2E0B5CAD), + blurRadius: 18, + offset: Offset(0, 6)) + ] + : const [], + ), + clipBehavior: Clip.antiAlias, + child: Material( + color: Colors.white, + child: InkWell( + onTap: () => onChanged(!selected), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Stack( + children: [ + Container( + height: 176, + color: AppColors.thumbBackground, + alignment: Alignment.center, + child: DocThumbnail(fileName: job.fileName, width: 120), + ), + Positioned( + right: 8, + top: 8, + child: Transform.scale( + scale: 1.5, + child: Checkbox( + value: selected, + onChanged: (v) => onChanged(v ?? false), + semanticLabel: 'Include ${job.fileName}', + ), + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + job.fileName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 17, fontWeight: FontWeight.w700), + ), + const SizedBox(height: 2), + Text( + jobMeta(job), + style: + const TextStyle(fontSize: 15, color: AppColors.muted), + ), + ], + ), ), + ], + ), + ), ), ); } diff --git a/frontend/lib/widgets/microsoft_logo.dart b/frontend/lib/widgets/microsoft_logo.dart new file mode 100644 index 0000000..a655d58 --- /dev/null +++ b/frontend/lib/widgets/microsoft_logo.dart @@ -0,0 +1,93 @@ +import 'package:flutter/material.dart'; + +/// Microsoft's four-square mark, drawn to its published colours and +/// proportions. Swap for Microsoft's own asset before release. +class MicrosoftLogo extends StatelessWidget { + final double size; + const MicrosoftLogo({super.key, this.size = 21}); + + @override + Widget build(BuildContext context) { + final s = size * 9 / 21; + final gap = size / 21; + Widget sq(Color c) => Container(width: s, height: s, color: c); + return ExcludeSemantics( + child: SizedBox( + width: size, + height: size, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + sq(const Color(0xFFF25022)), + SizedBox(width: gap), + sq(const Color(0xFF7FBA00)), + ]), + SizedBox(height: gap), + Row(mainAxisAlignment: MainAxisAlignment.center, children: [ + sq(const Color(0xFF00A4EF)), + SizedBox(width: gap), + sq(const Color(0xFFFFB900)), + ]), + ], + ), + ), + ); + } +} + +/// "Sign in with Microsoft" in Microsoft's sign-in button style. +class MicrosoftSignInButton extends StatelessWidget { + final VoidCallback? onPressed; + final bool busy; + final double height; + + const MicrosoftSignInButton({ + super.key, + required this.onPressed, + this.busy = false, + this.height = 56, + }); + + @override + Widget build(BuildContext context) { + return ConstrainedBox( + constraints: BoxConstraints(minHeight: height, minWidth: double.infinity), + child: OutlinedButton( + onPressed: busy ? null : onPressed, + style: OutlinedButton.styleFrom( + minimumSize: Size(double.infinity, height), + backgroundColor: Colors.white, + foregroundColor: const Color(0xFF5E5E5E), + disabledForegroundColor: const Color(0xFF5E5E5E), + side: const BorderSide(color: Color(0xFF8C8C8C)), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)), + textStyle: Theme.of(context) + .textTheme + .labelLarge + ?.copyWith(fontSize: 16, fontWeight: FontWeight.w600), + ), + child: busy + ? const SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator( + strokeWidth: 2.5, color: Color(0xFF5E5E5E)), + ) + : const Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + MicrosoftLogo(), + SizedBox(width: 12), + Flexible( + child: Text( + 'Sign in with Microsoft', + textAlign: TextAlign.center, + ), + ), + ], + ), + ), + ); + } +} diff --git a/frontend/lib/widgets/printer_illustration.dart b/frontend/lib/widgets/printer_illustration.dart new file mode 100644 index 0000000..f55adaf --- /dev/null +++ b/frontend/lib/widgets/printer_illustration.dart @@ -0,0 +1,127 @@ +import 'package:flutter/material.dart'; + +/// Flat two-blue printer with a sheet that feeds out of the front slot. +/// Replace with a photo of the real printer once one is available. +class PrinterIllustration extends StatefulWidget { + final double width; + const PrinterIllustration({super.key, this.width = 300}); + + @override + State createState() => _PrinterIllustrationState(); +} + +class _PrinterIllustrationState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, duration: const Duration(milliseconds: 3200)); + bool _started = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final reduce = MediaQuery.maybeOf(context)?.disableAnimations ?? false; + if (reduce) { + _controller.stop(); + _controller.value = 0.6; + _started = false; + } else if (!_started) { + _started = true; + _controller.repeat(); + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Semantics( + image: true, + label: 'Printer with a sheet coming out', + child: ExcludeSemantics( + child: SizedBox( + width: widget.width, + height: widget.width * 230 / 320, + child: AnimatedBuilder( + animation: _controller, + builder: (context, _) => + CustomPaint(painter: _PrinterPainter(_controller.value)), + ), + ), + ), + ); + } +} + +class _PrinterPainter extends CustomPainter { + _PrinterPainter(this.t); + final double t; + + Paint _p(int argb, [double opacity = 1]) => + Paint()..color = Color(argb).withAlpha((opacity * 255).round()); + + void _rr(Canvas c, double x, double y, double w, double h, double r, + Paint p) => + c.drawRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH(x, y, w, h), Radius.circular(r)), + p); + + @override + void paint(Canvas canvas, Size size) { + canvas.scale(size.width / 320, size.height / 230); + + canvas.drawOval( + Rect.fromCenter(center: const Offset(160, 216), width: 264, height: 18), + _p(0xFF000000, .22)); + + canvas.save(); + canvas.translate(160, 52); + canvas.rotate(-4 * 3.1415926535 / 180); + canvas.translate(-160, -52); + _rr(canvas, 92, 16, 136, 72, 4, _p(0xFFDCE6F1)); + canvas.restore(); + + _rr(canvas, 100, 8, 120, 76, 4, _p(0xFFFFFFFF)); + _rr(canvas, 112, 22, 60, 6, 3, _p(0xFFB9C8D8)); + _rr(canvas, 112, 36, 96, 4, 2, _p(0xFFDCE6F1)); + _rr(canvas, 112, 46, 88, 4, 2, _p(0xFFDCE6F1)); + + _rr(canvas, 30, 66, 260, 124, 16, _p(0xFF1F4B7A)); + final top = Path() + ..moveTo(30, 82) + ..arcToPoint(const Offset(46, 66), radius: const Radius.circular(16)) + ..lineTo(274, 66) + ..arcToPoint(const Offset(290, 82), radius: const Radius.circular(16)) + ..lineTo(290, 102) + ..lineTo(30, 102) + ..close(); + canvas.drawPath(top, _p(0xFF2B5F96)); + _rr(canvas, 52, 104, 76, 16, 3, _p(0xFFCFE3F7)); + canvas.drawCircle(const Offset(240, 112), 4.5, _p(0xFF7FD1FF)); + canvas.drawCircle(const Offset(256, 112), 4.5, _p(0xFFFFFFFF, .45)); + _rr(canvas, 62, 128, 196, 10, 5, _p(0xFF0A1E33)); + + // Sheet feeding out of the slot, clipped to the area below it. + final p = (t / 0.55).clamp(0.0, 1.0); + final offset = -46 * (1 - Curves.easeInOut.transform(p)); + canvas.save(); + canvas.clipRect(const Rect.fromLTWH(0, 134, 320, 100)); + canvas.translate(0, offset); + _rr(canvas, 80, 134, 160, 78, 3, _p(0xFFFFFFFF)); + _rr(canvas, 94, 150, 70, 6, 3, _p(0xFFB9C8D8)); + _rr(canvas, 94, 164, 130, 4, 2, _p(0xFFDCE6F1)); + _rr(canvas, 94, 174, 116, 4, 2, _p(0xFFDCE6F1)); + _rr(canvas, 94, 184, 124, 4, 2, _p(0xFFDCE6F1)); + canvas.restore(); + + _rr(canvas, 50, 188, 34, 12, 3, _p(0xFF0A1E33)); + _rr(canvas, 236, 188, 34, 12, 3, _p(0xFF0A1E33)); + } + + @override + bool shouldRepaint(covariant _PrinterPainter old) => old.t != t; +} diff --git a/frontend/lib/widgets/quota_indicator.dart b/frontend/lib/widgets/quota_indicator.dart deleted file mode 100644 index 60f640f..0000000 --- a/frontend/lib/widgets/quota_indicator.dart +++ /dev/null @@ -1,29 +0,0 @@ -import 'package:flutter/material.dart'; - -class QuotaIndicator extends StatelessWidget { - final int total; - final int used; - - const QuotaIndicator({ - super.key, - required this.total, - required this.used, - }); - - @override - Widget build(BuildContext context) { - double progress = total > 0 ? used / total : 0.0; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - LinearProgressIndicator( - value: progress, - backgroundColor: Colors.grey[300], - color: progress > 0.8 ? Colors.red : Colors.green, - ), - const SizedBox(height: 4), - Text("$used / $total pages"), - ], - ); - } -} diff --git a/frontend/lib/widgets/quota_ring.dart b/frontend/lib/widgets/quota_ring.dart new file mode 100644 index 0000000..a066557 --- /dev/null +++ b/frontend/lib/widgets/quota_ring.dart @@ -0,0 +1,88 @@ +import 'dart:math' as math; +import 'package:flutter/material.dart'; +import '../models/session.dart'; +import '../utils/theme.dart'; + +/// Ring showing pages left this month, for use on the navy header. +class QuotaRing extends StatelessWidget { + final QuotaInfo quota; + final double size; + + const QuotaRing({super.key, required this.quota, this.size = 84}); + + @override + Widget build(BuildContext context) { + final fraction = quota.total == 0 ? 0.0 : quota.left / quota.total; + return Semantics( + label: '${quota.left} of ${quota.total} pages left', + child: ExcludeSemantics( + child: SizedBox( + width: size, + height: size, + child: TweenAnimationBuilder( + tween: Tween(begin: 0, end: fraction), + duration: const Duration(milliseconds: 400), + curve: Curves.easeOut, + builder: (context, value, child) => CustomPaint( + painter: _RingPainter(value), + child: child, + ), + child: Center( + child: Padding( + padding: const EdgeInsets.all(14), + child: FittedBox( + fit: BoxFit.scaleDown, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${quota.left}', + style: const TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.w800, + height: 1), + ), + const SizedBox(height: 2), + const Text( + 'pages left', + style: TextStyle( + color: AppColors.onNavyMuted, fontSize: 10), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} + +class _RingPainter extends CustomPainter { + _RingPainter(this.fraction); + final double fraction; + + @override + void paint(Canvas canvas, Size size) { + const stroke = 8.0; + final rect = Rect.fromLTWH( + stroke / 2, stroke / 2, size.width - stroke, size.height - stroke); + final track = Paint() + ..color = AppColors.ringTrack + ..style = PaintingStyle.stroke + ..strokeWidth = stroke; + final fill = Paint() + ..color = AppColors.ringFill + ..style = PaintingStyle.stroke + ..strokeWidth = stroke + ..strokeCap = StrokeCap.round; + canvas.drawArc(rect, 0, math.pi * 2, false, track); + canvas.drawArc(rect, -math.pi / 2, math.pi * 2 * fraction, false, fill); + } + + @override + bool shouldRepaint(covariant _RingPainter old) => old.fraction != fraction; +} diff --git a/pubspec.lock b/pubspec.lock index 6293c6d..e2e5f96 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -109,10 +109,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" checked_yaml: dependency: transitive description: @@ -305,7 +305,7 @@ packages: source: sdk version: "0.0.0" flutter_web_plugins: - dependency: transitive + dependency: "direct main" description: flutter source: sdk version: "0.0.0" @@ -361,10 +361,10 @@ packages: dependency: "direct main" description: name: intl - sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" url: "https://pub.dev" source: hosted - version: "0.20.2" + version: "0.20.3" io: dependency: transitive description: @@ -401,26 +401,26 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0" + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" url: "https://pub.dev" source: hosted - version: "10.0.9" + version: "11.0.2" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" url: "https://pub.dev" source: hosted - version: "3.0.9" + version: "3.0.10" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.2" lints: dependency: transitive description: @@ -441,26 +441,26 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.19.0" mime: dependency: transitive description: @@ -469,14 +469,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" - msal_flutter: - dependency: "direct main" - description: - name: msal_flutter - sha256: "5123bda74d513f44dd6489fe30835a138c40299bdf1e33a00df7007607c09258" - url: "https://pub.dev" - source: hosted - version: "2.0.1" nested: dependency: transitive description: @@ -718,10 +710,10 @@ packages: dependency: transitive description: name: test_api - sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.4" + version: "0.7.12" timing: dependency: transitive description: @@ -742,10 +734,10 @@ packages: dependency: transitive description: name: vector_math - sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.4.3" vm_service: dependency: transitive description: @@ -803,5 +795,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.8.0 <4.0.0" + dart: ">=3.11.0-0 <4.0.0" flutter: ">=3.27.0" diff --git a/pubspec.yaml b/pubspec.yaml index 9d37597..9c85531 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: pull_printing_app -description: A Flutter frontend for pull printing with Azure AD authentication and job release. +description: "Pull printing - send a document, sign in at any printer with your work account, and tap Print." publish_to: 'none' # Since this is internal to your company version: 1.0.0+1 @@ -10,15 +10,14 @@ environment: dependencies: flutter: sdk: flutter + flutter_web_plugins: + sdk: flutter # Networking & state management http: ^1.2.0 dio: ^5.1.1 provider: ^6.1.2 - # Azure AD authentication - msal_flutter: ^2.0.1 - # Data & storage json_annotation: ^4.9.0 shared_preferences: ^2.0.13 diff --git a/pull_printing_app.sln b/pull_printing_app.sln index fdf0f16..93c8a37 100644 --- a/pull_printing_app.sln +++ b/pull_printing_app.sln @@ -1,9 +1,11 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.5.2.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PullPrintingBackend", "backend\PullPrintingBackend.csproj", "{C93FB1CB-51B9-151E-9131-1FCFAF9CF417}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PullPrintingBackend.Tests", "backend.Tests\PullPrintingBackend.Tests.csproj", "{78D927CB-F498-4408-BB67-48B0D73BCF3E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -14,6 +16,10 @@ Global {C93FB1CB-51B9-151E-9131-1FCFAF9CF417}.Debug|Any CPU.Build.0 = Debug|Any CPU {C93FB1CB-51B9-151E-9131-1FCFAF9CF417}.Release|Any CPU.ActiveCfg = Release|Any CPU {C93FB1CB-51B9-151E-9131-1FCFAF9CF417}.Release|Any CPU.Build.0 = Release|Any CPU + {78D927CB-F498-4408-BB67-48B0D73BCF3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {78D927CB-F498-4408-BB67-48B0D73BCF3E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {78D927CB-F498-4408-BB67-48B0D73BCF3E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {78D927CB-F498-4408-BB67-48B0D73BCF3E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/render.yaml b/render.yaml new file mode 100644 index 0000000..ad75c3c --- /dev/null +++ b/render.yaml @@ -0,0 +1,13 @@ +# Render Blueprint: deploys the demo on Render's free plan. +# In Render: New > Blueprint > pick this repository. +services: + - type: web + name: pull-print-demo + runtime: docker + plan: free + healthCheckPath: /healthz + autoDeploy: true + envVars: + # Keeps visitors signed in across restarts. + - key: Auth__SigningKey + generateValue: true diff --git a/scripts/vercel-build.sh b/scripts/vercel-build.sh new file mode 100755 index 0000000..e174c58 --- /dev/null +++ b/scripts/vercel-build.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Builds the demo-mode web app for static hosting on Vercel. No server is needed: +# in this mode the app runs on built-in sample data inside the visitor's browser. +set -euo pipefail + +FLUTTER_DIR="${FLUTTER_DIR:-$HOME/flutter}" + +if [ ! -x "$FLUTTER_DIR/bin/flutter" ]; then + git clone --depth 1 --branch stable https://github.com/flutter/flutter.git "$FLUTTER_DIR" +fi +# Flutter unpacks its Dart SDK with unzip. +if ! command -v unzip >/dev/null 2>&1; then + (dnf install -y unzip || yum install -y unzip || apt-get install -y unzip) >/dev/null 2>&1 || true +fi + +export PATH="$FLUTTER_DIR/bin:$PATH" +export FLUTTER_SUPPRESS_ANALYTICS=true +git config --global --add safe.directory "$FLUTTER_DIR" || true + +flutter --version +flutter pub get +flutter build web -t frontend/lib/main.dart --release --no-web-resources-cdn --dart-define=USE_MOCK=true diff --git a/test/api_service_test.dart b/test/api_service_test.dart new file mode 100644 index 0000000..80b7bec --- /dev/null +++ b/test/api_service_test.dart @@ -0,0 +1,165 @@ +// ignore_for_file: avoid_relative_lib_imports +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; + +import '../frontend/lib/services/api_service.dart'; +import '../frontend/lib/services/print_repository.dart'; + +/// Builds an [ApiService] whose server is [handler], and records what was asked. +class _Server { + _Server(this.handler); + final http.Response Function(http.Request request) handler; + final requests = []; + + ApiService get api => ApiService( + baseUrl: 'https://demo.example/api', + client: MockClient((request) async { + requests.add(request); + return handler(request); + }), + ); +} + +http.Response _json(Object body, [int status = 200]) => http.Response( + jsonEncode(body), + status, + headers: {'content-type': 'application/json'}, + ); + +void main() { + test('demo sign-in sends the admin flag and reads the session from the reply', + () async { + final server = _Server((r) => _json({ + 'token': 't0k3n', + 'userId': 'demo-1', + 'name': 'Alice Tan', + 'isAdmin': false, + })); + + final session = await server.api.demoLogin(admin: true); + + expect(server.requests.single.url.toString(), + 'https://demo.example/api/auth/demo-login'); + expect(jsonDecode(server.requests.single.body), {'admin': true}); + expect(session.token, 't0k3n'); + expect(session.name, 'Alice Tan'); + expect(session.isAdmin, isFalse); + }); + + test( + 'held jobs are read from the server\'s JSON, including the offset in the date', + () async { + final server = _Server((r) => _json([ + { + 'id': 'a1', + 'userId': 'demo-1', + 'userName': 'Alice Tan', + 'fileName': 'Q3 budget review.pdf', + 'pages': 12, + 'submittedAt': '2026-10-22T09:00:00+00:00', + 'status': 'Held', + 'failureReason': null, + } + ])); + + final jobs = await server.api.heldJobs('tok'); + + expect(server.requests.single.headers['Authorization'], 'Bearer tok'); + expect(jobs.single.fileName, 'Q3 budget review.pdf'); + expect(jobs.single.pages, 12); + expect(jobs.single.isHeld, isTrue); + expect(jobs.single.submittedAt.toUtc(), DateTime.utc(2026, 10, 22, 9)); + }); + + test('quota and user list parse the server\'s shape', () async { + final quota = + await _Server((r) => _json({'used': 12, 'total': 50, 'left': 38})) + .api + .quota('tok'); + expect((quota.used, quota.total, quota.left), (12, 50, 38)); + + final users = await _Server((r) => _json([ + { + 'userId': 'u2', + 'name': 'Bob Reyes', + 'quota': {'used': 50, 'total': 50, 'left': 0}, + } + ])).api.users('tok'); + expect(users.single.name, 'Bob Reyes'); + expect(users.single.quota.left, 0); + }); + + test('printing posts the chosen ids', () async { + final server = _Server((r) => _json({ + 'printed': ['a1'], + 'pages': 12 + })); + await server.api.release('tok', ['a1', 'b2']); + expect(server.requests.single.url.path, '/api/jobs/release'); + expect(jsonDecode(server.requests.single.body), { + 'jobIds': ['a1', 'b2'] + }); + }); + + test('a 409 quota_exceeded becomes QuotaExceededException with the shortfall', + () async { + final server = _Server((r) => _json({ + 'error': 'quota_exceeded', + 'message': 'Over your limit by 6 pages.', + 'pagesOver': 6, + }, 409)); + await expectLater( + server.api.release('tok', ['a1']), + throwsA(isA() + .having((e) => e.pagesOver, 'pagesOver', 6)), + ); + }); + + test('a 401 becomes SessionExpiredException', () async { + final server = _Server((r) => http.Response('', 401)); + await expectLater( + server.api.heldJobs('old'), throwsA(isA())); + }); + + test('the server\'s own message is passed on for other errors', () async { + final server = _Server((r) => _json({ + 'error': 'bad_request', + 'message': 'Quota must be between 0 and 10000 pages.' + }, 400)); + await expectLater( + server.api.setQuota('tok', 'u1', -5), + throwsA(isA().having( + (e) => e.message, 'message', contains('between 0 and 10000'))), + ); + }); + + test('a 403 and an unexpected 500 give plain messages', () async { + await expectLater( + _Server((r) => http.Response('', 403)).api.allJobs('tok'), + throwsA(isA() + .having((e) => e.message, 'message', contains('permission'))), + ); + await expectLater( + _Server((r) => http.Response('oops', 500)) + .api + .allJobs('tok'), + throwsA(isA() + .having((e) => e.message, 'message', contains('500'))), + ); + }); + + test('a network failure says the server cannot be reached', () async { + final api = ApiService( + baseUrl: 'https://demo.example/api', + client: MockClient((r) async => throw http.ClientException('offline')), + ); + await expectLater( + api.heldJobs('tok'), + throwsA(isA() + .having((e) => e.message, 'message', contains('Cannot reach'))), + ); + }); +} diff --git a/test/test_fonts.dart b/test/test_fonts.dart new file mode 100644 index 0000000..21ef0b2 --- /dev/null +++ b/test/test_fonts.dart @@ -0,0 +1,32 @@ +import 'dart:io'; +import 'package:flutter/services.dart'; + +/// Flutter tests draw text with a placeholder font whose letters are far wider +/// than any real font, which produces false overflow errors. Load Roboto and +/// the Material icons from the SDK so layout is checked with realistic widths. +/// Does nothing when the SDK fonts cannot be found. +Future loadTestFonts() async { + final root = Platform.environment['FLUTTER_ROOT']; + if (root == null) return; + final dir = '$root/bin/cache/artifacts/material_fonts'; + + Future load(String family, Map files) async { + final loader = FontLoader(family); + var any = false; + for (final name in files.keys) { + final f = File('$dir/$name'); + if (!f.existsSync()) continue; + any = true; + loader.addFont(Future.value(ByteData.sublistView(f.readAsBytesSync()))); + } + if (any) await loader.load(); + } + + await load('Roboto', { + 'Roboto-Regular.ttf': 400, + 'Roboto-Medium.ttf': 500, + 'Roboto-Bold.ttf': 700, + 'Roboto-Black.ttf': 900, + }); + await load('MaterialIcons', {'MaterialIcons-Regular.otf': 400}); +} diff --git a/test/widget_test.dart b/test/widget_test.dart index f9c092d..e2e9024 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -1,30 +1,586 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - +// ignore_for_file: avoid_relative_lib_imports import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../frontend/lib/main.dart'; +import '../frontend/lib/models/print_job.dart'; +import '../frontend/lib/models/session.dart'; +import '../frontend/lib/services/mock_print_repository.dart'; +import '../frontend/lib/services/print_repository.dart'; +import '../frontend/lib/utils/format.dart'; +import 'test_fonts.dart'; + +MockPrintRepository _repo() => MockPrintRepository(latency: Duration.zero); + +/// The printer illustration animates forever, so pumpAndSettle would time out. +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 120)); + } +} + +Future _openApp(WidgetTester tester, Size size, + {MockPrintRepository? repo}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + PullPrintingApp(repository: repo ?? _repo(), fontFamily: 'Roboto')); + await _settle(tester); +} + +Future _signIn(WidgetTester tester) async { + await tester.tap(find.text('Sign in with Microsoft')); + await _settle(tester); +} + +/// Signs in fine, then the server rejects the token, as after a restart. +class _ExpiredAfterSignIn extends MockPrintRepository { + _ExpiredAfterSignIn() : super(latency: Duration.zero); + + @override + Future> myHeldJobs(Session session) async => + throw const SessionExpiredException(); +} + +/// Prints only the first document that was asked for, as when the printer rejects the rest. +class _PartialRepo extends MockPrintRepository { + _PartialRepo() : super(latency: Duration.zero); + + @override + Future> release(Session session, List jobIds, + {String? printerId}) => + super.release(session, [jobIds.first], printerId: printerId); +} + +/// The printer rejects everything. +class _NothingPrintsRepo extends MockPrintRepository { + _NothingPrintsRepo() : super(latency: Duration.zero); + + @override + Future> release(Session session, List jobIds, + {String? printerId}) async => + []; +} + +/// The list on screen is out of date, so the server says the documents are not waiting. +class _StaleListRepo extends MockPrintRepository { + _StaleListRepo() : super(latency: Duration.zero); + + @override + Future> release(Session session, List jobIds, + {String? printerId}) async => + throw const PrintException('Those documents are not waiting to print.'); +} + +Future _withQuota(int total) async { + final repo = _repo(); + await repo.setQuota( + const Session(token: 't', userId: 'admin', name: 'A', isAdmin: true), + 'u1', + total); + return repo; +} void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const PullPrintingApp()); + setUpAll(loadTestFonts); + + const phone = Size(390, 844); + const panel = Size(1024, 600); + + group('phone', () { + testWidgets( + 'sign-in shows only the user\'s own documents, ticked to fit quota', + (tester) async { + await _openApp(tester, phone); + expect(find.text('Print now.\nCollect at any printer.'), findsOneWidget); + + await _signIn(tester); + + expect(find.text('Alice Tan'), findsOneWidget); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + expect(find.text('Site visit notes.docx'), findsOneWidget); + expect(find.text('Contract draft v4.pdf'), findsOneWidget); + expect(find.text('Floor plan.png'), findsOneWidget); + // Other people's files must never appear. + expect(find.text('Safety audit.pdf'), findsNothing); + expect(find.text('report.docx'), findsNothing); + + expect(find.text('Print 2 documents · 15 pages'), findsOneWidget); + expect(find.text('38'), findsOneWidget); // pages-left ring + }); + + testWidgets('going over quota disables Print and says by how much', + (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + + await tester.tap(find.text('Contract draft v4.pdf')); + await tester.pump(const Duration(milliseconds: 200)); + + final blocked = find.text('Over your limit by 5 pages. Untick one.'); + expect(blocked, findsOneWidget); + expect( + tester + .widget(find.ancestor( + of: blocked, matching: find.byType(FilledButton))) + .onPressed, + isNull); + + await tester.tap(find.text('Contract draft v4.pdf')); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.text('Print 2 documents · 15 pages'), findsOneWidget); + }); + + testWidgets('unticking everything disables Print', (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + + await tester.tap(find.text('Q3 budget review.pdf')); + await tester.tap(find.text('Site visit notes.docx')); + await tester.pump(const Duration(milliseconds: 200)); + + final blocked = find.text('Select a document to print'); + expect(blocked, findsOneWidget); + expect( + tester + .widget(find.ancestor( + of: blocked, matching: find.byType(FilledButton))) + .onPressed, + isNull); + }); + + testWidgets('printing confirms, reduces quota and removes the printed jobs', + (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + + await tester.tap(find.text('Print 2 documents · 15 pages')); + await _settle(tester); + + expect(find.text('Printing at Level 3 East'), findsOneWidget); + expect(find.text('23 of 50'), findsOneWidget); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + + await tester.tap(find.text('Back to my documents')); + await _settle(tester); + + expect(find.text('Q3 budget review.pdf'), findsNothing); + expect(find.text('Site visit notes.docx'), findsNothing); + expect(find.text('Contract draft v4.pdf'), findsOneWidget); + expect(find.text('23'), findsOneWidget); // ring now shows 23 left + }); + + testWidgets('signing out returns to the sign-in screen', (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + await tester.tap(find.byTooltip('Sign out')); + await _settle(tester); + expect(find.text('Sign in with Microsoft'), findsOneWidget); + }); + + testWidgets('empty state when nothing is waiting', (tester) async { + final repo = _repo(); + await repo.release( + const Session(token: 't', userId: 'u1', name: 'Alice Tan'), + ['1', '2']); + await repo.setQuota( + const Session(token: 't', userId: 'admin', name: 'A', isAdmin: true), + 'u1', + 500); + await repo.release( + const Session(token: 't', userId: 'u1', name: 'Alice Tan'), + ['3', '4']); + await _openApp(tester, phone, repo: repo); + await _signIn(tester); + expect(find.text('Nothing waiting to print.'), findsOneWidget); + }); + }); + + group('demo', () { + testWidgets('the banner explains the demo and its dialog can be opened', + (tester) async { + await _openApp(tester, phone); + expect(find.text('Demo: nothing is really printed.'), findsOneWidget); + + await tester.tap(find.text('What is this?')); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.textContaining('Print does not use a real printer'), + findsOneWidget); + expect(find.textContaining('Other visitors cannot see them'), + findsOneWidget); + + await tester.tap(find.text('Got it')); + await tester.pump(const Duration(milliseconds: 400)); + expect(find.textContaining('Print does not use a real printer'), + findsNothing); + }); + + testWidgets( + 'an empty list offers sample documents, and sending them fills it', + (tester) async { + final repo = _repo(); + const alice = Session(token: 't', userId: 'u1', name: 'Alice Tan'); + await repo.setQuota( + const Session(token: 't', userId: 'admin', name: 'A', isAdmin: true), + 'u1', + 500); + await repo.release(alice, ['1', '2', '3', '4']); + + await _openApp(tester, phone, repo: repo); + await _signIn(tester); + expect(find.text('Nothing waiting to print.'), findsOneWidget); + + await tester.tap(find.text('Send sample documents')); + await _settle(tester); + + expect(find.text('Nothing waiting to print.'), findsNothing); + expect(find.text('Meeting agenda.docx'), findsOneWidget); + expect(find.text('Safety checklist.pdf'), findsOneWidget); + }); + + testWidgets('"Send another sample document" adds one to a non-empty list', + (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + expect(find.text('Meeting agenda.docx'), findsNothing); + + await tester.tap(find.text('Send another sample document')); + await _settle(tester); + + expect(find.text('Meeting agenda.docx'), findsOneWidget); + }); - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); + testWidgets( + 'a session that has ended sends the user back to sign-in with a message', + (tester) async { + await _openApp(tester, phone, repo: _ExpiredAfterSignIn()); + await _signIn(tester); + + expect(find.text('Sign in with Microsoft'), findsOneWidget); + expect(find.text('Your session has ended. Please sign in again.'), + findsOneWidget); + }); + }); + + group('small screens', () { + testWidgets('a 360 x 640 phone shows every screen without overflow', + (tester) async { + await _openApp(tester, const Size(360, 640)); + await _signIn(tester); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + await tester.tap(find.textContaining('Print 2 documents')); + await _settle(tester); + expect(find.text('Back to my documents'), findsOneWidget); + }); + }); + + group('mistakes people make', () { + testWidgets('Select all and Clear change every document at once', + (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + expect(find.text('Print 2 documents · 15 pages'), findsOneWidget); + + await tester.tap(find.text('Select all')); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.text('Over your limit by 6 pages. Untick one.'), + findsOneWidget); // 44 pages, 38 left + + await tester.tap(find.text('Clear')); // the button now unticks everything + await tester.pump(const Duration(milliseconds: 200)); + expect(find.text('Select a document to print'), findsOneWidget); + }); + + testWidgets('one long document says what it needs and what is left', + (tester) async { + await _openApp(tester, phone, repo: await _withQuota(20)); // 8 pages left + await _signIn(tester); + expect(find.text('Select a document to print'), + findsOneWidget); // nothing fits, so nothing is ticked + + await tester.tap(find.text('Contract draft v4.pdf')); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.text('This document needs 28 pages. You have 8 left.'), + findsOneWidget); + expect(find.textContaining('Demo tip'), findsOneWidget); + }); + + testWidgets('no pages left is said plainly', (tester) async { + await _openApp(tester, phone, repo: await _withQuota(12)); // 0 left + await _signIn(tester); + await tester.tap(find.text('Floor plan.png')); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.text('No pages left this month.'), findsOneWidget); + }); + + testWidgets( + 'when only some documents print, the rest are named as still waiting', + (tester) async { + await _openApp(tester, phone, repo: _PartialRepo()); + await _signIn(tester); + await tester.tap(find.text('Print 2 documents · 15 pages')); + await _settle(tester); + + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + expect(find.text('Site visit notes.docx'), findsNothing); + expect(find.text('1 document could not be printed and is still waiting.'), + findsOneWidget); + expect(find.text('26 of 50'), + findsOneWidget); // only the 12 printed pages were used + }); + + testWidgets( + 'if nothing prints the person stays on their list with a message', + (tester) async { + await _openApp(tester, phone, repo: _NothingPrintsRepo()); + await _signIn(tester); + await tester.tap(find.text('Print 2 documents · 15 pages')); + await _settle(tester); + + expect(find.textContaining('The printer could not print your documents'), + findsOneWidget); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + expect(find.text('Print 2 documents · 15 pages'), findsOneWidget); + }); + + testWidgets( + 'an out-of-date list is refreshed when the server says the documents are gone', + (tester) async { + await _openApp(tester, phone, repo: _StaleListRepo()); + await _signIn(tester); + await tester.tap(find.text('Print 2 documents · 15 pages')); + await _settle(tester); + + expect( + find.textContaining('Your list has been refreshed.'), findsOneWidget); + }); + + testWidgets( + 'Start over gives fresh sample documents after everything was printed', + (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + await tester.tap(find.text('Print 2 documents · 15 pages')); + await _settle(tester); + await tester.tap(find.text('Back to my documents')); + await _settle(tester); + expect(find.text('Q3 budget review.pdf'), findsNothing); + + await tester.tap(find.text('What is this?')); + await tester.pump(const Duration(milliseconds: 400)); + await tester.tap(find.text('Start over')); + await _settle(tester); + expect(find.text('Started over with fresh sample documents.'), + findsOneWidget); + + await _signIn(tester); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + expect(find.text('Print 2 documents · 15 pages'), findsOneWidget); + }); + + testWidgets('the printer panel signs out someone who walks away', + (tester) async { + await _openApp(tester, panel); + await _signIn(tester); + expect(find.text('Your documents'), findsOneWidget); + + await tester.pump(const Duration(seconds: 61)); + await _settle(tester); + expect(find.text('Sign in to collect your prints'), findsOneWidget); + expect(find.text('You were signed out because the screen was idle.'), + findsOneWidget); + }); + + testWidgets('touching the printer panel keeps the person signed in', + (tester) async { + await _openApp(tester, panel); + await _signIn(tester); + + await tester.pump(const Duration(seconds: 45)); + await tester.tap( + find.text('Contract draft v4.pdf')); // a touch restarts the countdown + await tester.pump(const Duration(seconds: 45)); + expect(find.text('Your documents'), findsOneWidget); + + await tester.pump(const Duration(seconds: 20)); + await _settle(tester); + expect(find.text('Sign in to collect your prints'), findsOneWidget); + }); + + testWidgets('a phone does not sign anyone out for being idle', + (tester) async { + await _openApp(tester, phone); + await _signIn(tester); + await tester.pump(const Duration(seconds: 120)); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + }); + }); + + group('large text and small screens', () { + for (final scale in [1.5, 2.0]) { + testWidgets('every phone screen copes with text at ${scale}x', + (tester) async { + tester.platformDispatcher.textScaleFactorTestValue = scale; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + await _openApp(tester, phone); + expect(find.textContaining('Collect at any printer'), findsOneWidget); + await _signIn(tester); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + + await tester.tap(find.textContaining('Print 2 documents')); + await _settle(tester); + expect(find.text('Back to my documents'), findsOneWidget); + }); + } + + testWidgets('the printer panel copes with larger text', (tester) async { + tester.platformDispatcher.textScaleFactorTestValue = 1.3; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + await _openApp(tester, panel); + await _signIn(tester); + expect(find.text('Your documents'), findsOneWidget); + await tester.tap(find.text('Print')); + await _settle(tester); + expect(find.textContaining('Printing 15 pages'), findsOneWidget); + }); + + testWidgets('the admin screen works on a phone', (tester) async { + await _openApp(tester, phone); + await tester.tap(find.text('Demo: sign in as administrator')); + await _settle(tester); + expect(find.text('Pull Print Admin'), findsOneWidget); + expect(find.text('All jobs'), findsOneWidget); + }); + }); + + group('printer panel', () { + testWidgets('sign in, print, then sign out automatically', (tester) async { + await _openApp(tester, panel); + expect(find.text('Sign in to collect your prints'), findsOneWidget); + + await _signIn(tester); + expect(find.text('Your documents'), findsOneWidget); + expect(find.text('2 documents · 15 pages'), findsOneWidget); + expect(find.text('23 pages left after printing'), findsOneWidget); + + await tester.tap(find.text('Print')); + await _settle(tester); + expect(find.text('Printing 15 pages'), findsOneWidget); + + await tester.pump(const Duration(seconds: 21)); + await _settle(tester); + expect(find.text('Sign in to collect your prints'), findsOneWidget); + }); + + testWidgets('over quota shows the shortfall and blocks Print', + (tester) async { + await _openApp(tester, panel); + await _signIn(tester); + await tester.tap(find.text('Contract draft v4.pdf')); + await tester.pump(const Duration(milliseconds: 200)); + expect( + find.text('Over your limit by 5 pages. Untick one.'), findsOneWidget); + expect(find.text('Over your limit'), findsOneWidget); + }); + }); + + group('admin', () { + testWidgets('lists jobs, filters, and saves a quota', (tester) async { + final repo = _repo(); + await _openApp(tester, const Size(1280, 1000), repo: repo); + await tester.tap(find.text('Demo: sign in as administrator')); + await _settle(tester); + + expect(find.text('Pull Print Admin'), findsOneWidget); + expect(find.text('Safety audit.pdf'), findsOneWidget); + expect(find.text('Failed: printer offline'), findsOneWidget); + expect(find.text('Waiting to print'), findsOneWidget); + + await tester + .ensureVisible(find.widgetWithText(TextField, 'Search user or file')); + await tester.enterText( + find.widgetWithText(TextField, 'Search user or file'), 'priya'); + await tester.pump(); + expect(find.text('Safety audit.pdf'), findsOneWidget); + expect(find.text('Q3 budget review.pdf'), findsNothing); + + await tester.enterText( + find.widgetWithText(TextField, 'Search user or file'), 'zzz'); + await tester.pump(); + expect(find.text('No jobs match.'), findsOneWidget); + await tester.ensureVisible(find.text('Clear filters')); + await tester.tap(find.text('Clear filters')); + await tester.pump(); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + + // Bob is out of quota; give him 80 pages. + final bobField = find.widgetWithText(TextField, 'Pages per month').at(3); + await tester.ensureVisible(bobField); + await tester.enterText(bobField, '80'); + await tester.tap(find.text('Save').at(2)); + await _settle(tester); + expect(find.text('Quota for Bob Reyes set to 80 pages.'), findsOneWidget); + + final bob = (await repo.users(const Session( + token: 't', userId: 'admin', name: 'A', isAdmin: true))) + .firstWhere((u) => u.userId == 'u2'); + expect(bob.quota.total, 80); + }); + }); + + group('repository', () { + const alice = Session(token: 't', userId: 'u1', name: 'Alice Tan'); + const admin = + Session(token: 't', userId: 'admin', name: 'A', isAdmin: true); + + test('release rejects jobs that do not fit the quota and changes nothing', + () async { + final repo = _repo(); + expect( + () => repo.release(alice, ['1', '2', '3']), // 43 pages, 38 left + throwsA(isA() + .having((e) => e.pagesOver, 'over', 5)), + ); + expect((await repo.myHeldJobs(alice)).length, 4); + expect((await repo.myQuota(alice)).used, 12); + }); + + test('release marks jobs printed and uses up pages', () async { + final repo = _repo(); + await repo.release(alice, ['1', '2']); + expect((await repo.myHeldJobs(alice)).map((j) => j.id), ['3', '4']); + expect((await repo.myQuota(alice)).left, 23); + }); + + test('a user cannot release someone else\'s job', () async { + final repo = _repo(); + expect(() => repo.release(alice, ['6']), throwsA(isA())); + }); + + test('admin endpoints refuse non-admins', () async { + final repo = _repo(); + expect(() => repo.allJobs(alice), throwsA(isA())); + expect(() => repo.setQuota(alice, 'u1', 999), + throwsA(isA())); + expect((await repo.allJobs(admin)).length, 7); + }); + }); - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); + group('format', () { + test('whenLabel', () { + final now = DateTime(2026, 10, 22, 12); + expect(whenLabel(DateTime(2026, 10, 22, 9, 2), now: now), 'Today 9:02'); + expect(whenLabel(DateTime(2026, 10, 21, 23), now: now), 'Yesterday'); + expect(whenLabel(DateTime(2026, 10, 3), now: now), '3 Oct'); + }); - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); + test('initials and greeting', () { + expect(initials('Alice Tan'), 'AT'); + expect(initials('Madonna'), 'M'); + expect(greeting(now: DateTime(2026, 1, 1, 8)), 'Good morning'); + expect(greeting(now: DateTime(2026, 1, 1, 20)), 'Good evening'); + }); }); } diff --git a/test/workspace_test.dart b/test/workspace_test.dart new file mode 100644 index 0000000..6eeb0b7 --- /dev/null +++ b/test/workspace_test.dart @@ -0,0 +1,445 @@ +// ignore_for_file: avoid_relative_lib_imports +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; + +import '../frontend/lib/main.dart'; +import '../frontend/lib/models/printer.dart'; +import '../frontend/lib/models/session.dart'; +import '../frontend/lib/services/api_service.dart'; +import '../frontend/lib/services/http_print_repository.dart'; +import '../frontend/lib/services/mock_print_repository.dart'; +import '../frontend/lib/services/print_repository.dart'; +import '../frontend/lib/utils/constants.dart'; +import 'test_fonts.dart'; + +/// A server that signs people in with a work account, as when Microsoft or Google is set up. +class _WorkspaceRepo extends MockPrintRepository { + _WorkspaceRepo({this.config, this.comeBack, this.turnedAway}) + : super(latency: Duration.zero); + + final AuthConfig? config; + + /// The session the browser returns with, as after signing in at Microsoft or Google. + final Session? comeBack; + final String? turnedAway; + int workspaceSignIns = 0; + final released = []; + + @override + Future authConfig() async => + config ?? + const AuthConfig(provider: 'google', domain: 'example.com', demo: false); + + @override + void startWorkspaceSignIn() => workspaceSignIns++; + + @override + Future resumeSignIn() async { + if (turnedAway != null) throw PrintException(turnedAway!); + return comeBack; + } + + @override + Future> release(Session session, List jobIds, + {String? printerId}) { + released.add(printerId); + return super.release(session, jobIds, printerId: printerId); + } +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 120)); + } +} + +Future _open(WidgetTester tester, Size size, PrintRepository repo) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester + .pumpWidget(PullPrintingApp(repository: repo, fontFamily: 'Roboto')); + await _settle(tester); +} + +const _admin = Session( + token: 't', userId: 'admin', name: 'Admin', isAdmin: true, demo: false); + +void main() { + setUpAll(loadTestFonts); + const phone = Size(390, 844); + + group('sign-in options', () { + testWidgets('a Google workspace offers Google and no demo', (tester) async { + final repo = _WorkspaceRepo(); + await _open(tester, phone, repo); + + expect(find.text('Sign in with Google'), findsOneWidget); + expect(find.text('Sign in with Microsoft'), findsNothing); + expect(find.textContaining('@example.com'), findsOneWidget); + expect(find.text('Demo: sign in as administrator'), findsNothing); + expect(find.text('Demo: nothing is really printed.'), findsNothing); + + await tester.tap(find.text('Sign in with Google')); + await tester.pump(); + expect(repo.workspaceSignIns, 1); + }); + + testWidgets('a Microsoft workspace offers Microsoft', (tester) async { + final repo = _WorkspaceRepo( + config: const AuthConfig(provider: 'microsoft', demo: false)); + await _open(tester, phone, repo); + expect(find.text('Sign in with Microsoft'), findsOneWidget); + expect( + find.text('Use your work account. No new password.'), findsOneWidget); + }); + + testWidgets('a workspace that keeps the demo on offers both', + (tester) async { + final repo = _WorkspaceRepo( + config: const AuthConfig(provider: 'google', demo: true)); + await _open(tester, phone, repo); + expect(find.text('Sign in with Google'), findsOneWidget); + expect(find.text('Try the demo instead'), findsOneWidget); + + await tester.tap(find.text('Try the demo instead')); + await _settle(tester); + expect(find.text('Alice Tan'), findsOneWidget); + }); + + testWidgets('coming back from sign-in lands on the person\'s documents', + (tester) async { + final repo = _WorkspaceRepo( + comeBack: const Session( + token: 't', userId: 'u1', name: 'Alice Tan', demo: false)); + await _open(tester, phone, repo); + expect(find.text('Alice Tan'), findsOneWidget); + expect(find.text('Q3 budget review.pdf'), findsOneWidget); + // A real work account is not told it is a demo. + expect(find.text('Demo: nothing is really printed.'), findsNothing); + expect(Constants.demoMode, isFalse); + }); + + testWidgets('a turned-away account sees the reason and can try again', + (tester) async { + final repo = _WorkspaceRepo(turnedAway: 'That account is not allowed.'); + await _open(tester, phone, repo); + expect(find.text('That account is not allowed.'), findsOneWidget); + expect(find.text('Sign in with Google'), findsOneWidget); + }); + + testWidgets('when the server cannot be reached the person can try again', + (tester) async { + final repo = _OfflineRepo(); + await _open(tester, phone, repo); + expect(find.text('Cannot reach the print server.'), findsOneWidget); + repo.online = true; + await tester.tap(find.text('Try again')); + await _settle(tester); + expect(find.text('Sign in with Microsoft'), findsOneWidget); + }); + }); + + group('printers', () { + testWidgets('the person picks a printer and the confirmation names it', + (tester) async { + final repo = _WorkspaceRepo( + config: const AuthConfig(demo: true), + comeBack: const Session( + token: 't', userId: 'u1', name: 'Alice Tan', demo: false)); + await _open(tester, phone, repo); + expect(find.text('Level 3 East'), findsOneWidget); + + await tester.tap(find.text('Level 3 East')); + await _settle(tester); + await tester.tap(find.text('Reception')); + await _settle(tester); + await tester.tap(find.textContaining('Print 2 documents')); + await _settle(tester); + + expect(repo.released, ['p2']); + expect(find.text('Printing at Reception'), findsOneWidget); + }); + + testWidgets('with no printers set up nobody can print', (tester) async { + final repo = _NoPrintersRepo( + comeBack: const Session( + token: 't', userId: 'u1', name: 'Alice Tan', demo: false)); + await _open(tester, phone, repo); + expect(find.text('No printer available'), findsOneWidget); + expect(find.text('None set up yet'), findsOneWidget); + }); + }); + + group('admin setup', () { + testWidgets('the administrator adds, switches off and removes printers', + (tester) async { + final repo = MockPrintRepository(latency: Duration.zero); + await _open(tester, const Size(1280, 1400), repo); + await tester.tap(find.text('Demo: sign in as administrator')); + await _settle(tester); + + expect(find.text('Setup is complete'), findsOneWidget); + expect(find.text('Reception'), findsOneWidget); + + await tester.tap(find.text('Add a printer')); + await _settle(tester); + await tester.enterText(find.widgetWithText(TextField, 'Name'), 'Studio'); + await tester.tap(find.text('Add printer')); + await _settle(tester); + expect(find.text('Studio'), findsOneWidget); + expect((await repo.printers(_admin)).length, 4); + + await tester.tap(find.byType(Switch).first); + await _settle(tester); + expect((await repo.printers(_admin)).first.enabled, isFalse); + + await tester.tap(find.byTooltip('Remove Studio')); + await _settle(tester); + await tester.tap(find.text('Remove')); + await _settle(tester); + expect(find.text('Studio'), findsNothing); + }); + + testWidgets('quota rules: a default for new people and one for everyone', + (tester) async { + final repo = MockPrintRepository(latency: Duration.zero); + await _open(tester, const Size(1280, 1400), repo); + await tester.tap(find.text('Demo: sign in as administrator')); + await _settle(tester); + + final fields = find.widgetWithText(TextField, 'Pages per month'); + await tester.enterText(fields.at(0), '120'); + await tester.tap(find.text('Save').first); + await _settle(tester); + expect(find.text('New people will start with 120 pages a month.'), + findsOneWidget); + + await tester.enterText(fields.at(1), '75'); + await tester.tap(find.text('Apply to everyone')); + await _settle(tester); + // Asks first, because it replaces every limit. + expect(find.text('Give everyone 75 pages a month?'), findsOneWidget); + await tester.tap(find.descendant( + of: find.byType(AlertDialog), + matching: find.text('Apply to everyone'))); + await _settle(tester); + expect(find.text('4 people now have 75 pages.'), findsOneWidget); + expect( + (await repo.users(_admin)).every((u) => u.quota.total == 75), isTrue); + }); + + testWidgets('a quota that is not a number is refused', (tester) async { + final repo = MockPrintRepository(latency: Duration.zero); + await _open(tester, const Size(1280, 1400), repo); + await tester.tap(find.text('Demo: sign in as administrator')); + await _settle(tester); + await tester.enterText( + find.widgetWithText(TextField, 'Pages per month').at(1), 'lots'); + await tester.tap(find.text('Apply to everyone')); + await _settle(tester); + expect(find.text('Enter a whole number of pages, from 0 to 100000.'), + findsOneWidget); + }); + }); + + group('browser hand-over', () { + http.Client noServer() => MockClient((r) async => http.Response('{}', 200)); + + /// [fragment] is what the page was opened with after signing in; it can be read once. + HttpPrintRepository repo(String url, + {String fragment = '', + List? went, + List? taken, + http.Client? client}) { + var left = fragment; + return HttpPrintRepository( + api: ApiService( + baseUrl: 'https://p.example/api', client: client ?? noServer()), + location: () => Uri.parse(url), + navigate: (u) => went?.add(u), + takeFragment: () { + taken?.add(1); + final value = left; + left = ''; + return value; + }, + ); + } + + test('the sign-in link keeps the printer panel\'s address', () { + final went = []; + repo('https://p.example/?printer=p2', went: went).startWorkspaceSignIn(); + expect(went.single, + 'https://p.example/api/auth/login?returnTo=%2F%3Fprinter%3Dp2'); + final plain = []; + repo('https://p.example/', went: plain).startWorkspaceSignIn(); + expect(plain.single, 'https://p.example/api/auth/login?returnTo=%2F'); + }); + + test('the printer in the address is the panel\'s printer', () { + expect(repo('https://p.example/?printer=p2').panelPrinterId, 'p2'); + expect(repo('https://p.example/').panelPrinterId, isNull); + expect(repo('https://p.example/?printer=').panelPrinterId, isNull); + }); + + test('the token the page was opened with is used, and only once', () async { + final client = MockClient((r) async { + expect(r.headers['Authorization'], 'Bearer abc.def-ghi_jkl'); + return http.Response( + jsonEncode({'userId': 'g-1', 'name': 'Pat', 'isAdmin': true}), 200, + headers: {'content-type': 'application/json'}); + }); + final r = repo('https://p.example/?printer=p2', + fragment: 'token=abc.def-ghi_jkl', client: client); + final session = await r.resumeSignIn(); + expect(session!.name, 'Pat'); + expect(session.isAdmin, isTrue); + expect(session.demo, isFalse); + // Asking again finds nothing, so a refresh does not sign in twice. + expect(await r.resumeSignIn(), isNull); + }); + + test('nothing to resume when the page was opened normally', () async { + expect(await repo('https://p.example/').resumeSignIn(), isNull); + }); + + test('every reason for being turned away is explained', () async { + for (final code in [ + 'wrong_account', + 'unverified_email', + 'no_identity', + 'sign_in_failed' + ]) { + await expectLater( + repo('https://p.example/', fragment: 'error=$code').resumeSignIn(), + throwsA(isA().having((e) => e.message, 'message', + HttpPrintRepository.signInProblem(code))), + ); + } + expect(HttpPrintRepository.signInProblem('wrong_account'), + isNot(HttpPrintRepository.signInProblem('sign_in_failed'))); + }); + }); + + group('server calls', () { + final requests = []; + ApiService api(Object body) => ApiService( + baseUrl: 'https://p.example/api', + client: MockClient((r) async { + requests.add(r); + return http.Response(jsonEncode(body), 200, + headers: {'content-type': 'application/json'}); + })); + + setUp(requests.clear); + + test('the sign-in options are read before anyone signs in', () async { + final config = await api({ + 'provider': 'google', + 'providerName': 'Google', + 'domain': 'example.com', + 'demo': false + }).authConfig(); + expect(requests.single.url.path, '/api/auth/config'); + expect(requests.single.headers.containsKey('Authorization'), isFalse); + expect(config.provider, 'google'); + expect(config.domain, 'example.com'); + expect(config.demo, isFalse); + expect(config.hasWorkspace, isTrue); + }); + + test('releasing names the printer', () async { + await api({ + 'printed': ['1'] + }).release('t', ['1'], printerId: 'p2'); + expect(jsonDecode(requests.single.body), { + 'jobIds': ['1'], + 'printerId': 'p2' + }); + requests.clear(); + await api({ + 'printed': ['1'] + }).release('t', ['1']); + expect(jsonDecode(requests.single.body), { + 'jobIds': ['1'] + }); + }); + + test('printers are listed', () async { + final list = await api([ + {'id': 'p1', 'name': 'Level 3', 'location': 'East', 'enabled': true}, + {'id': 'p2', 'name': 'Old', 'location': '', 'enabled': false} + ]).printers('t'); + expect(list.map((p) => p.name), ['Level 3', 'Old']); + expect(list.last.enabled, isFalse); + }); + + test('setup and quota rules go to the right places', () async { + final setup = await api({ + 'provider': 'Google', + 'domain': 'example.com', + 'demoEnabled': false, + 'defaultQuota': 50, + 'people': 3, + 'printers': 0, + 'redirectUri': 'https://p.example/api/auth/callback', + 'warnings': ['No printers yet.'] + }).setup('t'); + expect(requests.single.url.path, '/api/admin/setup'); + expect(setup.warnings, ['No printers yet.']); + expect(setup.hasWorkspace, isTrue); + + requests.clear(); + await api({}).setDefaultQuota('t', 80); + expect(requests.single.url.path, '/api/admin/default-quota'); + expect(jsonDecode(requests.single.body), {'quota': 80}); + + requests.clear(); + final changed = await api({'changed': 7}).setQuotaForAll('t', 30); + expect(requests.single.url.path, '/api/admin/set-quota-all'); + expect(changed, 7); + }); + + test('printers are added, changed and removed', () async { + final added = await api( + {'id': 'p9', 'name': 'Studio', 'location': 'L1', 'enabled': true}) + .addPrinter('t', 'Studio', 'L1'); + expect(requests.single.method, 'POST'); + expect(added.id, 'p9'); + + requests.clear(); + await api({}).updatePrinter('t', added); + expect(requests.single.method, 'PUT'); + expect(requests.single.url.path, '/api/admin/printers/p9'); + expect(jsonDecode(requests.single.body), + {'name': 'Studio', 'location': 'L1', 'enabled': true}); + + requests.clear(); + await api({}).deletePrinter('t', 'p9'); + expect(requests.single.method, 'DELETE'); + }); + }); +} + +class _OfflineRepo extends MockPrintRepository { + _OfflineRepo() : super(latency: Duration.zero); + bool online = false; + + @override + Future authConfig() async { + if (!online) throw const PrintException('Cannot reach the print server.'); + return AuthConfig.demoOnly; + } +} + +class _NoPrintersRepo extends _WorkspaceRepo { + _NoPrintersRepo({super.comeBack}); + + @override + Future> printers(Session session) async => const []; +} diff --git a/tools/screenshots/README.md b/tools/screenshots/README.md new file mode 100644 index 0000000..e19e796 --- /dev/null +++ b/tools/screenshots/README.md @@ -0,0 +1,57 @@ +# Pictures for the docs + +Every picture in `docs/images/` and the README is taken from the running app, so they stay true. Run these when a screen changes. + +## What you need + +* Node.js and [Playwright](https://playwright.dev) (`npm i -g playwright`), and a Chromium. Set `CHROMIUM=/path/to/chrome` if it is not at `/opt/pw-browsers/chromium`. +* Optional: `ROBOTO=/path/to/Roboto-Regular.ttf` so the page does not wait for Google Fonts. +* `ffmpeg` for the GIF. +* The web app built against the API, served by the API: + + ```bash + flutter build web -t frontend/lib/main.dart --release --no-web-resources-cdn --dart-define=USE_MOCK=false + dotnet publish backend -c Release -o /tmp/pp + rm -rf /tmp/pp/wwwroot && cp -r build/web /tmp/pp/wwwroot + ``` + +## Start four copies of the server + +They differ only in how sign-in is set up, so each kind of screen can be shown. + +```bash +cd /tmp/pp +KEY=0123456789012345678901234567890123456789 # for pictures only +# 1 the demo (port 5055) +ASPNETCORE_URLS=http://127.0.0.1:5055 Demo__Enabled=true dotnet PullPrintingBackend.dll & +# 2 Google Workspace, demo off (port 5056) +ASPNETCORE_URLS=http://127.0.0.1:5056 Demo__Enabled=false Workspace__Provider=Google \ + Workspace__ClientId=x Workspace__ClientSecret=x Workspace__Domain=example.com Auth__SigningKey=$KEY \ + dotnet PullPrintingBackend.dll & +# 3 Microsoft 365, demo off (port 5057) +ASPNETCORE_URLS=http://127.0.0.1:5057 Demo__Enabled=false Workspace__Provider=Microsoft \ + Workspace__ClientId=x Workspace__ClientSecret=x Workspace__TenantId=11111111-1111-1111-1111-111111111111 \ + Auth__SigningKey=$KEY dotnet PullPrintingBackend.dll & +# 4 Google with the demo on, no signing key (port 5058) +ASPNETCORE_URLS=http://127.0.0.1:5058 Demo__Enabled=true Workspace__Provider=Google \ + Workspace__ClientId=x Workspace__ClientSecret=x Workspace__Domain=example.com \ + dotnet PullPrintingBackend.dll & +``` + +## Take the pictures + +```bash +node tools/screenshots/shoot.js docs/images # every screenshot +node tools/screenshots/record.js /tmp/video # the phone walk-through video +tools/screenshots/make-gif.sh /tmp/video/*.webm docs/images/demo.gif 5 +``` + +`shoot.js` takes the four server addresses as optional arguments after the output folder. It reports any step that failed and exits with an error. + +The two diagrams, `docs/images/how-it-fits.svg` and `sign-in-flow.svg`, are plain SVG files. Edit them by hand. + +## Rules for pictures + +* Take them from the app, never mock them up. +* Use the sample people and documents the demo starts with. No real names, addresses or secrets. +* Give every picture useful alt text where it is used. diff --git a/tools/screenshots/make-gif.sh b/tools/screenshots/make-gif.sh new file mode 100755 index 0000000..e852b4f --- /dev/null +++ b/tools/screenshots/make-gif.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Turns the recorded video into a small looping GIF. +# tools/screenshots/make-gif.sh [skip-seconds] +set -euo pipefail +in="$1"; out="$2"; skip="${3:-0}" +pal="$(mktemp --suffix=.png)" +ffmpeg -loglevel error -y -ss "$skip" -i "$in" -vf "fps=10,scale=300:-1:flags=lanczos,palettegen=max_colors=96" "$pal" +ffmpeg -loglevel error -y -ss "$skip" -i "$in" -i "$pal" -lavfi "fps=10,scale=300:-1:flags=lanczos[x];[x][1:v]paletteuse=dither=bayer:bayer_scale=4" "$out" +rm -f "$pal" diff --git a/tools/screenshots/record.js b/tools/screenshots/record.js new file mode 100644 index 0000000..7c833e0 --- /dev/null +++ b/tools/screenshots/record.js @@ -0,0 +1,36 @@ +// Records the short phone walk-through used at the top of the README. +// node tools/screenshots/record.js [demoUrl] then it is turned into a GIF by make-gif.sh +const { chromium } = require('playwright'); +const fs = require('fs'); +const [out, DEMO = 'http://127.0.0.1:5055'] = process.argv.slice(2); +if (!out) { console.error('Usage: node record.js [url]'); process.exit(1); } +fs.mkdirSync(out, { recursive: true }); + +(async () => { + const browser = await chromium.launch({ executablePath: process.env.CHROMIUM || '/opt/pw-browsers/chromium' }); + const ctx = await browser.newContext({ + viewport: { width: 390, height: 844 }, deviceScaleFactor: 1, + recordVideo: { dir: out, size: { width: 390, height: 844 } }, + }); + const p = await ctx.newPage(); + if (process.env.ROBOTO) { + await p.route(/fonts\.gstatic\.com|fonts\.googleapis\.com/, r => r.fulfill({ path: process.env.ROBOTO, contentType: 'font/ttf' })); + } + await p.goto(DEMO); + await p.waitForSelector('flt-glass-pane', { state: 'attached', timeout: 60000 }); + await p.waitForTimeout(3500); + await p.evaluate(() => document.querySelector('flt-semantics-placeholder')?.click()); + const t0 = Date.now(); + console.log('READY_AT_MS', t0); + await p.waitForTimeout(1800); + await p.getByRole('button', { name: 'Sign in with Microsoft' }).first().click({ force: true }); + await p.waitForTimeout(2600); + await p.getByRole('checkbox', { name: /Contract draft/ }).first().click({ force: true }); + await p.waitForTimeout(1800); + await p.getByRole('checkbox', { name: /Contract draft/ }).first().click({ force: true }); + await p.waitForTimeout(1200); + await p.getByRole('button', { name: /^Print 2 documents/ }).first().click({ force: true }); + await p.waitForTimeout(3500); + await ctx.close(); + await browser.close(); +})(); diff --git a/tools/screenshots/shoot.js b/tools/screenshots/shoot.js new file mode 100644 index 0000000..539031c --- /dev/null +++ b/tools/screenshots/shoot.js @@ -0,0 +1,144 @@ +// Takes every picture used in the README and docs/ from a running copy of the app. +// +// node tools/screenshots/shoot.js [demoUrl] [googleUrl] [microsoftUrl] [mixedUrl] +// +// See tools/screenshots/README.md for how to start the four servers it expects. +// Needs Playwright and a Chromium (set CHROMIUM=/path/to/chrome if it is not found). +const { chromium } = require('playwright'); +const fs = require('fs'); + +const [out, DEMO = 'http://127.0.0.1:5055', GOOGLE = 'http://127.0.0.1:5056', + MICROSOFT = 'http://127.0.0.1:5057', MIXED = 'http://127.0.0.1:5058'] = process.argv.slice(2); +if (!out) { console.error('Usage: node shoot.js [urls...]'); process.exit(1); } +fs.mkdirSync(out, { recursive: true }); + +const PHONE = { width: 390, height: 844 }; +const PANEL = { width: 1024, height: 600 }; +const WIDE = { width: 1280, height: 1500 }; +const failures = []; + +(async () => { + const browser = await chromium.launch({ executablePath: process.env.CHROMIUM || '/opt/pw-browsers/chromium' }); + + async function open(url, size, { fonts = true } = {}) { + const ctx = await browser.newContext({ viewport: size, deviceScaleFactor: 2 }); + const page = await ctx.newPage(); + if (fonts && process.env.ROBOTO) { + await page.route(/fonts\.gstatic\.com|fonts\.googleapis\.com/, r => + r.fulfill({ path: process.env.ROBOTO, contentType: 'font/ttf' })); + } + await page.goto(url); + await page.waitForSelector('flt-glass-pane', { state: 'attached', timeout: 60000 }); + await page.waitForTimeout(3500); + await page.evaluate(() => document.querySelector('flt-semantics-placeholder')?.click()); + await page.waitForTimeout(800); + return page; + } + const button = (p, name) => p.getByRole('button', { name }).first(); + const press = async (p, name) => { await button(p, name).click({ force: true }); await p.waitForTimeout(1500); }; + const shot = async (p, name, clip) => { + await p.waitForTimeout(900); + await p.screenshot({ path: `${out}/${name}.png`, ...(clip ? { clip } : {}) }); + console.log('saved', name); + }; + const step = async (label, fn) => { try { await fn(); } catch (e) { failures.push(label); console.log('FAILED', label, e.message.split('\n')[0]); } }; + const api = (base, path, token, method = 'GET', body) => fetch(base + '/api' + path, { + method, headers: { 'content-type': 'application/json', ...(token ? { authorization: 'Bearer ' + token } : {}) }, + body: body ? JSON.stringify(body) : undefined, + }).then(r => r.status === 204 ? null : r.text().then(t => t ? JSON.parse(t) : null)); + const demoLogin = (base, admin) => api(base, '/auth/demo-login', null, 'POST', { admin }); + + // ---- a person on their phone ---- + await step('phone', async () => { + const p = await open(DEMO, PHONE); + await shot(p, 'phone-1-sign-in'); + await press(p, /What is this/); + await shot(p, 'phone-1b-about-demo'); + await press(p, 'Got it'); + await press(p, 'Sign in with Microsoft'); + await shot(p, 'phone-2-documents'); + await p.getByRole('checkbox', { name: /Contract draft/ }).first().click({ force: true }); + await shot(p, 'phone-3-over-limit'); + await p.getByRole('checkbox', { name: /Contract draft/ }).first().click({ force: true }); + await p.getByText('Level 3 East').first().click({ force: true }); + await shot(p, 'phone-4-pick-printer'); + await p.getByText('Reception').first().click({ force: true }); + await p.waitForTimeout(800); + await button(p, /^Print 2 documents/).click({ force: true }); + await p.waitForTimeout(2500); + await shot(p, 'phone-5-printed'); + }); + + // ---- the printer's own screen ---- + await step('panel', async () => { + const admin = await demoLogin(DEMO, false); + const printers = await api(DEMO, '/printers', admin.token); + const reception = printers.find(x => x.name === 'Reception'); + const p = await open(`${DEMO}/?printer=${reception.id}`, PANEL); + await shot(p, 'panel-1-sign-in'); + await press(p, 'Sign in with Microsoft'); + await shot(p, 'panel-2-documents'); + await p.getByRole('checkbox', { name: /Contract draft/ }).first().click({ force: true }); + await shot(p, 'panel-2b-over-limit'); + await p.getByRole('checkbox', { name: /Contract draft/ }).first().click({ force: true }); + await p.waitForTimeout(500); + await press(p, /^Print$/); + await p.waitForTimeout(1500); + await shot(p, 'panel-3-printing'); + }); + + // ---- the administrator ---- + await step('admin', async () => { + const p = await open(DEMO, WIDE); + await press(p, /Demo: sign in as administrator/); + await p.waitForTimeout(1500); + await shot(p, 'admin-1-overview', { x: 0, y: 0, width: 1280, height: 660 }); + await shot(p, 'admin-2-printers', { x: 24, y: 360, width: 1232, height: 300 }); + await shot(p, 'admin-3-people', { x: 24, y: 676, width: 1232, height: 500 }); + await shot(p, 'admin-4-jobs', { x: 24, y: 1188, width: 1232, height: 312 }); + await press(p, 'Add a printer'); + await shot(p, 'admin-5-add-printer'); + await p.keyboard.press('Escape'); + await p.waitForTimeout(500); + }); + await step('admin-confirm', async () => { + const p = await open(DEMO, WIDE); + await press(p, /Demo: sign in as administrator/); + // The first box is "New people start with", the second is "Give everyone". + const field = p.getByRole('textbox').nth(1); + await field.click({ force: true }); + await p.keyboard.type('75'); + await press(p, 'Apply to everyone'); + await shot(p, 'admin-6-apply-to-everyone'); + }); + + // ---- setup that still has things to do ---- + await step('setup-todo', async () => { + const admin = await demoLogin(DEMO, true); + for (const x of await api(DEMO, '/printers', admin.token)) await api(DEMO, `/admin/printers/${x.id}`, admin.token, 'DELETE'); + const p = await open(`${DEMO}/#token=${admin.token}`, WIDE); + await shot(p, 'setup-1-finish', { x: 0, y: 0, width: 1280, height: 520 }); + }); + await step('setup-address', async () => { + const admin = await demoLogin(MIXED, true); + const p = await open(`${MIXED}/#token=${admin.token}`, WIDE); + await shot(p, 'setup-2-register-address', { x: 0, y: 0, width: 1280, height: 420 }); + }); + + // ---- signing in with a work account ---- + await step('work-account', async () => { + let p = await open(GOOGLE, PHONE); + await shot(p, 'workspace-google-phone'); + p = await open(`${GOOGLE}/?printer=p1`, PANEL); + await shot(p, 'workspace-google-panel'); + p = await open(MICROSOFT, PHONE); + await shot(p, 'workspace-microsoft-phone'); + p = await open(MIXED, PHONE); + await shot(p, 'workspace-with-demo'); + p = await open(`${GOOGLE}/#error=wrong_account`, PANEL); + await shot(p, 'workspace-turned-away'); + }); + + await browser.close(); + if (failures.length) { console.log('Steps that failed:', failures.join(', ')); process.exit(1); } +})(); diff --git a/vercel.json b/vercel.json new file mode 100644 index 0000000..cfdd746 --- /dev/null +++ b/vercel.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "framework": null, + "installCommand": "echo \"dependencies are installed by the build script\"", + "buildCommand": "bash scripts/vercel-build.sh", + "outputDirectory": "build/web", + "headers": [ + { + "source": "/(index.html|flutter_bootstrap.js|flutter_service_worker.js|version.json)", + "headers": [{ "key": "Cache-Control", "value": "no-cache" }] + } + ] +} diff --git a/web/favicon.png b/web/favicon.png index 8aaa46a..1e63824 100644 Binary files a/web/favicon.png and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png index b749bfe..24269d6 100644 Binary files a/web/icons/Icon-192.png and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png index 88cfd48..e82ff9b 100644 Binary files a/web/icons/Icon-512.png and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png index eb9b4d7..0295f70 100644 Binary files a/web/icons/Icon-maskable-192.png and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png index d69c566..c3e22fa 100644 Binary files a/web/icons/Icon-maskable-512.png and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html index 68dd220..e619104 100644 --- a/web/index.html +++ b/web/index.html @@ -1,38 +1,82 @@ - + - + - + + + + + + + + + + - - + + + - - - - pull_printing_app + + + Pull Print demo + + +
+
+ + Pull Print +
+ +
Loading the demo. This can take a few seconds the first time.
+ +
+ + diff --git a/web/manifest.json b/web/manifest.json index 8ea7105..7cf4f5d 100644 --- a/web/manifest.json +++ b/web/manifest.json @@ -1,12 +1,12 @@ { - "name": "pull_printing_app", - "short_name": "pull_printing_app", + "name": "Pull Print", + "short_name": "Pull Print", "start_url": ".", "display": "standalone", - "background_color": "#0175C2", - "theme_color": "#0175C2", - "description": "A new Flutter project.", - "orientation": "portrait-primary", + "background_color": "#0E2A47", + "theme_color": "#0E2A47", + "description": "Documents wait on a server until you are at the printer and tap Print. A demo with sample data.", + "orientation": "any", "prefer_related_applications": false, "icons": [ {