mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-10-21 20:23:19 +01:00
Compare commits
51 Commits
fix/neutra
...
chore/fran
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f41bca1a3 | ||
|
|
eed654b9c8 | ||
|
|
68833a5125 | ||
|
|
735f3b8d39 | ||
|
|
9caf911795 | ||
|
|
c55afd234e | ||
|
|
20cc5f9e5b | ||
|
|
2df7a2845e | ||
|
|
510cb10cb9 | ||
|
|
b46f015754 | ||
|
|
fc8985f513 | ||
|
|
812b3f2f54 | ||
|
|
4b25b2adfa | ||
|
|
9557296eb0 | ||
|
|
c69edc81be | ||
|
|
902270a189 | ||
|
|
f60c9ca457 | ||
|
|
1c41432389 | ||
|
|
3197c8c7a0 | ||
|
|
b8761dffce | ||
|
|
ba2b37f264 | ||
|
|
9e6013eaf1 | ||
|
|
11dd4e174e | ||
|
|
b73cdc4bb5 | ||
|
|
e82c601449 | ||
|
|
f65a1532ad | ||
|
|
b42e84294c | ||
|
|
1863953a23 | ||
|
|
ce9413a55e | ||
|
|
b08364770c | ||
|
|
26926d3b2c | ||
|
|
fd008dd4a8 | ||
|
|
9a845bad8f | ||
|
|
b9e3f55537 | ||
|
|
0b2a417788 | ||
|
|
65525791a6 | ||
|
|
0c58896b00 | ||
|
|
6301b0f4a1 | ||
|
|
4c993c8eb2 | ||
|
|
ae6937d012 | ||
|
|
1256fa61bd | ||
|
|
d6f80e23fb | ||
|
|
c994345de9 | ||
|
|
e56a659723 | ||
|
|
c3529e4373 | ||
|
|
81c923644d | ||
|
|
689b2e93e1 | ||
|
|
63ca886154 | ||
|
|
5010a5be3a | ||
|
|
b05f275fe8 | ||
|
|
f01a4111b6 |
14
.github/workflows/generate-api-docs.yml
vendored
14
.github/workflows/generate-api-docs.yml
vendored
@@ -3,6 +3,7 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -57,10 +58,9 @@ jobs:
|
||||
name: api-docs.json
|
||||
path: build/api-docs.json
|
||||
|
||||
- name: "Download Fastfront CLI"
|
||||
run: curl https://fastfront-cli.s3.fr-par.scw.cloud/fastfront-cli.phar -o fastfront-cli.phar
|
||||
|
||||
- name: "Deploy with Fastfront"
|
||||
run: php fastfront-cli.phar deploy 9beab6cf-f459-446b-85f1-38ec007cf457 ./build
|
||||
env:
|
||||
FASTFRONT_API_KEY: ${{ secrets.FASTFRONT_API_DOCS_API_KEY }}
|
||||
- name: "Deploy with FastFront"
|
||||
uses: fastfront-io/deploy-action@v0.0.1
|
||||
with:
|
||||
folder: './build'
|
||||
environment: ${{ vars.FASTFRONT_API_DOCS_STAGE }}
|
||||
api_key: ${{ secrets.FASTFRONT_API_DOCS_STAGE_KEY }}
|
||||
|
||||
7
.github/workflows/phpunit-extensions.yml
vendored
7
.github/workflows/phpunit-extensions.yml
vendored
@@ -5,7 +5,7 @@ permissions:
|
||||
jobs:
|
||||
phpunit-extensions:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
timeout-minutes: 25
|
||||
strategy:
|
||||
matrix:
|
||||
postgres_version: [ 15, 16, 17 ]
|
||||
@@ -132,5 +132,8 @@ jobs:
|
||||
php artisan key:generate
|
||||
php artisan passport:keys
|
||||
|
||||
- name: "Run PHPUnit"
|
||||
- name: "Run PHPUnit (extensions)"
|
||||
run: php artisan test extensions/Billing/tests extensions/Services/tests extensions/Invoicing/tests --stop-on-failure
|
||||
|
||||
- name: "Run PHPUnit (core)"
|
||||
run: php artisan test --testsuite=Unit,Feature --stop-on-failure
|
||||
|
||||
86
.oss-scanner/Dockerfile
Normal file
86
.oss-scanner/Dockerfile
Normal file
@@ -0,0 +1,86 @@
|
||||
# Build environment for Anthropic's OSS Scanner (https://github.com/anthropics/oss-scanner).
|
||||
# The scanner builds this image with the repository root as the build context and then audits it without network
|
||||
# access, so everything needed to run the app and its test suite (PHP + Composer deps, Node deps + built frontend,
|
||||
# a local PostgreSQL and a local Gotenberg for PDF rendering) is installed here.
|
||||
#
|
||||
# The base image is the FrankenPHP image the production image (docker/prod/Dockerfile) is built on: in production the
|
||||
# app runs as long-lived Laravel Octane workers in FrankenPHP worker mode, not as one PHP process per request.
|
||||
#
|
||||
# Inside the finished image:
|
||||
# .oss-scanner/start-postgres.sh start the local PostgreSQL server (required for tests and the app)
|
||||
# .oss-scanner/start-gotenberg.sh start the local Gotenberg server (required for PDF exports)
|
||||
# php artisan test run the PHPUnit suite (needs PostgreSQL and Gotenberg running)
|
||||
# .oss-scanner/start-octane.sh run the app like production on http://127.0.0.1:8000 (starts everything above)
|
||||
|
||||
ARG FRANKENPHP_VERSION=1.11
|
||||
ARG PHP_VERSION=8.3
|
||||
|
||||
FROM node:20-trixie-slim AS node
|
||||
|
||||
FROM gotenberg/gotenberg:8 AS gotenberg
|
||||
|
||||
FROM dunglas/frankenphp:${FRANKENPHP_VERSION}-php${PHP_VERSION}
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
COMPOSER_ALLOW_SUPERUSER=1 \
|
||||
COMPOSER_NO_INTERACTION=1 \
|
||||
OCTANE_SERVER=frankenphp \
|
||||
TZ=UTC
|
||||
|
||||
COPY --from=composer:2 /usr/bin/composer /usr/local/bin/composer
|
||||
COPY --from=node /usr/local/bin/node /usr/local/bin/node
|
||||
COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules
|
||||
RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \
|
||||
&& ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
|
||||
|
||||
# PostgreSQL 17 (Debian trixie default) is one of the versions solidtime is tested against in CI.
|
||||
# chromium, qpdf and exiftool are what Gotenberg needs for HTML to PDF rendering.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends git unzip curl ca-certificates postgresql postgresql-client \
|
||||
chromium fonts-liberation qpdf libimage-exiftool-perl \
|
||||
&& install-php-extensions pdo_pgsql pgsql intl gd zip bcmath exif pcntl sockets soap apcu \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& echo "memory_limit=2G" > "$PHP_INI_DIR/conf.d/99-oss-scanner.ini"
|
||||
|
||||
# Gotenberg 8 (the PDF renderer, same image as in CI). solidtime only uses its Chromium HTML to PDF route, so LibreOffice
|
||||
# and pdftk are not installed: Gotenberg only checks at startup that their binaries exist, start-gotenberg.sh disables
|
||||
# the LibreOffice routes and the Chromium route does not use pdftk.
|
||||
COPY --from=gotenberg /usr/bin/gotenberg /usr/local/bin/gotenberg
|
||||
COPY --from=gotenberg /usr/bin/pdfcpu /usr/local/bin/pdfcpu
|
||||
COPY --from=gotenberg /opt/gotenberg /opt/gotenberg
|
||||
ENV CHROMIUM_BIN_PATH=/usr/bin/chromium \
|
||||
CHROMIUM_HYPHEN_DATA_DIR_PATH=/opt/gotenberg/chromium-hyphen-data \
|
||||
GOTENBERG_VERSIONS_DIR_PATH=/opt/gotenberg/versions \
|
||||
QPDF_BIN_PATH=/usr/bin/qpdf \
|
||||
EXIFTOOL_BIN_PATH=/usr/bin/exiftool \
|
||||
PDFCPU_BIN_PATH=/usr/local/bin/pdfcpu \
|
||||
LIBREOFFICE_BIN_PATH=/bin/false \
|
||||
UNOCONVERTER_BIN_PATH=/bin/false \
|
||||
PDFTK_BIN_PATH=/bin/false
|
||||
|
||||
# Database matching .env.ci: user root / password root, database laravel.
|
||||
RUN pg_ctlcluster 17 main start \
|
||||
&& runuser -u postgres -- psql -c "CREATE ROLE root WITH LOGIN SUPERUSER PASSWORD 'root';" \
|
||||
&& runuser -u postgres -- createdb -O root laravel \
|
||||
&& pg_ctlcluster 17 main stop
|
||||
|
||||
# scanner contract: the checkout lives inside the image, at /src
|
||||
COPY . /src
|
||||
WORKDIR /src
|
||||
|
||||
RUN composer install --prefer-dist \
|
||||
&& npm ci \
|
||||
&& npm run build
|
||||
|
||||
RUN cp .env.ci .env \
|
||||
&& php artisan key:generate \
|
||||
&& php artisan passport:keys --force \
|
||||
&& php artisan octane:install --server=frankenphp --no-interaction \
|
||||
&& chmod +x .oss-scanner/*.sh
|
||||
|
||||
# Run the test suite so the image is known to work, but do not fail the build on test failures.
|
||||
RUN .oss-scanner/start-postgres.sh \
|
||||
&& .oss-scanner/start-gotenberg.sh \
|
||||
&& (php artisan test || echo "WARNING: PHPUnit reported failures") \
|
||||
&& kill "$(cat /tmp/gotenberg.pid)" \
|
||||
&& pg_ctlcluster 17 main stop
|
||||
18
.oss-scanner/Dockerfile.dockerignore
Normal file
18
.oss-scanner/Dockerfile.dockerignore
Normal file
@@ -0,0 +1,18 @@
|
||||
# Used instead of the root .dockerignore when building .oss-scanner/Dockerfile. The root one is tailored to the
|
||||
# production image and excludes tests, phpunit.xml etc., which the scanner needs.
|
||||
node_modules
|
||||
extensions/*/node_modules
|
||||
vendor
|
||||
.env
|
||||
public/build
|
||||
public/hot
|
||||
storage/*.key
|
||||
storage/logs/*
|
||||
coverage
|
||||
test-results
|
||||
playwright-report
|
||||
.phpunit.cache
|
||||
.phpunit.result.cache
|
||||
auth.json
|
||||
.DS_Store
|
||||
.idea
|
||||
16
.oss-scanner/start-gotenberg.sh
Executable file
16
.oss-scanner/start-gotenberg.sh
Executable file
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start the local Gotenberg server (PDF rendering) on 127.0.0.1:3000, matching GOTENBERG_URL in .env.ci.
|
||||
# Only the Chromium routes are needed by solidtime, see .oss-scanner/Dockerfile. Stop: kill "$(cat /tmp/gotenberg.pid)"
|
||||
set -euo pipefail
|
||||
|
||||
if ! curl -fs http://127.0.0.1:3000/health >/dev/null; then
|
||||
nohup gotenberg \
|
||||
--api-port=3000 \
|
||||
--libreoffice-disable-routes \
|
||||
--libreoffice-auto-start=false \
|
||||
--log-level=warn \
|
||||
>/tmp/gotenberg.log 2>&1 &
|
||||
echo $! >/tmp/gotenberg.pid
|
||||
until curl -fs http://127.0.0.1:3000/health >/dev/null; do sleep 0.5; done
|
||||
fi
|
||||
echo "Gotenberg is running on http://127.0.0.1:3000 (log: /tmp/gotenberg.log)"
|
||||
37
.oss-scanner/start-octane.sh
Executable file
37
.oss-scanner/start-octane.sh
Executable file
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run the app the way production does: Laravel Octane on FrankenPHP in worker mode, with the production Caddyfile.
|
||||
# A worker boots the app once and then serves many requests, so state kept in memory (static properties, singletons,
|
||||
# changed config, ...) survives from one request to the next. With a single worker, consecutive requests always hit the
|
||||
# same worker, so such leaks between requests (e.g. between users of different organizations) reproduce reliably.
|
||||
#
|
||||
# Usage: .oss-scanner/start-octane.sh (OCTANE_WORKERS and OCTANE_MAX_REQUESTS can be overridden)
|
||||
# Stop: php artisan octane:stop
|
||||
# After changing PHP code, run `php artisan octane:reload`: workers keep the code they booted with.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
.oss-scanner/start-postgres.sh
|
||||
.oss-scanner/start-gotenberg.sh
|
||||
|
||||
php artisan migrate --force
|
||||
if [ "$(PGPASSWORD=root psql -h 127.0.0.1 -U root -d laravel -tAc 'SELECT count(*) FROM users')" = "0" ]; then
|
||||
php artisan db:seed --force
|
||||
fi
|
||||
php artisan optimize:clear >/dev/null
|
||||
|
||||
nohup php artisan octane:frankenphp \
|
||||
--host=127.0.0.1 \
|
||||
--port=8000 \
|
||||
--workers="${OCTANE_WORKERS:-1}" \
|
||||
--max-requests="${OCTANE_MAX_REQUESTS:-10000}" \
|
||||
--caddyfile=docker/prod/deployment/octane/FrankenPHP/Caddyfile \
|
||||
>/tmp/octane.log 2>&1 &
|
||||
|
||||
until curl -fs -o /dev/null http://127.0.0.1:8000/login; do
|
||||
if ! kill -0 $! 2>/dev/null; then
|
||||
cat /tmp/octane.log
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "solidtime is running on http://127.0.0.1:8000 with Octane/FrankenPHP (log: /tmp/octane.log)"
|
||||
7
.oss-scanner/start-postgres.sh
Executable file
7
.oss-scanner/start-postgres.sh
Executable file
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start the local PostgreSQL server used by the test suite and the app (see .oss-scanner/Dockerfile).
|
||||
set -euo pipefail
|
||||
|
||||
pg_ctlcluster 17 main start 2>/dev/null || true
|
||||
until pg_isready -h 127.0.0.1 -p 5432 -q; do sleep 0.5; done
|
||||
echo "PostgreSQL is running on 127.0.0.1:5432 (user root, password root, database laravel)"
|
||||
122
.oss-scanner/threat_model.md
Normal file
122
.oss-scanner/threat_model.md
Normal file
@@ -0,0 +1,122 @@
|
||||
# Threat model
|
||||
|
||||
## What this project does
|
||||
|
||||
solidtime is an open-source, multi-tenant time tracking web application (Laravel backend, Vue 3 + Inertia frontend,
|
||||
PostgreSQL). It runs as a hosted SaaS (solidtime.io) and is self-hosted by many organisations. Users belong to one or
|
||||
more **organizations**; inside an organization each member has a role: `owner`, `admin`, `manager`, `employee` or
|
||||
`placeholder` (an imported, non-login member). What each role may do is defined in `app/Service/PermissionStore.php`.
|
||||
|
||||
The most important security property is **isolation**: a user must never read or modify data of an organization they
|
||||
are not a member of, and within an organization a member must not exceed the permissions of their role (e.g. an
|
||||
employee must not see other members' time entries, billable rates, or manage members, unless the organization settings
|
||||
explicitly allow it).
|
||||
|
||||
## Trust boundaries
|
||||
|
||||
- **Super admins are fully trusted.** They are the instance operators, configured via the `SUPER_ADMINS` env
|
||||
variable, and have access to the Filament admin panel (`app/Filament`), which can view and change data of every
|
||||
organization and impersonate users. Anything a super admin can do through the panel (including XSS, SQL injection,
|
||||
SSRF or file access that is only reachable from the panel) is not a vulnerability.
|
||||
- What **is** in scope: a user who is not a super admin reaching the admin panel, or any of its actions, at all.
|
||||
- Operators of a self-hosted instance (shell, database, environment, filesystem access) are trusted.
|
||||
- Everyone else, including organization owners and admins when acting outside their own organization, is untrusted.
|
||||
|
||||
## Runtime: long-lived Octane workers
|
||||
|
||||
In production (the hosted SaaS and the official Docker image, `docker/prod/`) the app does **not** run as one PHP
|
||||
process per request. It runs on Laravel Octane with FrankenPHP in worker mode: each worker boots the application once
|
||||
and then serves many requests from different users and organizations. Anything kept in memory survives from one request
|
||||
to the next unless Octane resets it (`config/octane.php` lists what is reset). This includes static properties and
|
||||
static caches, container bindings registered with `singleton()` instead of `scoped()` (see
|
||||
`app/Providers/AppServiceProvider.php`), objects captured by those singletons, runtime `config()` / locale / timezone
|
||||
changes, macros and event listeners registered during a request, and state in third-party packages.
|
||||
|
||||
Request A leaving state behind that request B (another user, possibly of another organization) then sees or is
|
||||
affected by is in scope, rated by its impact like any other issue (see severity below). The PHPUnit suite cannot
|
||||
show this class of bug, because it boots a fresh application for every test. It has to be reproduced over HTTP against
|
||||
the Octane server, see "How to exercise it".
|
||||
|
||||
## Where untrusted input enters
|
||||
|
||||
All authenticated users, including employees of any organization and anyone who self-registers (registration is open
|
||||
by default), are untrusted.
|
||||
|
||||
- **JSON API** `routes/api.php` (`/api/v1/...`), authenticated via Passport (session cookie or personal access token).
|
||||
Most routes are scoped by `{organization}` and authorised in the controllers / form requests.
|
||||
- **Public, unauthenticated** endpoints: `GET /api/v1/public/reports` (shared reports, accessed by a secret), login,
|
||||
registration, password reset, email verification, organization invitation acceptance (`routes/web.php`).
|
||||
- **Web / Inertia routes** `routes/web.php` and Fortify/Jetstream actions in `app/Actions`.
|
||||
- **Imports** (`app/Service/Import/Importers`): user-uploaded CSV and ZIP files from Toggl, Clockify, Harvest,
|
||||
generic CSV and solidtime's own export format. ZIP handling is in `ZipImportHelper.php`.
|
||||
- **Exports / reports** (`app/Service/Export`, `app/Service/ReportExport`): CSV/XLSX/ODS and PDF. PDFs are rendered by
|
||||
sending HTML to a Gotenberg (headless Chromium) service, so user-controlled content in that HTML matters.
|
||||
- **OAuth** (Passport) authorization and token endpoints.
|
||||
- **Filament admin panel** (`app/Filament`): only its access control is in scope (see Trust boundaries).
|
||||
|
||||
## Components that matter most / least
|
||||
|
||||
Most important: organization scoping and role checks in the API controllers, form requests (`app/Http/Requests`),
|
||||
`PermissionStore`, public report sharing, invitations and member management (role changes, ownership transfer, member
|
||||
merge), authentication flows (Fortify, 2FA, email change, API tokens), import parsing.
|
||||
|
||||
Less important / out of scope:
|
||||
- `extensions/` is empty in this repository (proprietary modules are not part of the open-source code).
|
||||
- `docker/`, `k8s/`, `e2e/`, `playwright/`, `docs/` and developer tooling.
|
||||
- Third-party dependencies in `vendor/` and `node_modules/`, unless solidtime uses them in an unsafe way.
|
||||
|
||||
## How to exercise it
|
||||
|
||||
- `.oss-scanner/start-postgres.sh` starts the local PostgreSQL server (user `root`, password `root`, db `laravel`).
|
||||
- `.oss-scanner/start-gotenberg.sh` starts the local Gotenberg server (PDF rendering via headless Chromium) on
|
||||
http://127.0.0.1:3000, so the PDF export code path, including what Chromium does with the rendered HTML, can be
|
||||
exercised.
|
||||
- `php artisan test` runs the PHPUnit suite (start PostgreSQL and Gotenberg first); all tests are expected to pass. Endpoint tests in `tests/Unit/Endpoint/Api/V1/` show how to create users,
|
||||
organizations and members with factories and call the API with a given role; they are the quickest way to write a
|
||||
reproducer. Example: `php artisan test --filter=TimeEntryEndpointTest`.
|
||||
- To run the app like production: `.oss-scanner/start-octane.sh` (http://127.0.0.1:8000). It starts PostgreSQL and
|
||||
Gotenberg, migrates (and seeds an empty database, see `database/seeders/DatabaseSeeder.php` for the users) and runs
|
||||
Octane/FrankenPHP with the production Caddyfile and a **single worker**, so consecutive requests always hit the same
|
||||
worker and leaks between requests reproduce reliably. Workers keep the code they booted with: after changing PHP
|
||||
code run `php artisan octane:reload`. Stop it with `php artisan octane:stop`. Note that the test suite and the app
|
||||
share the same database, so `php artisan test` wipes the app's data.
|
||||
- A reproducer for a leak between requests is a script that sends request A (e.g. as a member of organization X) and
|
||||
then request B (as a user of organization Y) to the running Octane server and shows that B observes A's state. API
|
||||
requests can be authenticated with a personal access token, e.g. created with
|
||||
`php artisan tinker --execute="echo App\Models\User::where('email', '...')->first()->createToken('t')->accessToken;"`.
|
||||
- There is no network: mail delivery is not available (mail uses the `array` driver in tests), and remote resources
|
||||
referenced by PDF templates (e.g. fonts from fonts.bunny.net) fail to load, so PDFs fall back to local fonts.
|
||||
|
||||
## How we rate severity
|
||||
|
||||
- **Critical**: unauthenticated access to other users' data or accounts; authentication bypass; remote code execution;
|
||||
SQL injection reachable by any registered user; reading or writing data of an organization the attacker is not a
|
||||
member of, including through state leaking between requests in an Octane worker.
|
||||
- **High**: privilege escalation within an organization (e.g. employee to admin/owner, or performing admin-only
|
||||
actions); access to data the role must not see (other members' time entries, billable rates, member emails) when
|
||||
the organization settings do not allow it; stored XSS that executes in another user's session; SSRF via PDF
|
||||
rendering or imports; account takeover requiring user interaction.
|
||||
- **Medium**: information disclosure with limited impact, CSRF on state-changing endpoints, issues requiring an
|
||||
unusual but realistic configuration, denial of service by a single authenticated request (e.g. pathological
|
||||
import file).
|
||||
- **Low**: everything else with real security impact.
|
||||
|
||||
## Anything to leave alone
|
||||
|
||||
Please do not report (see also `SECURITY.md`):
|
||||
- Theoretical findings without a working reproducer.
|
||||
- Missing or weak security headers in isolation; TLS / mail DNS configuration.
|
||||
- Self-XSS; CSRF on non-state-changing endpoints (logout, theme).
|
||||
- CSV / spreadsheet formula injection in exports.
|
||||
- Owners or admins acting destructively within their own organization.
|
||||
- Anything requiring direct DB, shell or filesystem access on a self-hosted instance.
|
||||
- Anything that requires being a super admin, including issues inside the Filament admin panel.
|
||||
- Missing OAuth scope enforcement (not implemented yet).
|
||||
- Rate-limit tuning and generic DoS through volume of requests.
|
||||
|
||||
## Reports and patches
|
||||
|
||||
Please include the affected endpoint or code path, the attacker's role and the victim, a PHPUnit test (in the style of
|
||||
`tests/Unit/Endpoint/Api/V1/`) that reproduces the issue (for leaks between requests: a script against
|
||||
`.oss-scanner/start-octane.sh` instead), and a minimal patch that follows the existing patterns
|
||||
(authorisation in form requests/controllers via `PermissionStore`).
|
||||
@@ -6,7 +6,19 @@ Contributions are greatly apprecited, please make sure to read the rules and vis
|
||||
|
||||
### Issues for Bugs, Discussions for Feature requests
|
||||
|
||||
In order to keep the issues of the repository clean we decided to only use them for bugs. Feature Requests and enhancement are handled in discussions. This also helps us to see which feature requests are popular as they can be upvoted.
|
||||
In order to keep the issues of the repository clean we decided to only use them for bugs. Feature Requests and enhancements are handled in discussions. This also helps us to see which feature requests are popular as they can be upvoted.
|
||||
|
||||
### Do not use AI-generated text in issues, discussions and PR descriptions
|
||||
|
||||
We are human, so please write in natural language in your issues, discussions, and PR descriptions.
|
||||
Don't be a meatproxy. We will ban people who repeatedly violate this rule from further communication on our repositories.
|
||||
|
||||
### Before you contribute, ask yourself what value you add
|
||||
|
||||
We much prefer reading your thoughts on features or issues you encountered than reading through hundreds of lines of code changes produced by your agent.
|
||||
Consider that the maintainers of this project have the same access to LLMs and more knowledge about the project itself.
|
||||
Prompting a feature into existence without further consideration or discussion is mostly a burden for maintainers.
|
||||
If we want to, we can burn the tokens ourselves.
|
||||
|
||||
### Only work on approved issues
|
||||
|
||||
|
||||
12
README.md
12
README.md
@@ -30,8 +30,16 @@ If you do not want to self-host solidtime or try it out you can sign up for [sol
|
||||
|
||||
## Issues & Feature Requests
|
||||
|
||||
If you find any **bugs in solidtime**, please feel free to [**open an issue**](https://github.com/solidtime-io/solidtime/issues/new) in this repository, with instructions on how to reproduce the bug.
|
||||
If you have a **feature request**, please [**create a discussion**](https://github.com/solidtime-io/solidtime/discussions/new?category=feature-requests) in this repository.
|
||||
If you
|
||||
* find any **bugs in solidtime**, please feel free to [**open an issue**](https://github.com/solidtime-io/solidtime/issues/new) in this repository, with instructions on how to reproduce the bug.
|
||||
* have a **feature request**, please [**create a discussion**](https://github.com/solidtime-io/solidtime/discussions/new?category=feature-requests) in this repository.
|
||||
|
||||
|
||||
> **Do not use AI-generated text in issues, discussions and PR descriptions.**
|
||||
>
|
||||
> We are human, so please write in natural language in your issues, discussions, and PR descriptions.
|
||||
> Don't be a meatproxy. We will ban people who repeatedly violate this rule from further communication on our repositories.
|
||||
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands\Correction;
|
||||
|
||||
use App\Jobs\RecalculateSpentTimeForProject;
|
||||
use App\Jobs\RecalculateSpentTimeForTask;
|
||||
use App\Models\TimeEntry;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class CorrectionDeleteTimeEntriesWithEndBeforeStartCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'correction:delete-time-entries-with-end-before-start '.
|
||||
' { --dry-run : Do not actually save anything to the database, just output what would happen }';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Deletes all time entries where the end is before the start';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$this->comment('Deletes all time entries where the end is before the start...');
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
if ($dryRun) {
|
||||
$this->comment('Running in dry-run mode. Nothing will be saved to the database.');
|
||||
}
|
||||
|
||||
$timeEntries = TimeEntry::query()
|
||||
->whereNotNull('end')
|
||||
->whereColumn('end', '<', 'start')
|
||||
->with(['project', 'task'])
|
||||
->get();
|
||||
foreach ($timeEntries as $timeEntry) {
|
||||
/** @var TimeEntry $timeEntry */
|
||||
if (! $dryRun) {
|
||||
// Delete via Eloquent, so that the deletion is audited
|
||||
$timeEntry->delete();
|
||||
if ($timeEntry->project !== null) {
|
||||
RecalculateSpentTimeForProject::dispatch($timeEntry->project);
|
||||
}
|
||||
if ($timeEntry->task !== null) {
|
||||
RecalculateSpentTimeForTask::dispatch($timeEntry->task);
|
||||
}
|
||||
}
|
||||
$this->line('Deleted time entry (id='.$timeEntry->getKey().', start='.$timeEntry->start->toIso8601ZuluString().', end='.$timeEntry->end?->toIso8601ZuluString().')');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class SelfHostDatabaseConsistency extends Command
|
||||
$problems = DB::table('time_entries')
|
||||
->select(['time_entries.id as id'])
|
||||
->join('tasks', 'time_entries.task_id', '=', 'tasks.id')
|
||||
->where('tasks.project_id', '!=', DB::raw('time_entries.project_id'))
|
||||
->whereRaw('tasks.project_id is distinct from time_entries.project_id')
|
||||
->get();
|
||||
$this->logProblems($problems, 'Time entries have a task that does not belong to the project of the time entry', $hadAProblem);
|
||||
|
||||
@@ -59,6 +59,14 @@ class SelfHostDatabaseConsistency extends Command
|
||||
->get();
|
||||
$this->logProblems($problems, 'Time entries have a client but no project', $hadAProblem);
|
||||
|
||||
// End of time entries can not be before the start
|
||||
$problems = DB::table('time_entries')
|
||||
->select(['id'])
|
||||
->whereNotNull('end')
|
||||
->whereColumn('end', '<', 'start')
|
||||
->get();
|
||||
$this->logProblems($problems, 'Time entries have an end that is before the start', $hadAProblem);
|
||||
|
||||
// Every user needs to be a member of at least one organization
|
||||
$problems = DB::table('users')
|
||||
->select(['users.id as id'])
|
||||
|
||||
22
app/Enums/GoalComparison.php
Normal file
22
app/Enums/GoalComparison.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
|
||||
|
||||
enum GoalComparison: string
|
||||
{
|
||||
use LaravelEnumHelper;
|
||||
|
||||
/**
|
||||
* The goal is reached when at least the target amount of time was tracked in the period.
|
||||
*/
|
||||
case AtLeast = 'at_least';
|
||||
|
||||
/**
|
||||
* The goal is reached when less than the target amount of time was tracked in the period.
|
||||
*/
|
||||
case LessThan = 'less_than';
|
||||
}
|
||||
16
app/Enums/GoalPeriod.php
Normal file
16
app/Enums/GoalPeriod.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
|
||||
|
||||
enum GoalPeriod: string
|
||||
{
|
||||
use LaravelEnumHelper;
|
||||
|
||||
case Day = 'day';
|
||||
case Week = 'week';
|
||||
case Month = 'month';
|
||||
}
|
||||
32
app/Enums/GoalStatus.php
Normal file
32
app/Enums/GoalStatus.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
|
||||
|
||||
enum GoalStatus: string
|
||||
{
|
||||
use LaravelEnumHelper;
|
||||
|
||||
/**
|
||||
* "At least" goal, the target has not been reached yet in the current period.
|
||||
*/
|
||||
case InProgress = 'in_progress';
|
||||
|
||||
/**
|
||||
* "At least" goal, the target has been reached in the current period.
|
||||
*/
|
||||
case Achieved = 'achieved';
|
||||
|
||||
/**
|
||||
* "Less than" goal, the tracked time is still below the limit.
|
||||
*/
|
||||
case OnTrack = 'on_track';
|
||||
|
||||
/**
|
||||
* "Less than" goal, the tracked time reached or exceeded the limit.
|
||||
*/
|
||||
case Exceeded = 'exceeded';
|
||||
}
|
||||
24
app/Enums/GoalType.php
Normal file
24
app/Enums/GoalType.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
|
||||
|
||||
enum GoalType: string
|
||||
{
|
||||
use LaravelEnumHelper;
|
||||
|
||||
/**
|
||||
* A goal a member set for themselves. Only that member can see and manage it, no permission reaches it.
|
||||
*/
|
||||
case Personal = 'personal';
|
||||
|
||||
/**
|
||||
* A goal the organization set for a member or for the whole organization.
|
||||
* Managed by the members that may manage goals, visible to them and to the member the goal is for.
|
||||
* Requires the team goals extension.
|
||||
*/
|
||||
case Organization = 'organization';
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exceptions\Api;
|
||||
|
||||
class TimeEntryMemberCanNotBeChangedWhileRunningApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'time_entry_member_can_not_be_changed_while_running';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
174
app/Filament/Resources/GoalResource.php
Normal file
174
app/Filament/Resources/GoalResource.php
Normal file
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Enums\GoalComparison;
|
||||
use App\Enums\GoalPeriod;
|
||||
use App\Enums\GoalType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Filament\Resources\GoalResource\Pages;
|
||||
use App\Models\Goal;
|
||||
use App\Service\Dto\GoalFiltersDto;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Forms;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Novadaemon\FilamentPrettyJson\Form\PrettyJsonField;
|
||||
|
||||
class GoalResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Goal::class;
|
||||
|
||||
protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-viewfinder-circle';
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Timetracking';
|
||||
|
||||
protected static ?int $navigationSort = 8;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(1)
|
||||
->components([
|
||||
Forms\Components\TextInput::make('name')
|
||||
->label('Name')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
Forms\Components\Select::make('type')
|
||||
->label('Type')
|
||||
->options(collect(GoalType::cases())->mapWithKeys(fn (GoalType $type): array => [$type->value => $type->name])->all())
|
||||
->disabled()
|
||||
->required(),
|
||||
Forms\Components\Select::make('comparison')
|
||||
->label('Comparison')
|
||||
->options(collect(GoalComparison::cases())->mapWithKeys(fn (GoalComparison $comparison): array => [$comparison->value => $comparison->name])->all())
|
||||
->required(),
|
||||
Forms\Components\TextInput::make('target_seconds')
|
||||
->label('Target (seconds)')
|
||||
->numeric()
|
||||
->minValue(1)
|
||||
->required(),
|
||||
Forms\Components\Select::make('period')
|
||||
->label('Period')
|
||||
->options(collect(GoalPeriod::cases())->mapWithKeys(fn (GoalPeriod $period): array => [$period->value => $period->name])->all())
|
||||
->required(),
|
||||
Forms\Components\Select::make('timezone')
|
||||
->label('Timezone')
|
||||
->options(fn (): array => collect(\DateTimeZone::listIdentifiers())->mapWithKeys(fn (string $timezone): array => [$timezone => $timezone])->all())
|
||||
->searchable()
|
||||
->required(),
|
||||
Forms\Components\Select::make('week_start')
|
||||
->label('Week start')
|
||||
->options(collect(Weekday::cases())->mapWithKeys(fn (Weekday $weekday): array => [$weekday->value => $weekday->name])->all())
|
||||
->required(),
|
||||
DateTimePicker::make('archived_at')
|
||||
->label('Archived At'),
|
||||
Forms\Components\Select::make('organization_id')
|
||||
->label('Organization')
|
||||
->relationship(name: 'organization', titleAttribute: 'name')
|
||||
->searchable(['name'])
|
||||
->disabled()
|
||||
->required(),
|
||||
Forms\Components\Select::make('member_id')
|
||||
->label('Member (empty = every member)')
|
||||
->relationship(name: 'member', titleAttribute: 'id')
|
||||
->disabled(),
|
||||
PrettyJsonField::make('filters')
|
||||
->formatStateUsing(function (GoalFiltersDto $state, Goal $record): string {
|
||||
return $record->getRawOriginal('filters');
|
||||
})
|
||||
->disabled(),
|
||||
DateTimePicker::make('created_at')
|
||||
->label('Created At')
|
||||
->hiddenOn(['create'])
|
||||
->disabled(),
|
||||
DateTimePicker::make('updated_at')
|
||||
->label('Updated At')
|
||||
->hiddenOn(['create'])
|
||||
->disabled(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('comparison')
|
||||
->sortable(),
|
||||
TextColumn::make('target_seconds')
|
||||
->label('Target')
|
||||
->formatStateUsing(fn (int $state): string => sprintf('%dh %02dm', intdiv($state, 3600), intdiv($state % 3600, 60)))
|
||||
->sortable(),
|
||||
TextColumn::make('period')
|
||||
->sortable(),
|
||||
TextColumn::make('type')
|
||||
->sortable(),
|
||||
TextColumn::make('member.user.email')
|
||||
->label('Member')
|
||||
->placeholder('Every member')
|
||||
->searchable(),
|
||||
TextColumn::make('archived_at')
|
||||
->dateTime()
|
||||
->placeholder('Not archived')
|
||||
->sortable()
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
TextColumn::make('organization.name')
|
||||
->searchable()
|
||||
->sortable(),
|
||||
TextColumn::make('created_at')
|
||||
->dateTime()
|
||||
->sortable(),
|
||||
TextColumn::make('updated_at')
|
||||
->dateTime()
|
||||
->sortable()
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->defaultSort('created_at', 'desc')
|
||||
->filters([
|
||||
SelectFilter::make('type')
|
||||
->label('Type')
|
||||
->options(collect(GoalType::cases())->mapWithKeys(fn (GoalType $type): array => [$type->value => $type->name])->all()),
|
||||
SelectFilter::make('organization')
|
||||
->label('Organization')
|
||||
->relationship('organization', 'name')
|
||||
->searchable(),
|
||||
SelectFilter::make('organization_id')
|
||||
->label('Organization ID')
|
||||
->relationship('organization', 'id')
|
||||
->searchable(),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
EditAction::make(),
|
||||
DeleteAction::make(),
|
||||
])
|
||||
->toolbarActions([
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => Pages\ListGoals::route('/'),
|
||||
'edit' => Pages\EditGoal::route('/{record}/edit'),
|
||||
'view' => Pages\ViewGoal::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
22
app/Filament/Resources/GoalResource/Pages/EditGoal.php
Normal file
22
app/Filament/Resources/GoalResource/Pages/EditGoal.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\GoalResource\Pages;
|
||||
|
||||
use App\Filament\Resources\GoalResource;
|
||||
use Filament\Actions;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditGoal extends EditRecord
|
||||
{
|
||||
protected static string $resource = GoalResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Actions\DeleteAction::make()
|
||||
->icon('heroicon-m-trash'),
|
||||
];
|
||||
}
|
||||
}
|
||||
19
app/Filament/Resources/GoalResource/Pages/ListGoals.php
Normal file
19
app/Filament/Resources/GoalResource/Pages/ListGoals.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\GoalResource\Pages;
|
||||
|
||||
use App\Filament\Resources\GoalResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListGoals extends ListRecords
|
||||
{
|
||||
protected static string $resource = GoalResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
];
|
||||
}
|
||||
}
|
||||
22
app/Filament/Resources/GoalResource/Pages/ViewGoal.php
Normal file
22
app/Filament/Resources/GoalResource/Pages/ViewGoal.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\GoalResource\Pages;
|
||||
|
||||
use App\Filament\Resources\GoalResource;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
|
||||
class ViewGoal extends ViewRecord
|
||||
{
|
||||
protected static string $resource = GoalResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
EditAction::make('edit')
|
||||
->icon('heroicon-s-pencil'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -183,7 +183,7 @@ class OrganizationResource extends Resource
|
||||
->action(function (Organization $record, array $data): void {
|
||||
try {
|
||||
try {
|
||||
$file = Storage::disk(config('filament.default_filesystem_disk'))->get($data['file']);
|
||||
$file = Storage::disk(config('filesystems.private'))->get($data['file']);
|
||||
} catch (UnableToReadFile) {
|
||||
$file = null;
|
||||
}
|
||||
@@ -220,12 +220,17 @@ class OrganizationResource extends Resource
|
||||
->body('Message: '.$exception->getMessage())
|
||||
->persistent()
|
||||
->send();
|
||||
} finally {
|
||||
Storage::disk(config('filesystems.private'))->delete($data['file']);
|
||||
}
|
||||
})
|
||||
->tooltip(fn (Organization $record): string => 'Import into '.$record->name)
|
||||
->schema([
|
||||
FileUpload::make('file')
|
||||
->label('File')
|
||||
->disk(config('filesystems.private'))
|
||||
->directory('admin-import-uploads')
|
||||
->visibility('private')
|
||||
->required(),
|
||||
Select::make('type')
|
||||
->required()
|
||||
|
||||
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\Role;
|
||||
use App\Models\Organization;
|
||||
use App\Service\BillableRateService;
|
||||
use App\Service\DashboardService;
|
||||
use App\Service\PermissionStore;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
@@ -154,12 +154,12 @@ class ChartController extends Controller
|
||||
*
|
||||
* @response array{value: int, currency: string}
|
||||
*/
|
||||
public function totalWeeklyBillableAmount(Organization $organization, DashboardService $dashboardService): JsonResponse
|
||||
public function totalWeeklyBillableAmount(Organization $organization, DashboardService $dashboardService, BillableRateService $billableRateService): JsonResponse
|
||||
{
|
||||
$this->checkPermission($organization, 'charts:view:own');
|
||||
$user = $this->user();
|
||||
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
$showBillableRate = $billableRateService->canSeeBillableRates($organization, $this->member($organization));
|
||||
if (! $showBillableRate) {
|
||||
throw new AuthorizationException('You do not have permission to view billable rates.');
|
||||
}
|
||||
|
||||
@@ -49,4 +49,9 @@ class Controller extends \App\Http\Controllers\Controller
|
||||
{
|
||||
return app(BillingContract::class)->hasSubscription($organization) || app(BillingContract::class)->hasTrial($organization);
|
||||
}
|
||||
|
||||
protected function canUseBillableRates(Organization $organization): bool
|
||||
{
|
||||
return app(BillingContract::class)->canUseBillableRates($organization);
|
||||
}
|
||||
}
|
||||
|
||||
241
app/Http/Controllers/Api/V1/GoalController.php
Normal file
241
app/Http/Controllers/Api/V1/GoalController.php
Normal file
@@ -0,0 +1,241 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\GoalType;
|
||||
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
|
||||
use App\Http\Requests\V1\Goal\GoalIndexRequest;
|
||||
use App\Http\Requests\V1\Goal\GoalStoreRequest;
|
||||
use App\Http\Requests\V1\Goal\GoalUpdateRequest;
|
||||
use App\Http\Resources\V1\Goal\GoalCollection;
|
||||
use App\Http\Resources\V1\Goal\GoalResource;
|
||||
use App\Models\Goal;
|
||||
use App\Models\Organization;
|
||||
use App\Service\BillingContract;
|
||||
use App\Service\GoalProgressService;
|
||||
use App\Service\GoalsContract;
|
||||
use App\Service\TimezoneService;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class GoalController extends Controller
|
||||
{
|
||||
/**
|
||||
* @throws AuthorizationException
|
||||
*/
|
||||
protected function checkPermission(Organization $organization, string $permission, ?Goal $goal = null): void
|
||||
{
|
||||
parent::checkPermission($organization, $permission);
|
||||
if ($goal !== null) {
|
||||
$this->checkGoalBelongsToOrganization($organization, $goal);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws AuthorizationException
|
||||
*/
|
||||
private function checkGoalBelongsToOrganization(Organization $organization, Goal $goal): void
|
||||
{
|
||||
if ($goal->organization_id !== $organization->id) {
|
||||
throw new AuthorizationException('Goal does not belong to organization');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforces the goal limit provided by the BillingContract, if any. Archived goals count toward the limit.
|
||||
*
|
||||
* @throws FeatureIsNotAvailableInFreePlanApiException
|
||||
*/
|
||||
private function checkGoalLimit(Organization $organization): void
|
||||
{
|
||||
$limit = app(BillingContract::class)->getGoalLimit($organization);
|
||||
if ($limit === null) {
|
||||
return;
|
||||
}
|
||||
$goals = Goal::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->count();
|
||||
if ($goals >= $limit) {
|
||||
throw new FeatureIsNotAvailableInFreePlanApiException;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get goals
|
||||
*
|
||||
* Returns the goals the current member is allowed to see, including the progress in the current period.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId getGoals
|
||||
*/
|
||||
public function index(Organization $organization, GoalIndexRequest $request, GoalsContract $access, GoalProgressService $progressService): GoalCollection
|
||||
{
|
||||
// An organization goal is visible to the member it is for, who does not hold the :organization-type permission.
|
||||
// Either permission is enough, the access contract decides which goals come back.
|
||||
$this->checkAnyPermission($organization, ['goals:view:own', 'goals:view:organization-type']);
|
||||
$member = $this->member($organization);
|
||||
|
||||
$query = Goal::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->with(['member.user'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->orderBy('id');
|
||||
$query = $access->scopeVisibleGoals($query, $member);
|
||||
if ($request->getType() !== null) {
|
||||
$query->where('type', '=', $request->getType()->value);
|
||||
}
|
||||
if ($request->getArchivedFilter() === 'true') {
|
||||
$query->archived();
|
||||
} elseif ($request->getArchivedFilter() === 'false') {
|
||||
$query->notArchived();
|
||||
}
|
||||
|
||||
$goals = $query->paginate(config('app.pagination_per_page_default'));
|
||||
$progressByGoalId = $progressService->getCurrentProgressForGoals($goals->getCollection(), Carbon::now());
|
||||
|
||||
return new GoalCollection($goals, $progressByGoalId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get goal
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId getGoal
|
||||
*/
|
||||
public function show(Organization $organization, Goal $goal, GoalsContract $access, GoalProgressService $progressService): GoalResource
|
||||
{
|
||||
// Either permission is enough, see index
|
||||
$this->checkAnyPermission($organization, ['goals:view:own', 'goals:view:organization-type']);
|
||||
$this->checkGoalBelongsToOrganization($organization, $goal);
|
||||
$member = $this->member($organization);
|
||||
if (! $access->canViewGoal($member, $goal)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
$goal->load('member.user');
|
||||
|
||||
return new GoalResource($goal, $progressService->getCurrentProgress($goal, Carbon::now()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create goal
|
||||
*
|
||||
* @throws AuthorizationException|FeatureIsNotAvailableInFreePlanApiException
|
||||
*
|
||||
* @operationId createGoal
|
||||
*/
|
||||
public function store(Organization $organization, GoalStoreRequest $request, GoalsContract $access, GoalProgressService $progressService): JsonResponse
|
||||
{
|
||||
if ($request->getType() === GoalType::Personal) {
|
||||
$this->checkPermission($organization, 'goals:create:own');
|
||||
} else {
|
||||
$this->checkPermission($organization, 'goals:create:organization-type');
|
||||
}
|
||||
$member = $this->member($organization);
|
||||
|
||||
$type = $request->getType();
|
||||
$targetMemberId = $request->hasMemberId() ? $request->getMemberId() : $member->getKey();
|
||||
if (! $access->canCreateGoal($member, $type, $targetMemberId)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
$this->checkGoalLimit($organization);
|
||||
|
||||
$user = $member->user;
|
||||
$goal = new Goal;
|
||||
$goal->name = $request->getName();
|
||||
$goal->type = $type;
|
||||
$goal->comparison = $request->getComparison();
|
||||
$goal->target_seconds = $request->getTargetSeconds();
|
||||
$goal->period = $request->getPeriod();
|
||||
$goal->filters = $request->getFilters();
|
||||
$goal->timezone = $request->getTimezone() ?? app(TimezoneService::class)->getTimezoneFromUser($user)->getName();
|
||||
$goal->week_start = $request->getWeekStart() ?? $user->week_start;
|
||||
$goal->organization()->associate($organization);
|
||||
$goal->member_id = $targetMemberId;
|
||||
$goal->save();
|
||||
$goal->load('member.user');
|
||||
|
||||
return (new GoalResource($goal, $progressService->getCurrentProgress($goal, Carbon::now())))
|
||||
->response()
|
||||
->setStatusCode(201);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update goal
|
||||
*
|
||||
* The type of a goal and the member it is for can not be changed after creation.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId updateGoal
|
||||
*/
|
||||
public function update(Organization $organization, Goal $goal, GoalUpdateRequest $request, GoalsContract $access, GoalProgressService $progressService): GoalResource
|
||||
{
|
||||
if ($goal->type === GoalType::Personal) {
|
||||
$this->checkPermission($organization, 'goals:update:own', $goal);
|
||||
} else {
|
||||
$this->checkPermission($organization, 'goals:update:organization-type', $goal);
|
||||
}
|
||||
$member = $this->member($organization);
|
||||
if (! $access->canUpdateGoal($member, $goal)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
if ($request->has('filters')) {
|
||||
$goal->filters = $request->getFilters();
|
||||
}
|
||||
|
||||
if ($request->has('name')) {
|
||||
$goal->name = $request->getName();
|
||||
}
|
||||
if ($request->has('comparison')) {
|
||||
$goal->comparison = $request->getComparison();
|
||||
}
|
||||
if ($request->has('target_seconds')) {
|
||||
$goal->target_seconds = $request->getTargetSeconds();
|
||||
}
|
||||
if ($request->has('period')) {
|
||||
$goal->period = $request->getPeriod();
|
||||
}
|
||||
if ($request->has('timezone')) {
|
||||
$goal->timezone = $request->getTimezone();
|
||||
}
|
||||
if ($request->has('week_start')) {
|
||||
$goal->week_start = $request->getWeekStart();
|
||||
}
|
||||
if ($request->has('is_archived')) {
|
||||
$goal->archived_at = $request->getIsArchived() ? Carbon::now() : null;
|
||||
}
|
||||
$goal->save();
|
||||
$goal->load('member.user');
|
||||
|
||||
return new GoalResource($goal, $progressService->getCurrentProgress($goal, Carbon::now()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete goal
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId deleteGoal
|
||||
*/
|
||||
public function destroy(Organization $organization, Goal $goal, GoalsContract $access): JsonResponse
|
||||
{
|
||||
if ($goal->type === GoalType::Personal) {
|
||||
$this->checkPermission($organization, 'goals:delete:own', $goal);
|
||||
} else {
|
||||
$this->checkPermission($organization, 'goals:delete:organization-type', $goal);
|
||||
}
|
||||
$member = $this->member($organization);
|
||||
if (! $access->canDeleteGoal($member, $goal)) {
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
$goal->delete();
|
||||
|
||||
return response()->json(null, 204);
|
||||
}
|
||||
}
|
||||
@@ -81,10 +81,9 @@ class MemberController extends Controller
|
||||
{
|
||||
$this->checkPermission($organization, 'members:update', $member);
|
||||
|
||||
if ($request->has('billable_rate') && $member->billable_rate !== $request->getBillableRate()) {
|
||||
$oldBillableRate = $member->billable_rate;
|
||||
if ($request->has('billable_rate') && $this->canUseBillableRates($organization)) {
|
||||
$member->billable_rate = $request->getBillableRate();
|
||||
|
||||
$billableRateService->updateTimeEntriesBillableRateForMember($member);
|
||||
}
|
||||
if ($request->has('role') && $member->role !== $request->getRole()->value) {
|
||||
$newRole = $request->getRole();
|
||||
@@ -93,6 +92,10 @@ class MemberController extends Controller
|
||||
}
|
||||
$member->save();
|
||||
|
||||
if ($oldBillableRate !== $member->billable_rate) {
|
||||
$billableRateService->updateTimeEntriesBillableRateForMember($member);
|
||||
}
|
||||
|
||||
return new MemberResource($member);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\Role;
|
||||
use App\Events\AfterCreateOrganization;
|
||||
use App\Http\Requests\V1\Organization\OrganizationDestroyRequest;
|
||||
use App\Http\Requests\V1\Organization\OrganizationStoreRequest;
|
||||
@@ -28,11 +27,11 @@ class OrganizationController extends Controller
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*/
|
||||
public function show(Organization $organization): OrganizationResource
|
||||
public function show(Organization $organization, BillableRateService $billableRateService): OrganizationResource
|
||||
{
|
||||
$this->checkPermission($organization, 'organizations:view');
|
||||
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
$showBillableRate = $billableRateService->canSeeBillableRates($organization, $this->member($organization));
|
||||
|
||||
return new OrganizationResource($organization, $showBillableRate);
|
||||
}
|
||||
@@ -47,6 +46,7 @@ class OrganizationController extends Controller
|
||||
public function update(Organization $organization, OrganizationUpdateRequest $request, BillableRateService $billableRateService): OrganizationResource
|
||||
{
|
||||
$this->checkPermission($organization, 'organizations:update');
|
||||
$canUseBillableRates = $this->canUseBillableRates($organization);
|
||||
|
||||
if ($request->getName() !== null) {
|
||||
$organization->name = $request->getName();
|
||||
@@ -54,7 +54,8 @@ class OrganizationController extends Controller
|
||||
if ($request->getCurrency() !== null) {
|
||||
$organization->currency = $request->getCurrency();
|
||||
}
|
||||
if ($request->getEmployeesCanSeeBillableRates() !== null) {
|
||||
// Organizations that can not use billable rates can keep or remove the visibility for employees, but not enable it
|
||||
if ($request->getEmployeesCanSeeBillableRates() !== null && ($canUseBillableRates || ! $request->getEmployeesCanSeeBillableRates())) {
|
||||
$organization->employees_can_see_billable_rates = $request->getEmployeesCanSeeBillableRates();
|
||||
}
|
||||
if ($request->getEmployeesCanManageTasks() !== null) {
|
||||
@@ -81,14 +82,13 @@ class OrganizationController extends Controller
|
||||
if ($request->getBreaksEnabled() !== null) {
|
||||
$organization->breaks_enabled = $request->getBreaksEnabled();
|
||||
}
|
||||
$hasBillableRate = $request->has('billable_rate');
|
||||
if ($hasBillableRate) {
|
||||
$oldBillableRate = $organization->billable_rate;
|
||||
if ($request->has('billable_rate') && $canUseBillableRates) {
|
||||
$organization->billable_rate = $request->getBillableRate();
|
||||
}
|
||||
$organization->save();
|
||||
|
||||
if ($hasBillableRate && $oldBillableRate !== $request->getBillableRate()) {
|
||||
if ($oldBillableRate !== $organization->billable_rate) {
|
||||
$billableRateService->updateTimeEntriesBillableRateForOrganization($organization);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\Role;
|
||||
use App\Exceptions\Api\EntityStillInUseApiException;
|
||||
use App\Http\Requests\V1\Project\ProjectIndexRequest;
|
||||
use App\Http\Requests\V1\Project\ProjectStoreRequest;
|
||||
@@ -39,7 +38,7 @@ class ProjectController extends Controller
|
||||
*
|
||||
* @operationId getProjects
|
||||
*/
|
||||
public function index(Organization $organization, ProjectIndexRequest $request): ProjectCollection
|
||||
public function index(Organization $organization, ProjectIndexRequest $request, BillableRateService $billableRateService): ProjectCollection
|
||||
{
|
||||
$this->checkPermission($organization, 'projects:view');
|
||||
$canViewAllProjects = $this->hasPermission($organization, 'projects:view:all');
|
||||
@@ -63,7 +62,7 @@ class ProjectController extends Controller
|
||||
->orderBy('id')
|
||||
->paginate(config('app.pagination_per_page_default'));
|
||||
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
$showBillableRate = $billableRateService->canSeeBillableRates($organization, $this->member($organization));
|
||||
|
||||
return new ProjectCollection($projects, $showBillableRate);
|
||||
}
|
||||
@@ -97,11 +96,12 @@ class ProjectController extends Controller
|
||||
public function store(Organization $organization, ProjectStoreRequest $request): JsonResource
|
||||
{
|
||||
$this->checkPermission($organization, 'projects:create');
|
||||
$canUseBillableRates = $this->canUseBillableRates($organization);
|
||||
$project = new Project;
|
||||
$project->name = $request->input('name');
|
||||
$project->color = $request->input('color');
|
||||
$project->is_billable = (bool) $request->input('is_billable');
|
||||
$project->billable_rate = $request->getBillableRate();
|
||||
$project->is_billable = $canUseBillableRates && $request->boolean('is_billable');
|
||||
$project->billable_rate = $canUseBillableRates ? $request->getBillableRate() : null;
|
||||
$project->client_id = $request->input('client_id');
|
||||
$project->is_public = $request->getIsPublic();
|
||||
if ($this->canAccessPremiumFeatures($organization) && $request->has('estimated_time')) {
|
||||
@@ -123,9 +123,13 @@ class ProjectController extends Controller
|
||||
public function update(Organization $organization, Project $project, ProjectUpdateRequest $request, BillableRateService $billableRateService): JsonResource
|
||||
{
|
||||
$this->checkPermission($organization, 'projects:update', $project);
|
||||
$canUseBillableRates = $this->canUseBillableRates($organization);
|
||||
$project->name = $request->input('name');
|
||||
$project->color = $request->input('color');
|
||||
$project->is_billable = (bool) $request->input('is_billable');
|
||||
// Organizations that can not use billable rates can keep or remove the billable flag, but not set it
|
||||
if ($canUseBillableRates || ! $request->boolean('is_billable')) {
|
||||
$project->is_billable = $request->boolean('is_billable');
|
||||
}
|
||||
if ($request->has('is_archived')) {
|
||||
$project->archived_at = $request->getIsArchived() ? Carbon::now() : null;
|
||||
}
|
||||
@@ -137,14 +141,16 @@ class ProjectController extends Controller
|
||||
}
|
||||
$oldBillableRate = $project->billable_rate;
|
||||
$clientIdChanged = false;
|
||||
if ($request->has('billable_rate') && $canUseBillableRates) {
|
||||
$project->billable_rate = $request->getBillableRate();
|
||||
}
|
||||
if ($project->client_id !== $request->input('client_id')) {
|
||||
$project->client_id = $request->input('client_id');
|
||||
$clientIdChanged = true;
|
||||
}
|
||||
$project->save();
|
||||
|
||||
if ($oldBillableRate !== $request->getBillableRate()) {
|
||||
if ($oldBillableRate !== $project->billable_rate) {
|
||||
$billableRateService->updateTimeEntriesBillableRateForProject($project);
|
||||
}
|
||||
if ($clientIdChanged) {
|
||||
|
||||
@@ -73,13 +73,13 @@ class ProjectMemberController extends Controller
|
||||
}
|
||||
|
||||
$projectMember = new ProjectMember;
|
||||
$projectMember->billable_rate = $request->getBillableRate();
|
||||
$projectMember->billable_rate = $this->canUseBillableRates($organization) ? $request->getBillableRate() : null;
|
||||
$projectMember->member()->associate($member);
|
||||
$projectMember->user()->associate($member->user);
|
||||
$projectMember->project()->associate($project);
|
||||
$projectMember->save();
|
||||
|
||||
if ($request->getBillableRate() !== null) {
|
||||
if ($projectMember->billable_rate !== null) {
|
||||
$billableRateService->updateTimeEntriesBillableRateForProjectMember($projectMember);
|
||||
}
|
||||
|
||||
@@ -97,10 +97,12 @@ class ProjectMemberController extends Controller
|
||||
{
|
||||
$this->checkPermission($organization, 'project-members:update', projectMember: $projectMember);
|
||||
$oldBillableRate = $projectMember->billable_rate;
|
||||
if ($this->canUseBillableRates($organization)) {
|
||||
$projectMember->billable_rate = $request->getBillableRate();
|
||||
}
|
||||
$projectMember->save();
|
||||
|
||||
if ($oldBillableRate !== $request->getBillableRate()) {
|
||||
if ($oldBillableRate !== $projectMember->billable_rate) {
|
||||
$billableRateService->updateTimeEntriesBillableRateForProjectMember($projectMember);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,12 @@ declare(strict_types=1);
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\Role;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
|
||||
use App\Exceptions\Api\OverlappingTimeEntryApiException;
|
||||
use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
|
||||
use App\Exceptions\Api\TimeEntryCanNotBeRestartedApiException;
|
||||
use App\Exceptions\Api\TimeEntryMemberCanNotBeChangedWhileRunningApiException;
|
||||
use App\Exceptions\Api\TimeEntryStillRunningApiException;
|
||||
use App\Http\Requests\V1\TimeEntry\TimeEntryAggregateExportRequest;
|
||||
use App\Http\Requests\V1\TimeEntry\TimeEntryAggregateRequest;
|
||||
@@ -29,6 +29,7 @@ use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\BillableRateService;
|
||||
use App\Service\LocalizationService;
|
||||
use App\Service\ReportExport\TimeEntriesDetailedCsvExport;
|
||||
use App\Service\ReportExport\TimeEntriesDetailedExport;
|
||||
@@ -51,6 +52,7 @@ use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
@@ -227,7 +229,7 @@ class TimeEntryController extends Controller
|
||||
*
|
||||
* @operationId exportTimeEntries
|
||||
*/
|
||||
public function indexExport(Organization $organization, TimeEntryIndexExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService): JsonResponse
|
||||
public function indexExport(Organization $organization, TimeEntryIndexExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService, BillableRateService $billableRateService): JsonResponse
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $memberFilter */
|
||||
@@ -245,7 +247,7 @@ class TimeEntryController extends Controller
|
||||
}
|
||||
$user = $this->user();
|
||||
$timezone = $user->timezone;
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
$showBillableRate = $billableRateService->canSeeBillableRates($organization, $this->member($organization));
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
|
||||
@@ -384,7 +386,7 @@ class TimeEntryController extends Controller
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*/
|
||||
public function aggregate(Organization $organization, TimeEntryAggregateRequest $request, TimeEntryAggregationService $timeEntryAggregationService): array
|
||||
public function aggregate(Organization $organization, TimeEntryAggregateRequest $request, TimeEntryAggregationService $timeEntryAggregationService, BillableRateService $billableRateService): array
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $memberFilter */
|
||||
@@ -396,7 +398,7 @@ class TimeEntryController extends Controller
|
||||
}
|
||||
$canAccessPremiumFeatures = $this->canAccessPremiumFeatures($organization);
|
||||
$user = $this->user();
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
$showBillableRate = $billableRateService->canSeeBillableRates($organization, $this->member($organization));
|
||||
|
||||
$group1Type = $request->getGroup();
|
||||
$group2Type = $request->getSubGroup();
|
||||
@@ -434,7 +436,7 @@ class TimeEntryController extends Controller
|
||||
* @throws NoOutputFileInResponse
|
||||
* @throws FeatureIsNotAvailableInFreePlanApiException
|
||||
*/
|
||||
public function aggregateExport(Organization $organization, TimeEntryAggregateExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService): JsonResponse
|
||||
public function aggregateExport(Organization $organization, TimeEntryAggregateExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService, BillableRateService $billableRateService): JsonResponse
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $memberFilter */
|
||||
@@ -451,7 +453,7 @@ class TimeEntryController extends Controller
|
||||
}
|
||||
$debug = $request->getDebug();
|
||||
$user = $this->user();
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
$showBillableRate = $billableRateService->canSeeBillableRates($organization, $this->member($organization));
|
||||
|
||||
$group = $request->getGroup();
|
||||
$subGroup = $request->getSubGroup();
|
||||
@@ -613,7 +615,24 @@ class TimeEntryController extends Controller
|
||||
$this->checkPermission($organization, 'time-entries:create:all');
|
||||
}
|
||||
|
||||
if ($request->input('end') === null && TimeEntry::query()->whereBelongsTo($member, 'member')->where('end', null)->exists()) {
|
||||
// Lock the creation of running time entries per user, so that concurrent requests can not create more than one running time entry
|
||||
$lock = $request->input('end') === null ? Cache::lock('time-entries:running:'.$member->user_id, 10) : null;
|
||||
$lock?->block(5);
|
||||
|
||||
try {
|
||||
return $this->storeTimeEntry($organization, $member, $request);
|
||||
} finally {
|
||||
$lock?->release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws TimeEntryStillRunningApiException
|
||||
*/
|
||||
private function storeTimeEntry(Organization $organization, Member $member, TimeEntryStoreRequest $request): JsonResource
|
||||
{
|
||||
// A user can only have one running time entry, across all organizations
|
||||
if ($request->input('end') === null && TimeEntry::query()->where('user_id', $member->user_id)->whereNull('end')->exists()) {
|
||||
throw new TimeEntryStillRunningApiException;
|
||||
}
|
||||
|
||||
@@ -628,6 +647,10 @@ class TimeEntryController extends Controller
|
||||
|
||||
$timeEntry = new TimeEntry;
|
||||
$timeEntry->fill($request->validated());
|
||||
// Organizations that can not use billable rates can not create billable time entries
|
||||
if ($timeEntry->billable && ! $this->canUseBillableRates($organization)) {
|
||||
$timeEntry->billable = false;
|
||||
}
|
||||
$timeEntry->client()->associate($client);
|
||||
$timeEntry->user_id = $member->user_id;
|
||||
$timeEntry->description = $request->input('description') ?? '';
|
||||
@@ -650,7 +673,7 @@ class TimeEntryController extends Controller
|
||||
*
|
||||
* To stop a running timer, set `end` to the stop time (UTC). Times the user gives in their own timezone must be converted to UTC first.
|
||||
*
|
||||
* @throws AuthorizationException|TimeEntryCanNotBeRestartedApiException
|
||||
* @throws AuthorizationException|TimeEntryCanNotBeRestartedApiException|TimeEntryMemberCanNotBeChangedWhileRunningApiException
|
||||
*
|
||||
* @operationId updateTimeEntry
|
||||
*/
|
||||
@@ -676,6 +699,11 @@ class TimeEntryController extends Controller
|
||||
$effectiveEnd = $request->has('end') ? ($request->input('end') !== null ? Carbon::parse($request->input('end')) : null) : $timeEntry->end;
|
||||
$this->assertNoOverlap($organization, $effectiveMember, $effectiveStart, $effectiveEnd, $timeEntry);
|
||||
|
||||
// The new member could already have a running time entry
|
||||
if ($effectiveEnd === null && $newMember !== null && $newMember->getKey() !== $timeEntry->member_id) {
|
||||
throw new TimeEntryMemberCanNotBeChangedWhileRunningApiException;
|
||||
}
|
||||
|
||||
$oldProject = $timeEntry->project;
|
||||
$oldTask = $timeEntry->task;
|
||||
|
||||
@@ -690,11 +718,20 @@ class TimeEntryController extends Controller
|
||||
$task = $request->input('task_id') !== null ? Task::findOrFail((string) $request->input('task_id')) : null;
|
||||
}
|
||||
|
||||
$wasBillable = $timeEntry->billable;
|
||||
$timeEntry->fill($request->validated());
|
||||
// Organizations that can not use billable rates can keep or remove the billable flag, but not set it
|
||||
if ($timeEntry->billable && ! $wasBillable && ! $this->canUseBillableRates($organization)) {
|
||||
$timeEntry->billable = false;
|
||||
}
|
||||
if ($newMember !== null) {
|
||||
$timeEntry->member()->associate($newMember);
|
||||
$timeEntry->user()->associate($newMember->user);
|
||||
}
|
||||
// If project is changed, but task is not, we remove the old task from the time entry
|
||||
if ($request->has('project_id') && ! $request->has('task_id') && $oldTask !== null && $oldTask->project_id !== $project?->getKey()) {
|
||||
$timeEntry->task()->disassociate();
|
||||
}
|
||||
$timeEntry->description = $request->input('description', $timeEntry->description) ?? '';
|
||||
$timeEntry->setComputedAttributeValue('billable_rate');
|
||||
$timeEntry->save();
|
||||
@@ -744,6 +781,7 @@ class TimeEntryController extends Controller
|
||||
->get();
|
||||
|
||||
$changes = $request->validated('changes');
|
||||
$canUseBillableRates = $this->canUseBillableRates($organization);
|
||||
|
||||
if ($request->has('changes.description')) {
|
||||
$changes['description'] = $request->input('changes.description') ?? '';
|
||||
@@ -801,16 +839,27 @@ class TimeEntryController extends Controller
|
||||
|
||||
continue;
|
||||
}
|
||||
// The new member could already have a running time entry
|
||||
if ($newMember !== null && $timeEntry->end === null && $newMember->getKey() !== $timeEntry->member_id) {
|
||||
$error->push($id);
|
||||
|
||||
continue;
|
||||
}
|
||||
$oldProject = $timeEntry->project;
|
||||
$oldTask = $timeEntry->task;
|
||||
$wasBillable = $timeEntry->billable;
|
||||
|
||||
$timeEntry->fill($changes);
|
||||
// Organizations that can not use billable rates can keep or remove the billable flag, but not set it
|
||||
if (! $wasBillable && ! $canUseBillableRates) {
|
||||
$timeEntry->billable = false;
|
||||
}
|
||||
if ($newMember !== null) {
|
||||
$timeEntry->member()->associate($newMember);
|
||||
$timeEntry->user_id = $newMember->user_id;
|
||||
}
|
||||
// If project is changed, but task is not, we remove the old task from the time entry
|
||||
if ($oldProject !== null && $project !== null && $oldProject->isNot($project) && $task === null) {
|
||||
if ($request->has('changes.project_id') && ! $request->has('changes.task_id') && $oldTask !== null && $oldTask->project_id !== $project?->getKey()) {
|
||||
$timeEntry->task()->disassociate();
|
||||
}
|
||||
if ($overwriteClient) {
|
||||
|
||||
@@ -12,7 +12,7 @@ class TimeZoneController extends Controller
|
||||
/**
|
||||
* Get all timezones
|
||||
*
|
||||
* @response object{key: string}[]
|
||||
* @response array{key: string}[]
|
||||
*
|
||||
* @operationId getTimezones
|
||||
*/
|
||||
|
||||
@@ -4,9 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Web;
|
||||
|
||||
use App\Enums\Weekday;
|
||||
use App\Service\Dto\UserAgentDto;
|
||||
use App\Service\TimezoneService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Support\Carbon;
|
||||
@@ -94,8 +92,6 @@ class UserProfileController extends Controller
|
||||
$this->validateTwoFactorAuthenticationState($request);
|
||||
|
||||
return Inertia::render('Profile/Show', [
|
||||
'timezones' => app(TimezoneService::class)->getSelectOptions(),
|
||||
'weekdays' => Weekday::toSelectArray(),
|
||||
'confirmsTwoFactorAuthentication' => Features::optionEnabled(Features::twoFactorAuthentication(), 'confirm'),
|
||||
'sessions' => $this->sessions($request),
|
||||
]);
|
||||
|
||||
@@ -42,6 +42,7 @@ class HandleInertiaRequests extends Middleware
|
||||
$hasBilling = Module::has('Billing') && Module::isEnabled('Billing');
|
||||
$hasInvoicing = Module::has('Invoicing') && Module::isEnabled('Invoicing');
|
||||
$hasServices = Module::has('Services') && Module::isEnabled('Services');
|
||||
$hasGoals = Module::has('Goals') && Module::isEnabled('Goals');
|
||||
|
||||
/** @var BillingContract $billing */
|
||||
$billing = app(BillingContract::class);
|
||||
@@ -52,11 +53,14 @@ class HandleInertiaRequests extends Middleware
|
||||
'has_billing_extension' => $hasBilling,
|
||||
'has_invoicing_extension' => $hasInvoicing,
|
||||
'has_services_extension' => $hasServices,
|
||||
'has_goals_extension' => $hasGoals,
|
||||
'billing' => $currentOrganization !== null ? [
|
||||
'has_subscription' => $billing->hasSubscription($currentOrganization),
|
||||
'has_trial' => $billing->hasTrial($currentOrganization),
|
||||
'trial_until' => $billing->getTrialUntil($currentOrganization)?->toIso8601ZuluString(),
|
||||
'is_blocked' => $billing->isBlocked($currentOrganization),
|
||||
'goal_limit' => $billing->getGoalLimit($currentOrganization),
|
||||
'can_use_billable_rates' => $billing->canUseBillableRates($currentOrganization),
|
||||
] : null,
|
||||
'flash' => [
|
||||
'message' => fn () => $request->session()->get('message'),
|
||||
|
||||
144
app/Http/Requests/V1/Goal/GoalFilterRules.php
Normal file
144
app/Http/Requests/V1/Goal/GoalFilterRules.php
Normal file
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\Goal;
|
||||
|
||||
use App\Enums\Role;
|
||||
use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Service\Dto\GoalFiltersDto;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Validation\Rule as LegacyValidationRule;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\ProhibitedIf;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
* Shared validation rules for the filters of a goal.
|
||||
*
|
||||
* @property Organization $organization Organization from model binding
|
||||
*/
|
||||
trait GoalFilterRules
|
||||
{
|
||||
/**
|
||||
* @param \Closure(): bool $forEveryMember Whether the goal counts every member instead of one member, evaluated during validation
|
||||
* @return array<string, array<string|ValidationRule|LegacyValidationRule|\Closure|ProhibitedIf>>
|
||||
*/
|
||||
protected function filterRules(\Closure $forEveryMember): array
|
||||
{
|
||||
return [
|
||||
'filters' => [
|
||||
'sometimes',
|
||||
'array',
|
||||
],
|
||||
// Filter by member IDs, member IDs are OR combined. Only for goals that count every member, null means every member.
|
||||
'filters.member_ids' => [
|
||||
'nullable',
|
||||
'array',
|
||||
// "prohibited" still lets null and an empty array through, both mean "no restriction"
|
||||
Rule::prohibitedIf(fn (): bool => ! $forEveryMember()),
|
||||
],
|
||||
'filters.member_ids.*' => [
|
||||
'string',
|
||||
'distinct',
|
||||
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Member> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization')
|
||||
->where('role', '!=', Role::Placeholder->value);
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by project IDs, project IDs are OR combined, "none" matches entries without a project
|
||||
'filters.project_ids' => [
|
||||
'nullable',
|
||||
'array',
|
||||
],
|
||||
'filters.project_ids.*' => [
|
||||
'string',
|
||||
$this->idOrNoneExistsInOrganization(Project::class),
|
||||
],
|
||||
// Filter by task IDs, task IDs are OR combined, "none" matches entries without a task
|
||||
'filters.task_ids' => [
|
||||
'nullable',
|
||||
'array',
|
||||
],
|
||||
'filters.task_ids.*' => [
|
||||
'string',
|
||||
$this->idOrNoneExistsInOrganization(Task::class),
|
||||
],
|
||||
// Filter by tag IDs, tag IDs are OR combined, "none" matches entries without tags
|
||||
'filters.tag_ids' => [
|
||||
'nullable',
|
||||
'array',
|
||||
],
|
||||
'filters.tag_ids.*' => [
|
||||
'string',
|
||||
$this->idOrNoneExistsInOrganization(Tag::class),
|
||||
],
|
||||
'filters.tag_match_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TagMatchType::class),
|
||||
],
|
||||
// Filter by client IDs, client IDs are OR combined, "none" matches entries without a client
|
||||
'filters.client_ids' => [
|
||||
'nullable',
|
||||
'array',
|
||||
],
|
||||
'filters.client_ids.*' => [
|
||||
'string',
|
||||
$this->idOrNoneExistsInOrganization(Client::class),
|
||||
],
|
||||
// Filter by billable status, null means both
|
||||
'filters.billable' => [
|
||||
'nullable',
|
||||
'boolean',
|
||||
],
|
||||
// Filter by time entry type, null means both
|
||||
'filters.time_entry_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TimeEntryType::class),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param class-string<Project|Task|Tag|Client> $modelClass
|
||||
*/
|
||||
private function idOrNoneExistsInOrganization(string $modelClass): \Closure
|
||||
{
|
||||
return function (string $attribute, mixed $value, \Closure $fail) use ($modelClass): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make($modelClass, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project|Task|Tag|Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
};
|
||||
}
|
||||
|
||||
public function getFilters(): GoalFiltersDto
|
||||
{
|
||||
$filters = new GoalFiltersDto;
|
||||
$filters->setMemberIds($this->input('filters.member_ids'));
|
||||
$filters->setProjectIds($this->input('filters.project_ids'));
|
||||
$filters->setTaskIds($this->input('filters.task_ids'));
|
||||
$filters->setTagIds($this->input('filters.tag_ids'));
|
||||
$filters->tagMatchType = $this->input('filters.tag_match_type') !== null ? TagMatchType::from($this->input('filters.tag_match_type')) : null;
|
||||
$filters->setClientIds($this->input('filters.client_ids'));
|
||||
$filters->billable = $this->input('filters.billable') !== null ? (bool) $this->input('filters.billable') : null;
|
||||
$filters->timeEntryType = $this->input('filters.time_entry_type') !== null ? TimeEntryType::from($this->input('filters.time_entry_type')) : null;
|
||||
|
||||
return $filters;
|
||||
}
|
||||
}
|
||||
61
app/Http/Requests/V1/Goal/GoalIndexRequest.php
Normal file
61
app/Http/Requests/V1/Goal/GoalIndexRequest.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\Goal;
|
||||
|
||||
use App\Enums\GoalType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Organization;
|
||||
use Illuminate\Contracts\Validation\Rule as LegacyValidationRule;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* @property Organization $organization Organization from model binding
|
||||
*/
|
||||
class GoalIndexRequest extends BaseFormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|LegacyValidationRule|\Closure>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
// Only return goals of this type (personal, organization)
|
||||
'type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(GoalType::class),
|
||||
],
|
||||
// Filter by archived status, "true" only archived, "false" only not archived (default), "all" both
|
||||
'archived' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'in:true,false,all',
|
||||
],
|
||||
'page' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function getType(): ?GoalType
|
||||
{
|
||||
if ($this->input('type') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return GoalType::from($this->input('type'));
|
||||
}
|
||||
|
||||
public function getArchivedFilter(): string
|
||||
{
|
||||
return (string) $this->input('archived', 'false');
|
||||
}
|
||||
}
|
||||
168
app/Http/Requests/V1/Goal/GoalStoreRequest.php
Normal file
168
app/Http/Requests/V1/Goal/GoalStoreRequest.php
Normal file
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\Goal;
|
||||
|
||||
use App\Enums\GoalComparison;
|
||||
use App\Enums\GoalPeriod;
|
||||
use App\Enums\GoalType;
|
||||
use App\Enums\Role;
|
||||
use App\Enums\Weekday;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use Illuminate\Contracts\Validation\Rule as LegacyValidationRule;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\In;
|
||||
use Illuminate\Validation\Rules\ProhibitedIf;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
* @property Organization $organization Organization from model binding
|
||||
*/
|
||||
class GoalStoreRequest extends BaseFormRequest
|
||||
{
|
||||
use GoalFilterRules;
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|LegacyValidationRule|In|ProhibitedIf|\Closure>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$memberExistsInOrganization = ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Member> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization')
|
||||
->where('role', '!=', Role::Placeholder->value);
|
||||
})->uuid();
|
||||
|
||||
return array_merge([
|
||||
'name' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
],
|
||||
// personal: a goal for yourself that nobody else can see, organization: a goal of the organization for a member or for every member. Organization goals require the team goals extension.
|
||||
'type' => [
|
||||
'required',
|
||||
'string',
|
||||
Rule::enum(GoalType::class),
|
||||
],
|
||||
// Whether the goal is reached when "at least" or "less than" the target time is tracked in the period
|
||||
'comparison' => [
|
||||
'required',
|
||||
'string',
|
||||
Rule::enum(GoalComparison::class),
|
||||
],
|
||||
// Target time in seconds
|
||||
'target_seconds' => [
|
||||
'required',
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
// The recurring time frame in which the target has to be reached
|
||||
'period' => [
|
||||
'required',
|
||||
'string',
|
||||
Rule::enum(GoalPeriod::class),
|
||||
],
|
||||
// ID of the member whose time entries count towards the goal, defaults to the current member. Send null for a goal that counts every member (organization goals only).
|
||||
'member_id' => $this->input('type') === GoalType::Personal->value
|
||||
// A personal goal is always for the current member, it can not count every member
|
||||
? [
|
||||
'sometimes',
|
||||
'filled',
|
||||
'string',
|
||||
Rule::in([$this->currentMemberId()]),
|
||||
]
|
||||
: [
|
||||
'nullable',
|
||||
'string',
|
||||
$memberExistsInOrganization,
|
||||
],
|
||||
// Timezone that defines the periods of the goal, defaults to the timezone of the current user
|
||||
'timezone' => [
|
||||
'nullable',
|
||||
'timezone:all',
|
||||
],
|
||||
// Week start that defines weekly periods, defaults to the week start of the current user
|
||||
'week_start' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(Weekday::class),
|
||||
],
|
||||
], $this->filterRules(
|
||||
// Without a member_id the goal is for the current member
|
||||
fn (): bool => $this->has('member_id') && $this->input('member_id') === null,
|
||||
));
|
||||
}
|
||||
|
||||
private function currentMemberId(): ?string
|
||||
{
|
||||
/** @var string|null $memberId */
|
||||
$memberId = Member::query()
|
||||
->whereBelongsTo($this->organization, 'organization')
|
||||
->where('user_id', $this->user()?->getKey())
|
||||
->value('id');
|
||||
|
||||
return $memberId;
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return (string) $this->input('name');
|
||||
}
|
||||
|
||||
public function getType(): GoalType
|
||||
{
|
||||
return GoalType::from($this->input('type'));
|
||||
}
|
||||
|
||||
public function getComparison(): GoalComparison
|
||||
{
|
||||
return GoalComparison::from($this->input('comparison'));
|
||||
}
|
||||
|
||||
public function getTargetSeconds(): int
|
||||
{
|
||||
return (int) $this->input('target_seconds');
|
||||
}
|
||||
|
||||
public function getPeriod(): GoalPeriod
|
||||
{
|
||||
return GoalPeriod::from($this->input('period'));
|
||||
}
|
||||
|
||||
public function hasMemberId(): bool
|
||||
{
|
||||
return $this->has('member_id');
|
||||
}
|
||||
|
||||
public function getMemberId(): ?string
|
||||
{
|
||||
return $this->input('member_id');
|
||||
}
|
||||
|
||||
public function getTimezone(): ?string
|
||||
{
|
||||
if (! $this->has('timezone') || $this->input('timezone') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (string) $this->input('timezone');
|
||||
}
|
||||
|
||||
public function getWeekStart(): ?Weekday
|
||||
{
|
||||
if (! $this->has('week_start') || $this->input('week_start') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Weekday::from($this->input('week_start'));
|
||||
}
|
||||
}
|
||||
130
app/Http/Requests/V1/Goal/GoalUpdateRequest.php
Normal file
130
app/Http/Requests/V1/Goal/GoalUpdateRequest.php
Normal file
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\Goal;
|
||||
|
||||
use App\Enums\GoalComparison;
|
||||
use App\Enums\GoalPeriod;
|
||||
use App\Enums\Weekday;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Goal;
|
||||
use App\Models\Organization;
|
||||
use Illuminate\Contracts\Validation\Rule as LegacyValidationRule;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\ProhibitedIf;
|
||||
|
||||
/**
|
||||
* @property Organization $organization Organization from model binding
|
||||
*/
|
||||
class GoalUpdateRequest extends BaseFormRequest
|
||||
{
|
||||
use GoalFilterRules;
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
* The type of a goal and the member it is for can not be changed after creation.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|LegacyValidationRule|ProhibitedIf|\Closure>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
/** @var Goal $goal */
|
||||
$goal = $this->route('goal');
|
||||
|
||||
return array_merge([
|
||||
'name' => [
|
||||
'sometimes',
|
||||
'string',
|
||||
'max:255',
|
||||
],
|
||||
// Whether the goal is reached when "at least" or "less than" the target time is tracked in the period
|
||||
'comparison' => [
|
||||
'sometimes',
|
||||
'string',
|
||||
Rule::enum(GoalComparison::class),
|
||||
],
|
||||
// Target time in seconds
|
||||
'target_seconds' => [
|
||||
'sometimes',
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
// The recurring time frame in which the target has to be reached
|
||||
'period' => [
|
||||
'sometimes',
|
||||
'string',
|
||||
Rule::enum(GoalPeriod::class),
|
||||
],
|
||||
// Timezone that defines the periods of the goal
|
||||
'timezone' => [
|
||||
'sometimes',
|
||||
'timezone:all',
|
||||
],
|
||||
// Week start that defines weekly periods
|
||||
'week_start' => [
|
||||
'sometimes',
|
||||
'string',
|
||||
Rule::enum(Weekday::class),
|
||||
],
|
||||
// Archived goals are hidden from the goal list by default, their progress is still calculated
|
||||
'is_archived' => [
|
||||
'sometimes',
|
||||
'boolean',
|
||||
],
|
||||
// Only allowed if it matches the current type of the goal
|
||||
'type' => [
|
||||
function (string $attribute, mixed $value, \Closure $fail) use ($goal): void {
|
||||
if ($value !== $goal->type->value) {
|
||||
$fail('The '.$attribute.' of a goal can not be changed.');
|
||||
}
|
||||
},
|
||||
],
|
||||
// Only allowed if it matches the current member of the goal
|
||||
'member_id' => [
|
||||
function (string $attribute, mixed $value, \Closure $fail) use ($goal): void {
|
||||
if ($value !== $goal->member_id) {
|
||||
$fail('The '.$attribute.' of a goal can not be changed.');
|
||||
}
|
||||
},
|
||||
],
|
||||
], $this->filterRules(fn (): bool => $goal->member_id === null));
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return (string) $this->input('name');
|
||||
}
|
||||
|
||||
public function getComparison(): GoalComparison
|
||||
{
|
||||
return GoalComparison::from($this->input('comparison'));
|
||||
}
|
||||
|
||||
public function getTargetSeconds(): int
|
||||
{
|
||||
return (int) $this->input('target_seconds');
|
||||
}
|
||||
|
||||
public function getPeriod(): GoalPeriod
|
||||
{
|
||||
return GoalPeriod::from($this->input('period'));
|
||||
}
|
||||
|
||||
public function getTimezone(): string
|
||||
{
|
||||
return (string) $this->input('timezone');
|
||||
}
|
||||
|
||||
public function getWeekStart(): Weekday
|
||||
{
|
||||
return Weekday::from($this->input('week_start'));
|
||||
}
|
||||
|
||||
public function getIsArchived(): bool
|
||||
{
|
||||
return (bool) $this->input('is_archived');
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ class ProjectUpdateRequest extends BaseFormRequest
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Billable rate in cents per hour (example: 8000 means 80.00 in the organization's currency)
|
||||
// Billable rate in cents per hour (example: 8000 means 80.00 in the organization's currency), the current rate is kept if the field is omitted
|
||||
'billable_rate' => array_merge([
|
||||
'nullable',
|
||||
],
|
||||
|
||||
@@ -13,9 +13,11 @@ use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\PermissionStore;
|
||||
use Carbon\Exceptions\InvalidFormatException;
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ConditionalRules;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -90,12 +92,32 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
// Start of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
|
||||
'start' => [
|
||||
'date_format:Y-m-d\TH:i:s\Z',
|
||||
function (string $attribute, mixed $value, Closure $fail) use ($timeEntry): void {
|
||||
// If the payload does not contain an end, the start needs to be validated against the persisted end
|
||||
if ($this->has('end') || $timeEntry?->end === null) {
|
||||
return;
|
||||
}
|
||||
$start = $this->parseDate($value);
|
||||
if ($start !== null && $start->gt($timeEntry->end)) {
|
||||
$fail('The start field must be a date before or equal to end.');
|
||||
}
|
||||
},
|
||||
],
|
||||
// End of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
|
||||
'end' => [
|
||||
'nullable',
|
||||
'date_format:Y-m-d\TH:i:s\Z',
|
||||
'after_or_equal:start',
|
||||
function (string $attribute, mixed $value, Closure $fail) use ($timeEntry): void {
|
||||
// If the payload does not contain a start, the end needs to be validated against the persisted start
|
||||
if ($this->has('start') || $timeEntry === null) {
|
||||
return;
|
||||
}
|
||||
$end = $this->parseDate($value);
|
||||
if ($end !== null && $end->lt($timeEntry->start)) {
|
||||
$fail('The end field must be a date after or equal to start.');
|
||||
}
|
||||
},
|
||||
],
|
||||
// Whether time entry is billable
|
||||
'billable' => [
|
||||
@@ -137,4 +159,16 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function parseDate(mixed $value): ?Carbon
|
||||
{
|
||||
if (! is_string($value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $value, 'UTC');
|
||||
} catch (InvalidFormatException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,9 +43,10 @@ class UserUpdateRequest extends BaseFormRequest
|
||||
'email' => [
|
||||
'email:rfc,strict',
|
||||
'max:255',
|
||||
UniqueEloquent::make(User::class, 'email')->ignore($this->user->id)->query(function (Builder $query) {
|
||||
UniqueEloquent::make(User::class, 'email')->query(function (Builder $query) {
|
||||
/** @var Builder<User> $query */
|
||||
return $query->where('is_placeholder', '=', false);
|
||||
return $query->where('is_placeholder', '=', false)
|
||||
->whereKeyNot($this->user->getKey());
|
||||
}),
|
||||
],
|
||||
'photo' => [
|
||||
|
||||
@@ -21,15 +21,15 @@ class ApiTokenResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of the API token, this ID is NOT a UUID */
|
||||
/** ID of the API token, this ID is NOT a UUID */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name of the API token */
|
||||
'name' => $this->resource->name,
|
||||
/** @var bool $revoked Whether the API token is revoked */
|
||||
/** Whether the API token is revoked */
|
||||
'revoked' => $this->resource->revoked,
|
||||
/** @var array<string> $scopes List of scopes that the API token has */
|
||||
/** List of scopes that the API token has */
|
||||
'scopes' => $this->resource->scopes,
|
||||
/** @var string $created_at When the API token was created (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
|
||||
/** When the API token was created (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string|null $expires_at At what time the API token expires (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
|
||||
'expires_at' => $this->formatDateTime($this->resource->expires_at),
|
||||
|
||||
@@ -29,15 +29,15 @@ class ApiTokenWithAccessTokenResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of the API token, this ID is NOT a UUID */
|
||||
/** ID of the API token, this ID is NOT a UUID */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name of the API token */
|
||||
'name' => $this->resource->name,
|
||||
/** @var bool $revoked Whether the API token is revoked */
|
||||
/** Whether the API token is revoked */
|
||||
'revoked' => $this->resource->revoked,
|
||||
/** @var array<string> $scopes List of scopes that the API token has */
|
||||
/** List of scopes that the API token has */
|
||||
'scopes' => $this->resource->scopes,
|
||||
/** @var string $created_at When the API token was created (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
|
||||
/** When the API token was created (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string|null $expires_at At what time the API token expires (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
|
||||
'expires_at' => $this->formatDateTime($this->resource->expires_at),
|
||||
|
||||
@@ -21,15 +21,15 @@ class ClientResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID */
|
||||
/** ID */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** @var bool $is_archived Whether the client is archived */
|
||||
/** Whether the client is archived */
|
||||
'is_archived' => $this->resource->is_archived,
|
||||
/** @var string $created_at When the tag was created */
|
||||
/** When the tag was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string $updated_at When the tag was last updated */
|
||||
/** When the tag was last updated */
|
||||
'updated_at' => $this->formatDateTime($this->resource->updated_at),
|
||||
];
|
||||
}
|
||||
|
||||
45
app/Http/Resources/V1/Goal/GoalCollection.php
Normal file
45
app/Http/Resources/V1/Goal/GoalCollection.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Resources\V1\Goal;
|
||||
|
||||
use App\Models\Goal;
|
||||
use App\Service\Dto\GoalProgressDto;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class GoalCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* @var array<string, GoalProgressDto>
|
||||
*/
|
||||
private array $progressByGoalId;
|
||||
|
||||
/**
|
||||
* @param array<string, GoalProgressDto> $progressByGoalId
|
||||
*/
|
||||
public function __construct($resource, array $progressByGoalId)
|
||||
{
|
||||
parent::__construct($resource);
|
||||
$this->progressByGoalId = $progressByGoalId;
|
||||
}
|
||||
|
||||
protected function collects(): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the resource collection into an array.
|
||||
*
|
||||
* @return array<array<string, string|bool|int|null|array<string, string|bool|int|null|array<int, string>>>>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return $this->collection->map(function (Goal $goal) use ($request): array {
|
||||
return (new GoalResource($goal, $this->progressByGoalId[$goal->getKey()]))
|
||||
->toArray($request);
|
||||
})->all();
|
||||
}
|
||||
}
|
||||
90
app/Http/Resources/V1/Goal/GoalResource.php
Normal file
90
app/Http/Resources/V1/Goal/GoalResource.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Resources\V1\Goal;
|
||||
|
||||
use App\Http\Resources\V1\BaseResource;
|
||||
use App\Models\Goal;
|
||||
use App\Service\Dto\GoalProgressDto;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* @property Goal $resource
|
||||
*/
|
||||
class GoalResource extends BaseResource
|
||||
{
|
||||
private GoalProgressDto $progress;
|
||||
|
||||
public function __construct(Goal $resource, GoalProgressDto $progress)
|
||||
{
|
||||
parent::__construct($resource);
|
||||
|
||||
$this->progress = $progress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the resource into an array.
|
||||
*
|
||||
* @return array<string, string|bool|int|null|array<string, string|bool|int|null|array<int, string>>>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** ID of the goal */
|
||||
'id' => $this->resource->id,
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** personal: a goal a member set for themselves, organization: a goal of the organization (team goals extension) */
|
||||
'type' => $this->resource->type->value,
|
||||
/** Whether the goal is reached with "at least" or "less than" the target time (at_least, less_than) */
|
||||
'comparison' => $this->resource->comparison->value,
|
||||
/** Target time in seconds */
|
||||
'target_seconds' => $this->resource->target_seconds,
|
||||
/** Recurring time frame (day, week, month) */
|
||||
'period' => $this->resource->period->value,
|
||||
/** ID of the member whose time entries count towards the goal, null if every member counts */
|
||||
'member_id' => $this->resource->member_id,
|
||||
/** Name of the member whose time entries count towards the goal, null if every member counts */
|
||||
'member_name' => $this->resource->member?->user->name,
|
||||
/** Timezone that defines the periods of the goal */
|
||||
'timezone' => $this->resource->timezone,
|
||||
/** Week start that defines weekly periods */
|
||||
'week_start' => $this->resource->week_start->value,
|
||||
/** Whether the goal is archived */
|
||||
'is_archived' => $this->resource->is_archived,
|
||||
'filters' => [
|
||||
/** @var array<string>|null $member_ids Filter by member IDs, member IDs are OR combined, only for goals that count every member */
|
||||
'member_ids' => $this->resource->filters->memberIds?->toArray(),
|
||||
/** @var array<string>|null $project_ids Filter by project IDs, project IDs are OR combined */
|
||||
'project_ids' => $this->resource->filters->projectIds?->toArray(),
|
||||
/** @var array<string>|null $task_ids Filter by task IDs, task IDs are OR combined */
|
||||
'task_ids' => $this->resource->filters->taskIds?->toArray(),
|
||||
/** @var array<string>|null $tag_ids Filter by tag IDs, tag IDs are OR combined */
|
||||
'tag_ids' => $this->resource->filters->tagIds?->toArray(),
|
||||
/** Tag match type (contains, not_contains) */
|
||||
'tag_match_type' => $this->resource->filters->tagMatchType?->value,
|
||||
/** @var array<string>|null $client_ids Filter by client IDs, client IDs are OR combined */
|
||||
'client_ids' => $this->resource->filters->clientIds?->toArray(),
|
||||
/** Filter by billable status */
|
||||
'billable' => $this->resource->filters->billable,
|
||||
/** Filter by time entry type (work, break) */
|
||||
'time_entry_type' => $this->resource->filters->timeEntryType?->value,
|
||||
],
|
||||
'progress' => [
|
||||
/** Start of the current period (inclusive) */
|
||||
'period_start' => $this->formatDateTime($this->progress->periodStart),
|
||||
/** End of the current period (exclusive) */
|
||||
'period_end' => $this->formatDateTime($this->progress->periodEnd),
|
||||
/** Seconds tracked in the current period that match the filters, incl. the running time entry */
|
||||
'tracked_seconds' => $this->progress->trackedSeconds,
|
||||
/** Status in the current period (in_progress, achieved, on_track, exceeded) */
|
||||
'status' => $this->progress->status->value,
|
||||
],
|
||||
/** Date when the goal was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** Date when the goal was last updated */
|
||||
'updated_at' => $this->formatDateTime($this->resource->updated_at),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -21,11 +21,11 @@ class InvitationResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of the invitation */
|
||||
/** ID of the invitation */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $email Email */
|
||||
/** Email */
|
||||
'email' => $this->resource->email,
|
||||
/** @var string $role Role */
|
||||
/** Role */
|
||||
'role' => $this->resource->role,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -22,19 +22,19 @@ class MemberResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of membership */
|
||||
/** ID of membership */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $id ID of user */
|
||||
/** ID of user */
|
||||
'user_id' => $this->resource->user->id,
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->user->name,
|
||||
/** @var string $email Email */
|
||||
/** Email */
|
||||
'email' => $this->resource->user->email,
|
||||
/** @var string $role Role */
|
||||
/** Role */
|
||||
'role' => $this->resource->role,
|
||||
/** @var bool $is_placeholder Placeholder user for imports, user might not really exist and does not know about this placeholder membership */
|
||||
/** Placeholder user for imports, user might not really exist and does not know about this placeholder membership */
|
||||
'is_placeholder' => $this->resource->user->is_placeholder,
|
||||
/** @var int|null $billable_rate Billable rate in cents per hour */
|
||||
/** Billable rate in cents per hour */
|
||||
'billable_rate' => $this->resource->billable_rate,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -21,17 +21,17 @@ class PersonalMembershipResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of membership */
|
||||
/** ID of membership */
|
||||
'id' => $this->resource->id,
|
||||
'organization' => [
|
||||
/** @var string $id ID of organization */
|
||||
/** ID of organization */
|
||||
'id' => $this->resource->organization->id,
|
||||
/** @var string $name Name of organization */
|
||||
/** Name of organization */
|
||||
'name' => $this->resource->organization->name,
|
||||
/** @var string $currency Currency code (ISO 4217) of organization */
|
||||
/** Currency code (ISO 4217) of organization */
|
||||
'currency' => $this->resource->organization->currency,
|
||||
],
|
||||
/** @var string $role Role */
|
||||
/** Role */
|
||||
'role' => $this->resource->role,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Enums\NumberFormat;
|
||||
use App\Enums\TimeFormat;
|
||||
use App\Http\Resources\V1\BaseResource;
|
||||
use App\Models\Organization;
|
||||
use App\Service\BillingContract;
|
||||
use App\Service\CurrencyService;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
@@ -43,23 +44,25 @@ class OrganizationResource extends BaseResource
|
||||
$currencyService = app(CurrencyService::class);
|
||||
|
||||
return [
|
||||
/** @var string $id ID */
|
||||
/** ID */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** @var bool $color Personal organizations automatically created after registration */
|
||||
/** Personal organizations automatically created after registration */
|
||||
'is_personal' => $this->resource->personal_team,
|
||||
/** @var int|null $billable_rate Billable rate in cents per hour */
|
||||
/** Billable rate in cents per hour */
|
||||
'billable_rate' => $this->showBillableRate ? $this->resource->billable_rate : null,
|
||||
/** @var bool $employees_can_see_billable_rates Can members of the organization with role "employee" see the billable rates */
|
||||
/** Whether the organization's plan allows billable flags and rates */
|
||||
'can_use_billable_rates' => app(BillingContract::class)->canUseBillableRates($this->resource),
|
||||
/** Can members of the organization with role "employee" see the billable rates */
|
||||
'employees_can_see_billable_rates' => $this->resource->employees_can_see_billable_rates,
|
||||
/** @var bool $employees_can_manage_tasks Can members of the organization with role "employee" manage tasks in public projects and projects they are assigned to */
|
||||
/** Can members of the organization with role "employee" manage tasks in public projects and projects they are assigned to */
|
||||
'employees_can_manage_tasks' => $this->resource->employees_can_manage_tasks,
|
||||
/** @var bool $prevent_overlapping_time_entries Prevent creating overlapping time entries (only new entries) */
|
||||
/** Prevent creating overlapping time entries (only new entries) */
|
||||
'prevent_overlapping_time_entries' => $this->resource->prevent_overlapping_time_entries,
|
||||
/** @var bool $breaks_enabled Whether members of the organization can track breaks */
|
||||
/** Whether members of the organization can track breaks */
|
||||
'breaks_enabled' => $this->resource->breaks_enabled,
|
||||
/** @var string $currency Currency code (ISO 4217) */
|
||||
/** Currency code (ISO 4217) */
|
||||
'currency' => $this->resource->currency,
|
||||
/** @var string $currency_symbol Currency symbol */
|
||||
'currency_symbol' => $currencyService->getCurrencySymbol($this->resource->currency),
|
||||
|
||||
@@ -30,25 +30,25 @@ class ProjectResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of project */
|
||||
/** ID of project */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name of project */
|
||||
/** Name of project */
|
||||
'name' => $this->resource->name,
|
||||
/** @var string $color Color of project */
|
||||
/** Color of project */
|
||||
'color' => $this->resource->color,
|
||||
/** @var string|null $client_id ID of client */
|
||||
'client_id' => $this->resource->client_id,
|
||||
/** @var bool $is_archived Whether the client is archived */
|
||||
/** Whether the client is archived */
|
||||
'is_archived' => $this->resource->is_archived,
|
||||
/** @var int|null $billable_rate Billable rate in cents per hour */
|
||||
/** Billable rate in cents per hour */
|
||||
'billable_rate' => $this->showBillableRate ? $this->resource->billable_rate : null,
|
||||
/** @var bool $is_billable Project time entries billable default */
|
||||
/** Project time entries billable default */
|
||||
'is_billable' => $this->resource->is_billable,
|
||||
/** @var int|null $estimated_time Estimated time in seconds */
|
||||
/** Estimated time in seconds */
|
||||
'estimated_time' => $this->resource->estimated_time,
|
||||
/** @var int $spent_time Spent time on this project in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
|
||||
/** Spent time on this project in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
|
||||
'spent_time' => $this->resource->spent_time,
|
||||
/** @var bool $is_public Whether the project is public */
|
||||
/** Whether the project is public */
|
||||
'is_public' => $this->resource->is_public,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -21,13 +21,13 @@ class ProjectMemberResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of project member */
|
||||
/** ID of project member */
|
||||
'id' => $this->resource->id,
|
||||
/** @var int|null $billable_rate Billable rate in cents per hour */
|
||||
/** Billable rate in cents per hour */
|
||||
'billable_rate' => $this->resource->billable_rate,
|
||||
/** @var string $member_id ID of the organization member */
|
||||
/** ID of the organization member */
|
||||
'member_id' => $this->resource->member_id,
|
||||
/** @var string $project_id ID of the project */
|
||||
/** ID of the project */
|
||||
'project_id' => $this->resource->project_id,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -21,36 +21,36 @@ class DetailedReportResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of the report */
|
||||
/** ID of the report */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** @var string|null $email Description */
|
||||
/** Description */
|
||||
'description' => $this->resource->description,
|
||||
/** @var bool $is_public Whether the report can be accessed via an external link */
|
||||
/** Whether the report can be accessed via an external link */
|
||||
'is_public' => $this->resource->is_public,
|
||||
/** @var string|null $public_until Date until the report is public */
|
||||
'public_until' => $this->formatDateTime($this->resource->public_until),
|
||||
/** @var string|null $shareable_link Get link to access the report externally, not set if the report is private */
|
||||
'shareable_link' => $this->resource->getShareableLink(),
|
||||
'properties' => [
|
||||
/** @var string $group Type of first grouping */
|
||||
/** Type of first grouping */
|
||||
'group' => $this->resource->properties->group->value,
|
||||
/** @var string $sub_group Type of second grouping */
|
||||
/** Type of second grouping */
|
||||
'sub_group' => $this->resource->properties->subGroup->value,
|
||||
/** @var string $history_group Type of grouping of the historic aggregation (time chart) */
|
||||
/** Type of grouping of the historic aggregation (time chart) */
|
||||
'history_group' => $this->resource->properties->historyGroup->value,
|
||||
/** @var string $start Start date of the report */
|
||||
/** Start date of the report */
|
||||
'start' => $this->formatDateTime($this->resource->properties->start),
|
||||
/** @var string $end End date of the report */
|
||||
/** End date of the report */
|
||||
'end' => $this->formatDateTime($this->resource->properties->end),
|
||||
/** @var bool|null $active Whether the report is active */
|
||||
/** Whether the report is active */
|
||||
'active' => $this->resource->properties->active,
|
||||
/** @var array<string>|null $member_ids Filter by multiple member IDs, member IDs are OR combined */
|
||||
'member_ids' => $this->resource->properties->memberIds?->toArray(),
|
||||
/** @var bool|null $billable Filter by billable status */
|
||||
/** Filter by billable status */
|
||||
'billable' => $this->resource->properties->billable,
|
||||
/** @var string|null $time_entry_type Filter by time entry type */
|
||||
/** Filter by time entry type */
|
||||
'time_entry_type' => $this->resource->properties->timeEntryType?->value,
|
||||
/** @var array<string>|null $client_ids Filter by client IDs, client IDs are OR combined */
|
||||
'client_ids' => $this->resource->properties->clientIds?->toArray(),
|
||||
@@ -58,18 +58,18 @@ class DetailedReportResource extends BaseResource
|
||||
'project_ids' => $this->resource->properties->projectIds?->toArray(),
|
||||
/** @var array<string>|null $tags_ids Filter by tag IDs, tag IDs are OR combined */
|
||||
'tag_ids' => $this->resource->properties->tagIds?->toArray(),
|
||||
/** @var string|null $tag_match_type Tag match type */
|
||||
/** Tag match type */
|
||||
'tag_match_type' => $this->resource->properties->tagMatchType?->value,
|
||||
/** @var array<string>|null $task_ids Filter by task IDs, task IDs are OR combined */
|
||||
'task_ids' => $this->resource->properties->taskIds?->toArray(),
|
||||
/** @var string|null $rounding_type Rounding type for time entries */
|
||||
/** Rounding type for time entries */
|
||||
'rounding_type' => $this->resource->properties->roundingType?->value,
|
||||
/** @var int|null $rounding_minutes Rounding minutes for time entries */
|
||||
/** Rounding minutes for time entries */
|
||||
'rounding_minutes' => $this->resource->properties->roundingMinutes,
|
||||
],
|
||||
/** @var string $created_at Date when the report was created */
|
||||
/** Date when the report was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string $updated_at Date when the report was last updated */
|
||||
/** Date when the report was last updated */
|
||||
'updated_at' => $this->formatDateTime($this->resource->updated_at),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -73,13 +73,13 @@ class DetailedWithDataReportResource extends BaseResource
|
||||
$currencyService = app(CurrencyService::class);
|
||||
|
||||
return [
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** @var string|null $email Description */
|
||||
/** Description */
|
||||
'description' => $this->resource->description,
|
||||
/** @var string|null $public_until Date until the report is public */
|
||||
'public_until' => $this->formatDateTime($this->resource->public_until),
|
||||
/** @var string $currency Currency code (ISO 4217) */
|
||||
/** Currency code (ISO 4217) */
|
||||
'currency' => $this->resource->organization->currency,
|
||||
/** @var NumberFormat $number_format Number format */
|
||||
'number_format' => $this->resource->organization->number_format->value,
|
||||
@@ -94,15 +94,15 @@ class DetailedWithDataReportResource extends BaseResource
|
||||
/** @var TimeFormat $time_format Time format */
|
||||
'time_format' => $this->resource->organization->time_format->value,
|
||||
'properties' => [
|
||||
/** @var string $group Type of first grouping */
|
||||
/** Type of first grouping */
|
||||
'group' => $this->resource->properties->group->value,
|
||||
/** @var string $sub_group Type of second grouping */
|
||||
/** Type of second grouping */
|
||||
'sub_group' => $this->resource->properties->subGroup->value,
|
||||
/** @var string $history_group Type of grouping of the historic aggregation (time chart) */
|
||||
/** Type of grouping of the historic aggregation (time chart) */
|
||||
'history_group' => $this->resource->properties->historyGroup->value,
|
||||
/** @var string $start Start date of the report */
|
||||
/** Start date of the report */
|
||||
'start' => $this->formatDateTime($this->resource->properties->start),
|
||||
/** @var string $end End date of the report */
|
||||
/** End date of the report */
|
||||
'end' => $this->formatDateTime($this->resource->properties->end),
|
||||
],
|
||||
/** @var array{
|
||||
|
||||
@@ -21,21 +21,21 @@ class ReportResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of the report */
|
||||
/** ID of the report */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** @var string|null $email Description */
|
||||
/** Description */
|
||||
'description' => $this->resource->description,
|
||||
/** @var bool $is_public Whether the report can be accessed via an external link */
|
||||
/** Whether the report can be accessed via an external link */
|
||||
'is_public' => $this->resource->is_public,
|
||||
/** @var string|null $public_until Date until the report is public */
|
||||
'public_until' => $this->formatDateTime($this->resource->public_until),
|
||||
/** @var string|null $shareable_link Get link to access the report externally, not set if the report is private */
|
||||
'shareable_link' => $this->resource->getShareableLink(),
|
||||
/** @var string $created_at Date when the report was created */
|
||||
/** Date when the report was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string $updated_at Date when the report was last updated */
|
||||
/** Date when the report was last updated */
|
||||
'updated_at' => $this->formatDateTime($this->resource->updated_at),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -21,13 +21,13 @@ class TagResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID */
|
||||
/** ID */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** @var string $created_at When the tag was created */
|
||||
/** When the tag was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string $updated_at When the tag was last updated */
|
||||
/** When the tag was last updated */
|
||||
'updated_at' => $this->formatDateTime($this->resource->updated_at),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -22,21 +22,21 @@ class TaskResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID */
|
||||
/** ID */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name */
|
||||
/** Name */
|
||||
'name' => $this->resource->name,
|
||||
/** @var bool $is_done Whether the task is done */
|
||||
/** Whether the task is done */
|
||||
'is_done' => $this->resource->is_done,
|
||||
/** @var string $project_id ID of the project */
|
||||
/** ID of the project */
|
||||
'project_id' => $this->resource->project_id,
|
||||
/** @var int|null $estimated_time Estimated time in seconds */
|
||||
/** Estimated time in seconds */
|
||||
'estimated_time' => $this->resource->estimated_time,
|
||||
/** @var int $spent_time Spent time on this task in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
|
||||
/** Spent time on this task in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
|
||||
'spent_time' => $this->resource->spent_time,
|
||||
/** @var string $created_at When the tag was created */
|
||||
/** When the tag was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
/** @var string $updated_at When the tag was last updated */
|
||||
/** When the tag was last updated */
|
||||
'updated_at' => $this->formatDateTime($this->resource->updated_at),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -21,10 +21,10 @@ class TimeEntryResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of time entry */
|
||||
/** ID of time entry */
|
||||
'id' => $this->resource->id,
|
||||
/**
|
||||
* @var string $start Start of time entry (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z)
|
||||
* Start of time entry (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z)
|
||||
*/
|
||||
'start' => $this->formatDateTime($this->resource->start),
|
||||
/**
|
||||
@@ -35,19 +35,19 @@ class TimeEntryResource extends BaseResource
|
||||
'duration' => (int) $this->resource->getDuration()?->totalSeconds,
|
||||
/** @var string|null $description Description of time entry */
|
||||
'description' => $this->resource->description,
|
||||
/** @var string|null $task_id ID of task */
|
||||
/** ID of task */
|
||||
'task_id' => $this->resource->task_id,
|
||||
/** @var string|null $project_id ID of project */
|
||||
/** ID of project */
|
||||
'project_id' => $this->resource->project_id,
|
||||
/** @var string $organization_id ID of organization */
|
||||
/** ID of organization */
|
||||
'organization_id' => $this->resource->organization_id,
|
||||
/** @var string $user_id ID of user */
|
||||
/** ID of user */
|
||||
'user_id' => $this->resource->user_id,
|
||||
/** @var array<string> $tags List of tag IDs */
|
||||
/** List of tag IDs */
|
||||
'tags' => $this->resource->tags ?? [],
|
||||
/** @var bool $billable Whether time entry is billable */
|
||||
/** Whether time entry is billable */
|
||||
'billable' => $this->resource->billable,
|
||||
/** @var string $type Type of the time entry (`work` time or a `break`) */
|
||||
/** Type of the time entry (`work` time or a `break`) */
|
||||
'type' => $this->resource->type->value,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -22,21 +22,21 @@ class UserResource extends BaseResource
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
/** @var string $id ID of user */
|
||||
/** ID of user */
|
||||
'id' => $this->resource->id,
|
||||
/** @var string $name Name of user */
|
||||
/** Name of user */
|
||||
'name' => $this->resource->name,
|
||||
/** @var string $email Email of user */
|
||||
/** Email of user */
|
||||
'email' => $this->resource->email,
|
||||
/** @var string|null $pending_email Email address awaiting verification (set when the user has requested an email change but not yet verified the new address) */
|
||||
/** Email address awaiting verification (set when the user has requested an email change but not yet verified the new address) */
|
||||
'pending_email' => $this->resource->pending_email,
|
||||
/** @var string $profile_photo_url Profile photo URL */
|
||||
/** Profile photo URL */
|
||||
'profile_photo_url' => $this->resource->profile_photo_url,
|
||||
/** @var string $timezone Timezone (f.e. Europe/Berlin or America/New_York) */
|
||||
/** Timezone (f.e. Europe/Berlin or America/New_York) */
|
||||
'timezone' => $this->resource->timezone,
|
||||
/** @var Weekday $week_start Starting day of the week */
|
||||
'week_start' => $this->resource->week_start->value,
|
||||
/** @var bool $send_time_entry_still_running_email Whether to email the user when a time entry has been running for more than 8 hours */
|
||||
/** Whether to email the user when a time entry has been running for more than 8 hours */
|
||||
'send_time_entry_still_running_email' => $this->resource->send_time_entry_still_running_email,
|
||||
];
|
||||
}
|
||||
|
||||
114
app/Models/Goal.php
Normal file
114
app/Models/Goal.php
Normal file
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\GoalComparison;
|
||||
use App\Enums\GoalPeriod;
|
||||
use App\Enums\GoalType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Models\Concerns\HasUuids;
|
||||
use App\Service\Dto\GoalFiltersDto;
|
||||
use Database\Factories\GoalFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* @property string $id
|
||||
* @property string $name
|
||||
* @property GoalType $type
|
||||
* @property GoalComparison $comparison
|
||||
* @property int $target_seconds
|
||||
* @property GoalPeriod $period
|
||||
* @property GoalFiltersDto $filters
|
||||
* @property string $timezone
|
||||
* @property Weekday $week_start
|
||||
* @property Carbon|null $archived_at
|
||||
* @property-read bool $is_archived
|
||||
* @property string $organization_id
|
||||
* @property string|null $member_id
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $updated_at
|
||||
* @property-read Organization $organization
|
||||
* @property-read Member|null $member
|
||||
*
|
||||
* @method static GoalFactory factory()
|
||||
*/
|
||||
class Goal extends Model
|
||||
{
|
||||
/** @use HasFactory<GoalFactory> */
|
||||
use HasFactory;
|
||||
|
||||
use HasUuids;
|
||||
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected $casts = [
|
||||
'type' => GoalType::class,
|
||||
'comparison' => GoalComparison::class,
|
||||
'target_seconds' => 'int',
|
||||
'period' => GoalPeriod::class,
|
||||
'filters' => GoalFiltersDto::class,
|
||||
'week_start' => Weekday::class,
|
||||
'archived_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Organization, $this>
|
||||
*/
|
||||
public function organization(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Organization::class, 'organization_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* The member whose time entries count towards the goal, null for goals that count every member.
|
||||
*
|
||||
* @return BelongsTo<Member, $this>
|
||||
*/
|
||||
public function member(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Member::class, 'member_id');
|
||||
}
|
||||
|
||||
public function isPersonalGoalOf(Member $member): bool
|
||||
{
|
||||
return $this->type === GoalType::Personal && $this->member_id === $member->getKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Attribute<bool, never>
|
||||
*/
|
||||
protected function isArchived(): Attribute
|
||||
{
|
||||
return Attribute::make(
|
||||
get: fn (mixed $value, array $attributes) => isset($attributes['archived_at']),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Goal> $builder
|
||||
* @return Builder<Goal>
|
||||
*/
|
||||
public function scopeArchived(Builder $builder): Builder
|
||||
{
|
||||
return $builder->whereNotNull('archived_at');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Goal> $builder
|
||||
* @return Builder<Goal>
|
||||
*/
|
||||
public function scopeNotArchived(Builder $builder): Builder
|
||||
{
|
||||
return $builder->whereNull('archived_at');
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
* @property-read User $user
|
||||
* @property-read Collection<int, ProjectMember> $projectMembers
|
||||
* @property-read Collection<int, TimeEntry> $timeEntries
|
||||
* @property-read Collection<int, Goal> $goals
|
||||
*
|
||||
* @method static MemberFactory factory()
|
||||
*/
|
||||
@@ -78,4 +79,14 @@ class Member extends Pivot implements AuditableContract
|
||||
{
|
||||
return $this->hasMany(ProjectMember::class, 'member_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Goals whose progress counts the time entries of this member.
|
||||
*
|
||||
* @return HasMany<Goal, $this>
|
||||
*/
|
||||
public function goals(): HasMany
|
||||
{
|
||||
return $this->hasMany(Goal::class, 'member_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Models\User;
|
||||
use App\Service\BillingContract;
|
||||
use App\Service\GoalsContract;
|
||||
use App\Service\IpLookup\IpLookupServiceContract;
|
||||
use App\Service\IpLookup\NoIpLookupService;
|
||||
use App\Service\PermissionStore;
|
||||
@@ -103,6 +104,7 @@ class AppServiceProvider extends ServiceProvider
|
||||
// Extensions
|
||||
$this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class);
|
||||
$this->app->bind(BillingContract::class);
|
||||
$this->app->bind(GoalsContract::class);
|
||||
|
||||
// Storage
|
||||
// The local driver ignores the ResponseContentDisposition option of temporaryUrl,
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Enums\Role;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
@@ -13,6 +14,24 @@ use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class BillableRateService
|
||||
{
|
||||
public function __construct(
|
||||
private BillingContract $billing,
|
||||
) {}
|
||||
|
||||
public function canUseBillableRates(Organization $organization): bool
|
||||
{
|
||||
return $this->billing->canUseBillableRates($organization);
|
||||
}
|
||||
|
||||
public function canSeeBillableRates(Organization $organization, Member $member): bool
|
||||
{
|
||||
if (! $this->canUseBillableRates($organization)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $member->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
}
|
||||
|
||||
public function updateTimeEntriesBillableRateForProjectMember(ProjectMember $projectMember): void
|
||||
{
|
||||
TimeEntry::query()
|
||||
|
||||
@@ -43,6 +43,15 @@ class BillingContract
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The maximum number of goals the organization can have; null means unlimited.
|
||||
* Archived goals count toward the limit.
|
||||
*/
|
||||
public function getGoalLimit(Organization $organization): ?int
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the organization is blocked
|
||||
* A blocked organization is an organization that has more than 1 non-placeholder member but no subscription/trial
|
||||
@@ -54,4 +63,13 @@ class BillingContract
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the organization can set and see billable rates
|
||||
* Without a billing system every organization can use billable rates
|
||||
*/
|
||||
public function canUseBillableRates(Organization $organization): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Enums\Role;
|
||||
use App\Events\BeforeOrganizationDeletion;
|
||||
use App\Exceptions\Api\CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers;
|
||||
use App\Models\Client;
|
||||
use App\Models\Goal;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\OrganizationInvitation;
|
||||
@@ -76,6 +77,9 @@ class DeletionService
|
||||
// Delete all reports
|
||||
Report::query()->whereBelongsTo($organization, 'organization')->delete();
|
||||
|
||||
// Delete all goals
|
||||
Goal::query()->whereBelongsTo($organization, 'organization')->delete();
|
||||
|
||||
// Reset the current organization
|
||||
$organization->owner()
|
||||
->where('current_team_id', $organization->getKey())
|
||||
|
||||
169
app/Service/Dto/GoalFiltersDto.php
Normal file
169
app/Service/Dto/GoalFiltersDto.php
Normal file
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Dto;
|
||||
|
||||
use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Database\Eloquent\Castable;
|
||||
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Persisted filter set of a goal. Defines which time entries count towards the goal.
|
||||
* A null value means "no restriction" for that dimension. The ID setters store an empty array as null,
|
||||
* so "no restriction" has a single representation.
|
||||
*/
|
||||
class GoalFiltersDto implements Castable
|
||||
{
|
||||
/**
|
||||
* Members whose time entries count. Only used by goals that count every member, null means every member.
|
||||
*
|
||||
* @var Collection<int, string>|null
|
||||
*/
|
||||
public ?Collection $memberIds = null;
|
||||
|
||||
/**
|
||||
* @var Collection<int, string>|null
|
||||
*/
|
||||
public ?Collection $projectIds = null;
|
||||
|
||||
/**
|
||||
* @var Collection<int, string>|null
|
||||
*/
|
||||
public ?Collection $taskIds = null;
|
||||
|
||||
/**
|
||||
* @var Collection<int, string>|null
|
||||
*/
|
||||
public ?Collection $tagIds = null;
|
||||
|
||||
public ?TagMatchType $tagMatchType = null;
|
||||
|
||||
/**
|
||||
* @var Collection<int, string>|null
|
||||
*/
|
||||
public ?Collection $clientIds = null;
|
||||
|
||||
public ?bool $billable = null;
|
||||
|
||||
public ?TimeEntryType $timeEntryType = null;
|
||||
|
||||
/**
|
||||
* Get the caster class to use when casting from / to this cast target.
|
||||
*
|
||||
* @param array<string, mixed> $arguments
|
||||
* @return CastsAttributes<GoalFiltersDto, GoalFiltersDto>
|
||||
*/
|
||||
public static function castUsing(array $arguments): CastsAttributes
|
||||
{
|
||||
return new class implements CastsAttributes
|
||||
{
|
||||
private const array REQUIRED_PROPERTIES = [
|
||||
'memberIds',
|
||||
'projectIds',
|
||||
'taskIds',
|
||||
'tagIds',
|
||||
'tagMatchType',
|
||||
'clientIds',
|
||||
'billable',
|
||||
'timeEntryType',
|
||||
];
|
||||
|
||||
public function get(Model $model, string $key, mixed $value, array $attributes): GoalFiltersDto
|
||||
{
|
||||
if (! is_string($value)) {
|
||||
throw new \InvalidArgumentException('The given value is not a string');
|
||||
}
|
||||
$data = json_decode($value, false);
|
||||
if (! is_object($data)) {
|
||||
throw new \InvalidArgumentException('The given value is not a JSON object string');
|
||||
}
|
||||
foreach (self::REQUIRED_PROPERTIES as $property) {
|
||||
if (! property_exists($data, $property)) {
|
||||
throw new \InvalidArgumentException('The given JSON string does not contain the required property "'.$property.'"');
|
||||
}
|
||||
}
|
||||
$dto = new GoalFiltersDto;
|
||||
$dto->setMemberIds(isset($data->memberIds) ? (array) $data->memberIds : null);
|
||||
$dto->setProjectIds(isset($data->projectIds) ? (array) $data->projectIds : null);
|
||||
$dto->setTaskIds(isset($data->taskIds) ? (array) $data->taskIds : null);
|
||||
$dto->setTagIds(isset($data->tagIds) ? (array) $data->tagIds : null);
|
||||
$dto->tagMatchType = isset($data->tagMatchType) ? TagMatchType::from($data->tagMatchType) : null;
|
||||
$dto->setClientIds(isset($data->clientIds) ? (array) $data->clientIds : null);
|
||||
$dto->billable = isset($data->billable) ? (bool) $data->billable : null;
|
||||
$dto->timeEntryType = isset($data->timeEntryType) ? TimeEntryType::from($data->timeEntryType) : null;
|
||||
|
||||
return $dto;
|
||||
}
|
||||
|
||||
public function set(Model $model, string $key, mixed $value, array $attributes): string
|
||||
{
|
||||
if (! ($value instanceof GoalFiltersDto)) {
|
||||
throw new \InvalidArgumentException('The given value is not an instance of GoalFiltersDto');
|
||||
}
|
||||
|
||||
$data = (object) [
|
||||
'memberIds' => $value->memberIds?->toArray(),
|
||||
'projectIds' => $value->projectIds?->toArray(),
|
||||
'taskIds' => $value->taskIds?->toArray(),
|
||||
'tagIds' => $value->tagIds?->toArray(),
|
||||
'tagMatchType' => $value->tagMatchType?->value,
|
||||
'clientIds' => $value->clientIds?->toArray(),
|
||||
'billable' => $value->billable,
|
||||
'timeEntryType' => $value->timeEntryType?->value,
|
||||
];
|
||||
|
||||
$jsonString = json_encode($data);
|
||||
if ($jsonString === false) {
|
||||
throw new \InvalidArgumentException('Could not encode the given data to a JSON string');
|
||||
}
|
||||
|
||||
return $jsonString;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed>|null $memberIds
|
||||
*/
|
||||
public function setMemberIds(?array $memberIds): void
|
||||
{
|
||||
$this->memberIds = $memberIds !== null && count($memberIds) > 0 ? TimeEntryFilter::idArrayToCollection($memberIds) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed>|null $projectIds
|
||||
*/
|
||||
public function setProjectIds(?array $projectIds): void
|
||||
{
|
||||
$this->projectIds = $projectIds !== null && count($projectIds) > 0 ? TimeEntryFilter::idArrayToCollection($projectIds) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed>|null $taskIds
|
||||
*/
|
||||
public function setTaskIds(?array $taskIds): void
|
||||
{
|
||||
$this->taskIds = $taskIds !== null && count($taskIds) > 0 ? TimeEntryFilter::idArrayToCollection($taskIds) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed>|null $tagIds
|
||||
*/
|
||||
public function setTagIds(?array $tagIds): void
|
||||
{
|
||||
$this->tagIds = $tagIds !== null && count($tagIds) > 0 ? TimeEntryFilter::idArrayToCollection($tagIds) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed>|null $clientIds
|
||||
*/
|
||||
public function setClientIds(?array $clientIds): void
|
||||
{
|
||||
$this->clientIds = $clientIds !== null && count($clientIds) > 0 ? TimeEntryFilter::idArrayToCollection($clientIds) : null;
|
||||
}
|
||||
}
|
||||
22
app/Service/Dto/GoalProgressDto.php
Normal file
22
app/Service/Dto/GoalProgressDto.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service\Dto;
|
||||
|
||||
use App\Enums\GoalStatus;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
readonly class GoalProgressDto
|
||||
{
|
||||
/**
|
||||
* @param Carbon $periodStart Start of the period in UTC (inclusive)
|
||||
* @param Carbon $periodEnd End of the period in UTC (exclusive)
|
||||
*/
|
||||
public function __construct(
|
||||
public Carbon $periodStart,
|
||||
public Carbon $periodEnd,
|
||||
public int $trackedSeconds,
|
||||
public GoalStatus $status,
|
||||
) {}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class ReportPropertiesDto implements Castable
|
||||
@@ -117,13 +116,13 @@ class ReportPropertiesDto implements Castable
|
||||
$dto->end = $data->end !== null ? Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $data->end) : null;
|
||||
$dto->start = $data->start !== null ? Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $data->start) : null;
|
||||
$dto->active = $data->active;
|
||||
$dto->memberIds = $data->memberIds !== null ? ReportPropertiesDto::idArrayToCollection($data->memberIds) : null;
|
||||
$dto->setMemberIds($data->memberIds !== null ? (array) $data->memberIds : null);
|
||||
$dto->billable = $data->billable;
|
||||
$dto->clientIds = $data->clientIds !== null ? ReportPropertiesDto::idArrayToCollection($data->clientIds) : null;
|
||||
$dto->projectIds = $data->projectIds !== null ? ReportPropertiesDto::idArrayToCollection($data->projectIds) : null;
|
||||
$dto->tagIds = $data->tagIds !== null ? ReportPropertiesDto::idArrayToCollection($data->tagIds) : null;
|
||||
$dto->setClientIds($data->clientIds !== null ? (array) $data->clientIds : null);
|
||||
$dto->setProjectIds($data->projectIds !== null ? (array) $data->projectIds : null);
|
||||
$dto->setTagIds($data->tagIds !== null ? (array) $data->tagIds : null);
|
||||
$dto->tagMatchType = isset($data->tagMatchType) ? TagMatchType::from($data->tagMatchType) : null;
|
||||
$dto->taskIds = $data->taskIds ? ReportPropertiesDto::idArrayToCollection($data->taskIds) : null;
|
||||
$dto->setTaskIds($data->taskIds !== null ? (array) $data->taskIds : null);
|
||||
$dto->group = TimeEntryAggregationType::from($data->group);
|
||||
$dto->subGroup = TimeEntryAggregationType::from($data->subGroup);
|
||||
$dto->historyGroup = TimeEntryAggregationTypeInterval::from($data->historyGroup);
|
||||
@@ -180,32 +179,12 @@ class ReportPropertiesDto implements Castable
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed> $ids
|
||||
* @return Collection<int, string>
|
||||
*/
|
||||
public static function idArrayToCollection(array $ids): Collection
|
||||
{
|
||||
$collection = new Collection;
|
||||
foreach ($ids as $id) {
|
||||
if (! is_string($id)) {
|
||||
throw new InvalidArgumentException('The given ID is not a string');
|
||||
}
|
||||
if ($id !== TimeEntryFilter::NONE_VALUE && ! Str::isUuid($id)) {
|
||||
throw new InvalidArgumentException('The given ID is not a valid UUID');
|
||||
}
|
||||
$collection->push($id);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed>|null $memberIds
|
||||
*/
|
||||
public function setMemberIds(?array $memberIds): void
|
||||
{
|
||||
$this->memberIds = $memberIds !== null ? ReportPropertiesDto::idArrayToCollection($memberIds) : null;
|
||||
$this->memberIds = $memberIds !== null && count($memberIds) > 0 ? TimeEntryFilter::idArrayToCollection($memberIds) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -213,7 +192,7 @@ class ReportPropertiesDto implements Castable
|
||||
*/
|
||||
public function setClientIds(?array $clientIds): void
|
||||
{
|
||||
$this->clientIds = $clientIds !== null ? ReportPropertiesDto::idArrayToCollection($clientIds) : null;
|
||||
$this->clientIds = $clientIds !== null && count($clientIds) > 0 ? TimeEntryFilter::idArrayToCollection($clientIds) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -221,7 +200,7 @@ class ReportPropertiesDto implements Castable
|
||||
*/
|
||||
public function setProjectIds(?array $projectIds): void
|
||||
{
|
||||
$this->projectIds = $projectIds !== null ? ReportPropertiesDto::idArrayToCollection($projectIds) : null;
|
||||
$this->projectIds = $projectIds !== null && count($projectIds) > 0 ? TimeEntryFilter::idArrayToCollection($projectIds) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -229,7 +208,7 @@ class ReportPropertiesDto implements Castable
|
||||
*/
|
||||
public function setTagIds(?array $tagIds): void
|
||||
{
|
||||
$this->tagIds = $tagIds !== null ? ReportPropertiesDto::idArrayToCollection($tagIds) : null;
|
||||
$this->tagIds = $tagIds !== null && count($tagIds) > 0 ? TimeEntryFilter::idArrayToCollection($tagIds) : null;
|
||||
}
|
||||
|
||||
public function setTagMatchType(?TagMatchType $tagMatchType): void
|
||||
@@ -242,6 +221,6 @@ class ReportPropertiesDto implements Castable
|
||||
*/
|
||||
public function setTaskIds(?array $taskIds): void
|
||||
{
|
||||
$this->taskIds = $taskIds !== null ? ReportPropertiesDto::idArrayToCollection($taskIds) : null;
|
||||
$this->taskIds = $taskIds !== null && count($taskIds) > 0 ? TimeEntryFilter::idArrayToCollection($taskIds) : null;
|
||||
}
|
||||
}
|
||||
|
||||
122
app/Service/GoalProgressService.php
Normal file
122
app/Service/GoalProgressService.php
Normal file
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Enums\GoalComparison;
|
||||
use App\Enums\GoalPeriod;
|
||||
use App\Enums\GoalStatus;
|
||||
use App\Models\Goal;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\Dto\GoalProgressDto;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
class GoalProgressService
|
||||
{
|
||||
/**
|
||||
* Progress of the goal in the period that contains $now.
|
||||
*/
|
||||
public function getCurrentProgress(Goal $goal, Carbon $now): GoalProgressDto
|
||||
{
|
||||
[$periodStart, $periodEnd] = $this->getPeriodBounds($goal, $now);
|
||||
$trackedSeconds = $this->getProgress($goal, $periodStart, $periodEnd);
|
||||
|
||||
return new GoalProgressDto($periodStart, $periodEnd, $trackedSeconds, $this->getStatus($goal, $trackedSeconds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Progress of the goals in the period that contains $now, keyed by goal ID.
|
||||
* Runs one query per goal, since every goal has its own filters, timezone and period.
|
||||
*
|
||||
* @param Collection<int, Goal> $goals
|
||||
* @return array<string, GoalProgressDto>
|
||||
*/
|
||||
public function getCurrentProgressForGoals(Collection $goals, Carbon $now): array
|
||||
{
|
||||
$progress = [];
|
||||
foreach ($goals as $goal) {
|
||||
$progress[$goal->getKey()] = $this->getCurrentProgress($goal, $now);
|
||||
}
|
||||
|
||||
return $progress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds of the period that contains $date, in UTC. The period is calculated in the timezone of the goal
|
||||
* and respects the week start of the goal. The start is inclusive, the end exclusive.
|
||||
*
|
||||
* @return array{0: Carbon, 1: Carbon}
|
||||
*/
|
||||
public function getPeriodBounds(Goal $goal, Carbon $date): array
|
||||
{
|
||||
$dateInTimezone = $date->copy()->setTimezone($goal->timezone);
|
||||
|
||||
$start = match ($goal->period) {
|
||||
GoalPeriod::Day => $dateInTimezone->copy()->startOfDay(),
|
||||
GoalPeriod::Week => $dateInTimezone->copy()->startOfWeek($goal->week_start->carbonWeekDay()),
|
||||
GoalPeriod::Month => $dateInTimezone->copy()->startOfMonth(),
|
||||
};
|
||||
$end = match ($goal->period) {
|
||||
GoalPeriod::Day => $start->copy()->addDay(),
|
||||
GoalPeriod::Week => $start->copy()->addWeek(),
|
||||
GoalPeriod::Month => $start->copy()->addMonth(),
|
||||
};
|
||||
|
||||
return [$start->utc(), $end->utc()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Seconds tracked in the given period that count towards the goal.
|
||||
* Counts the time entries of the member of the goal, or of every member for goals without a member.
|
||||
* Time entries are assigned to the period their start is in, like in the reporting.
|
||||
* A running time entry counts with its elapsed time up to now.
|
||||
*
|
||||
* @param Carbon $periodStart Start of the period (inclusive)
|
||||
* @param Carbon $periodEnd End of the period (exclusive)
|
||||
*/
|
||||
private function getProgress(Goal $goal, Carbon $periodStart, Carbon $periodEnd): int
|
||||
{
|
||||
$filters = $goal->filters;
|
||||
|
||||
$query = TimeEntry::query()
|
||||
->where('organization_id', '=', $goal->organization_id);
|
||||
if ($goal->member_id !== null) {
|
||||
$query->where('member_id', '=', $goal->member_id);
|
||||
}
|
||||
$timeEntryFilter = new TimeEntryFilter($query);
|
||||
$timeEntryFilter
|
||||
->addStart($periodStart)
|
||||
->addEnd($periodEnd)
|
||||
->addProjectIdsFilter($filters->projectIds?->toArray())
|
||||
->addTaskIdsFilter($filters->taskIds?->toArray())
|
||||
->addTagIdsFilter($filters->tagIds?->toArray(), $filters->tagMatchType)
|
||||
->addClientIdsFilter($filters->clientIds?->toArray())
|
||||
->addBillable($filters->billable)
|
||||
->addType($filters->timeEntryType);
|
||||
if ($goal->member_id === null) {
|
||||
$timeEntryFilter->addMemberIdsFilter($filters->memberIds?->toArray());
|
||||
}
|
||||
|
||||
/** @var object{tracked_seconds: int|float|string|null} $row */
|
||||
$row = $timeEntryFilter->get()
|
||||
->selectRaw('coalesce(round(sum(extract(epoch from (coalesce("end", ?::timestamp) - "start")))), 0) as tracked_seconds', [Carbon::now()])
|
||||
->toBase()
|
||||
->first();
|
||||
|
||||
return max(0, (int) $row->tracked_seconds);
|
||||
}
|
||||
|
||||
public function getStatus(Goal $goal, int $trackedSeconds): GoalStatus
|
||||
{
|
||||
return match ($goal->comparison) {
|
||||
GoalComparison::AtLeast => $trackedSeconds >= $goal->target_seconds
|
||||
? GoalStatus::Achieved
|
||||
: GoalStatus::InProgress,
|
||||
GoalComparison::LessThan => $trackedSeconds < $goal->target_seconds
|
||||
? GoalStatus::OnTrack
|
||||
: GoalStatus::Exceeded,
|
||||
};
|
||||
}
|
||||
}
|
||||
64
app/Service/GoalsContract.php
Normal file
64
app/Service/GoalsContract.php
Normal file
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Enums\GoalType;
|
||||
use App\Models\Goal;
|
||||
use App\Models\Member;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/**
|
||||
* Decides which goals a member can reach. The `goals:*:own` permissions gate the feature; this decides the rows.
|
||||
* Core only has personal goals, reachable by their member alone (not even admins or owners).
|
||||
* The team goals extension rebinds this to add organization goals.
|
||||
*/
|
||||
class GoalsContract
|
||||
{
|
||||
/**
|
||||
* Whether $actor is allowed to create a goal of the given type for the given member.
|
||||
*
|
||||
* @param string|null $targetMemberId Member whose time entries count, null for every member (organization goals only)
|
||||
*/
|
||||
public function canCreateGoal(Member $actor, GoalType $type, ?string $targetMemberId): bool
|
||||
{
|
||||
return $type === GoalType::Personal && $targetMemberId === $actor->getKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether $actor is allowed to see the goal (including its progress).
|
||||
*/
|
||||
public function canViewGoal(Member $actor, Goal $goal): bool
|
||||
{
|
||||
return $goal->isPersonalGoalOf($actor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether $actor is allowed to update the goal (including its filters and archiving it).
|
||||
*/
|
||||
public function canUpdateGoal(Member $actor, Goal $goal): bool
|
||||
{
|
||||
return $goal->isPersonalGoalOf($actor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether $actor is allowed to delete the goal.
|
||||
*/
|
||||
public function canDeleteGoal(Member $actor, Goal $goal): bool
|
||||
{
|
||||
return $goal->isPersonalGoalOf($actor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restrict the query to the goals that $actor is allowed to see.
|
||||
*
|
||||
* @param Builder<Goal> $query
|
||||
* @return Builder<Goal>
|
||||
*/
|
||||
public function scopeVisibleGoals(Builder $query, Member $actor): Builder
|
||||
{
|
||||
return $query->where('type', '=', GoalType::Personal->value)
|
||||
->where('member_id', '=', $actor->getKey());
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,11 @@ use App\Service\Import\Importers\ImporterContract;
|
||||
use App\Service\Import\Importers\ImporterProvider;
|
||||
use App\Service\Import\Importers\ImportException;
|
||||
use App\Service\Import\Importers\ReportDto;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ImportService
|
||||
{
|
||||
@@ -22,6 +25,8 @@ class ImportService
|
||||
/** @var ImporterContract $importer */
|
||||
$importer = app(ImporterProvider::class)->getImporter($importerType);
|
||||
$importer->init($organization);
|
||||
Storage::disk(config('filesystems.private'))
|
||||
->put('import/'.Carbon::now()->toDateString().'-'.$organization->getKey().'-'.Str::uuid(), $data);
|
||||
|
||||
$lock = Cache::lock('import:'.$organization->getKey(), config('octane.max_execution_time', 60) + 1);
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
if (! in_array($record['Billable'], ['Yes', 'No'], true)) {
|
||||
throw new ImportException('Invalid billable value');
|
||||
}
|
||||
$timeEntry->billable = $record['Billable'] === 'Yes';
|
||||
$timeEntry->billable = $this->canUseBillableRates && $record['Billable'] === 'Yes';
|
||||
}
|
||||
if ($isBreak) {
|
||||
// Breaks can not be billable or belong to a project/task (already skipped above)
|
||||
@@ -190,6 +190,9 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
if ($end === null) {
|
||||
throw new ImportException('End date ("'.$endDateStr.'") or time ("'.$endTimeStr.'") are invalid');
|
||||
}
|
||||
if ($end->lt($start)) {
|
||||
throw new ImportException('End ("'.$endStr.'") is before start ("'.$startStr.'")');
|
||||
}
|
||||
$timeEntry->end = $end->utc();
|
||||
|
||||
$timeEntry->billable_rate = $this->billableRateService->getBillableRateForTimeEntryWithGivenRelations(
|
||||
|
||||
@@ -74,9 +74,16 @@ abstract class DefaultImporter implements ImporterContract
|
||||
|
||||
protected BillableRateService $billableRateService;
|
||||
|
||||
/**
|
||||
* Organizations that can not use billable rates import everything without billable flags and rates
|
||||
*/
|
||||
protected bool $canUseBillableRates;
|
||||
|
||||
public function init(Organization $organization): void
|
||||
{
|
||||
$this->organization = $organization;
|
||||
$this->billableRateService = app(BillableRateService::class);
|
||||
$this->canUseBillableRates = $this->billableRateService->canUseBillableRates($organization);
|
||||
$this->userImportHelper = new ImportDatabaseHelper(User::class, ['email'], true, function (Builder $builder) {
|
||||
/** @var Builder<User> $builder */
|
||||
return $builder->belongsToOrganization($this->organization);
|
||||
@@ -99,7 +106,11 @@ abstract class DefaultImporter implements ImporterContract
|
||||
'string',
|
||||
'in:placeholder',
|
||||
],
|
||||
]);
|
||||
], beforeSave: function (Member $member): void {
|
||||
if (! $this->canUseBillableRates) {
|
||||
$member->billable_rate = null;
|
||||
}
|
||||
});
|
||||
$this->projectImportHelper = new ImportDatabaseHelper(Project::class, ['name', 'client_id', 'organization_id'], true, function (Builder $builder) {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->where('organization_id', $this->organization->id);
|
||||
@@ -126,6 +137,10 @@ abstract class DefaultImporter implements ImporterContract
|
||||
if ($project->billable_rate === 0) {
|
||||
$project->billable_rate = null;
|
||||
}
|
||||
if (! $this->canUseBillableRates) {
|
||||
$project->is_billable = false;
|
||||
$project->billable_rate = null;
|
||||
}
|
||||
});
|
||||
$this->projectMemberImportHelper = new ImportDatabaseHelper(ProjectMember::class, ['project_id', 'member_id'], true, function (Builder $builder): Builder {
|
||||
/** @var Builder<ProjectMember> $builder */
|
||||
@@ -140,6 +155,9 @@ abstract class DefaultImporter implements ImporterContract
|
||||
if ($projectMember->billable_rate === 0) {
|
||||
$projectMember->billable_rate = null;
|
||||
}
|
||||
if (! $this->canUseBillableRates) {
|
||||
$projectMember->billable_rate = null;
|
||||
}
|
||||
});
|
||||
$this->tagImportHelper = new ImportDatabaseHelper(Tag::class, ['name', 'organization_id'], true, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
@@ -181,7 +199,6 @@ abstract class DefaultImporter implements ImporterContract
|
||||
$this->timeEntriesCreated = 0;
|
||||
$this->colorService = app(ColorService::class);
|
||||
$this->timezoneService = app(TimezoneService::class);
|
||||
$this->billableRateService = app(BillableRateService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -134,7 +134,7 @@ class GenericTimeEntriesImporter extends DefaultImporter
|
||||
if (! in_array($record['billable'], ['true', 'false'], true)) {
|
||||
throw new ImportException('Invalid billable value');
|
||||
}
|
||||
$timeEntry->billable = $record['billable'] === 'true';
|
||||
$timeEntry->billable = $this->canUseBillableRates && $record['billable'] === 'true';
|
||||
$timeEntry->tags = $this->getTags($record['tags']);
|
||||
$timeEntry->is_imported = true;
|
||||
try {
|
||||
@@ -155,6 +155,9 @@ class GenericTimeEntriesImporter extends DefaultImporter
|
||||
if ($end === null) {
|
||||
throw new ImportException('Value of end ("'.$record['end'].'") is invalid');
|
||||
}
|
||||
if ($end->lt($start)) {
|
||||
throw new ImportException('Value of end ("'.$record['end'].'") is before start ("'.$record['start'].'")');
|
||||
}
|
||||
$timeEntry->end = $end->utc();
|
||||
$timeEntry->billable_rate = $this->billableRateService->getBillableRateForTimeEntryWithGivenRelations(
|
||||
$timeEntry,
|
||||
|
||||
@@ -115,7 +115,7 @@ class HarvestTimeEntriesImporter extends DefaultImporter
|
||||
if (! in_array($record['Billable?'], ['Yes', 'No'], true)) {
|
||||
throw new ImportException('Invalid billable value');
|
||||
}
|
||||
$timeEntry->billable = $record['Billable?'] === 'Yes';
|
||||
$timeEntry->billable = $this->canUseBillableRates && $record['Billable?'] === 'Yes';
|
||||
$timeEntry->tags = [];
|
||||
$timeEntry->is_imported = true;
|
||||
|
||||
@@ -136,6 +136,9 @@ class HarvestTimeEntriesImporter extends DefaultImporter
|
||||
throw new ImportException('Hours ("'.$record['Hours'].'") is invalid');
|
||||
}
|
||||
$hours = (float) $hoursField;
|
||||
if ($hours < 0) {
|
||||
throw new ImportException('Hours ("'.$record['Hours'].'") is negative');
|
||||
}
|
||||
$timeEntry->start = $date->copy()->startOfDay()->utc();
|
||||
$timeEntry->end = $date->copy()->startOfDay()->addHours($hours)->utc();
|
||||
$timeEntry->billable_rate = $this->billableRateService->getBillableRateForTimeEntryWithGivenRelations(
|
||||
|
||||
@@ -211,18 +211,34 @@ class SolidtimeImporter extends DefaultImporter
|
||||
|
||||
// Time entries
|
||||
foreach ($timeEntriesReader as $timeEntryRow) {
|
||||
// Running time entries are skipped, since the user could already have a running time entry
|
||||
if ($timeEntryRow['end'] === '') {
|
||||
continue;
|
||||
}
|
||||
$userId = $this->userImportHelper->getKeyByExternalIdentifier($timeEntryRow['user_id']);
|
||||
if ($userId === null) {
|
||||
throw new ImportException('Time entry references a user that does not exist in the import');
|
||||
}
|
||||
$memberId = $this->memberImportHelper->getKeyByExternalIdentifier($timeEntryRow['member_id']);
|
||||
if ($memberId === null) {
|
||||
throw new ImportException('Time entry references a member that does not exist in the import');
|
||||
}
|
||||
$member = $this->memberImportHelper->getModelById($memberId);
|
||||
$clientId = null;
|
||||
if ($timeEntryRow['client_id'] !== '') {
|
||||
$clientId = $this->clientImportHelper->getKeyByExternalIdentifier($timeEntryRow['client_id']);
|
||||
if ($clientId === null) {
|
||||
throw new ImportException('Time entry references a client that does not exist in the import');
|
||||
}
|
||||
}
|
||||
$project = null;
|
||||
$projectId = null;
|
||||
$projectMember = null;
|
||||
if ($timeEntryRow['project_id'] !== '') {
|
||||
$projectId = $this->projectImportHelper->getKeyByExternalIdentifier($timeEntryRow['project_id']);
|
||||
if ($projectId === null) {
|
||||
throw new ImportException('Time entry references a project that does not exist in the import');
|
||||
}
|
||||
$project = $this->projectImportHelper->getModelById($projectId);
|
||||
$projectMember = $this->projectMemberImportHelper->getModel([
|
||||
'project_id' => $projectId,
|
||||
@@ -232,6 +248,9 @@ class SolidtimeImporter extends DefaultImporter
|
||||
$taskId = null;
|
||||
if ($timeEntryRow['task_id'] !== '') {
|
||||
$taskId = $this->taskImportHelper->getKeyByExternalIdentifier($timeEntryRow['task_id']);
|
||||
if ($taskId === null) {
|
||||
throw new ImportException('Time entry references a task that does not exist in the import');
|
||||
}
|
||||
$this->taskImportHelper->getModelById($taskId);
|
||||
}
|
||||
$timeEntry = new TimeEntry;
|
||||
@@ -249,7 +268,7 @@ class SolidtimeImporter extends DefaultImporter
|
||||
if (! in_array($timeEntryRow['billable'], ['true', 'false'], true)) {
|
||||
throw new ImportException('Invalid billable value');
|
||||
}
|
||||
$timeEntry->billable = $timeEntryRow['billable'] === 'true';
|
||||
$timeEntry->billable = $this->canUseBillableRates && $timeEntryRow['billable'] === 'true';
|
||||
// The type column does not exist in old exports
|
||||
if (($timeEntryRow['type'] ?? '') !== '') {
|
||||
$type = TimeEntryType::tryFrom($timeEntryRow['type']);
|
||||
@@ -271,7 +290,6 @@ class SolidtimeImporter extends DefaultImporter
|
||||
}
|
||||
$timeEntry->start = $start->utc();
|
||||
|
||||
if ($timeEntryRow['end'] !== '') {
|
||||
try {
|
||||
$end = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $timeEntryRow['end'], 'UTC');
|
||||
} catch (InvalidFormatException) {
|
||||
@@ -280,10 +298,10 @@ class SolidtimeImporter extends DefaultImporter
|
||||
if ($end === null) {
|
||||
throw new ImportException('End date ("'.$timeEntryRow['end'].'") is invalid');
|
||||
}
|
||||
$timeEntry->end = $end->utc();
|
||||
} else {
|
||||
$timeEntry->end = null;
|
||||
if ($end->lt($start)) {
|
||||
throw new ImportException('End date ("'.$timeEntryRow['end'].'") is before start date ("'.$timeEntryRow['start'].'")');
|
||||
}
|
||||
$timeEntry->end = $end->utc();
|
||||
|
||||
if ($timeEntryRow['still_active_email_sent_at'] !== '') {
|
||||
try {
|
||||
|
||||
@@ -118,7 +118,7 @@ class TogglTimeEntriesImporter extends DefaultImporter
|
||||
if (! in_array($record['Billable'], ['Yes', 'No'], true)) {
|
||||
throw new ImportException('Invalid billable value');
|
||||
}
|
||||
$timeEntry->billable = $record['Billable'] === 'Yes';
|
||||
$timeEntry->billable = $this->canUseBillableRates && $record['Billable'] === 'Yes';
|
||||
$timeEntry->tags = $this->getTags($record['Tags']);
|
||||
$timeEntry->is_imported = true;
|
||||
try {
|
||||
@@ -139,6 +139,9 @@ class TogglTimeEntriesImporter extends DefaultImporter
|
||||
if ($end === null) {
|
||||
throw new ImportException('End date ("'.$record['End date'].'") or time ("'.$record['End time'].'") are invalid');
|
||||
}
|
||||
if ($end->lt($start)) {
|
||||
throw new ImportException('End ("'.$record['End date'].' '.$record['End time'].'") is before start ("'.$record['Start date'].' '.$record['Start time'].'")');
|
||||
}
|
||||
$timeEntry->end = $end->utc();
|
||||
$timeEntry->billable_rate = $this->billableRateService->getBillableRateForTimeEntryWithGivenRelations(
|
||||
$timeEntry,
|
||||
|
||||
@@ -14,6 +14,7 @@ use App\Exceptions\Api\ChangingRoleToPlaceholderIsNotAllowed;
|
||||
use App\Exceptions\Api\EntityStillInUseApiException;
|
||||
use App\Exceptions\Api\OnlyOwnerCanChangeOwnership;
|
||||
use App\Exceptions\Api\OrganizationNeedsAtLeastOneOwner;
|
||||
use App\Models\Goal;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
@@ -109,6 +110,12 @@ class MemberService
|
||||
}
|
||||
}
|
||||
|
||||
// A goal is deleted together with the member it is for, it is not part of the "still in use" check
|
||||
Goal::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->where('member_id', '=', $member->getKey())
|
||||
->delete();
|
||||
|
||||
$member->delete();
|
||||
|
||||
if ($isPlaceholder) {
|
||||
@@ -152,6 +159,13 @@ class MemberService
|
||||
|
||||
public function assignOrganizationEntitiesToDifferentMember(Organization $organization, Member $fromMember, Member $toMember): void
|
||||
{
|
||||
// Running time entries are deleted instead of moved, since $toMember could already have a running time entry
|
||||
TimeEntry::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->whereBelongsTo($fromMember, 'member')
|
||||
->whereNull('end')
|
||||
->delete();
|
||||
|
||||
// Time entries
|
||||
TimeEntry::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
@@ -181,6 +195,30 @@ class MemberService
|
||||
->whereBelongsToOrganization($organization)
|
||||
->whereBelongsTo($fromMember, 'member')
|
||||
->delete();
|
||||
|
||||
// Goals: the goal belongs to the person it is for, like time entries it moves along
|
||||
Goal::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->where('member_id', '=', $fromMember->getKey())
|
||||
->update([
|
||||
'member_id' => $toMember->getKey(),
|
||||
]);
|
||||
|
||||
// Goal member filters: the time entries of $fromMember now belong to $toMember, so the filters follow them
|
||||
$goalsWithMemberFilter = Goal::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->whereJsonContains('filters->memberIds', $fromMember->getKey())
|
||||
->get();
|
||||
foreach ($goalsWithMemberFilter as $goal) {
|
||||
$filters = $goal->filters;
|
||||
$memberIds = $filters->memberIds?->map(
|
||||
fn (string $memberId): string => $memberId === $fromMember->getKey() ? $toMember->getKey() : $memberId
|
||||
);
|
||||
// $toMember may already be in the filter
|
||||
$filters->setMemberIds($memberIds?->unique()->values()->all());
|
||||
$goal->filters = $filters;
|
||||
$goal->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -75,6 +75,14 @@ class PermissionStore
|
||||
'reports:create',
|
||||
'reports:update',
|
||||
'reports:delete',
|
||||
'goals:view:own',
|
||||
'goals:create:own',
|
||||
'goals:update:own',
|
||||
'goals:delete:own',
|
||||
'goals:view:organization-type',
|
||||
'goals:create:organization-type',
|
||||
'goals:update:organization-type',
|
||||
'goals:delete:organization-type',
|
||||
'invoices:view',
|
||||
'invoices:create',
|
||||
'invoices:update',
|
||||
@@ -146,6 +154,14 @@ class PermissionStore
|
||||
'reports:create',
|
||||
'reports:update',
|
||||
'reports:delete',
|
||||
'goals:view:own',
|
||||
'goals:create:own',
|
||||
'goals:update:own',
|
||||
'goals:delete:own',
|
||||
'goals:view:organization-type',
|
||||
'goals:create:organization-type',
|
||||
'goals:update:organization-type',
|
||||
'goals:delete:organization-type',
|
||||
'invoices:view',
|
||||
'invoices:create',
|
||||
'invoices:update',
|
||||
@@ -206,6 +222,14 @@ class PermissionStore
|
||||
'reports:create',
|
||||
'reports:update',
|
||||
'reports:delete',
|
||||
'goals:view:own',
|
||||
'goals:create:own',
|
||||
'goals:update:own',
|
||||
'goals:delete:own',
|
||||
'goals:view:organization-type',
|
||||
'goals:create:organization-type',
|
||||
'goals:update:organization-type',
|
||||
'goals:delete:organization-type',
|
||||
'invoices:view',
|
||||
'invoices:create',
|
||||
'invoices:update',
|
||||
@@ -233,6 +257,10 @@ class PermissionStore
|
||||
'time-entries:update:own',
|
||||
'time-entries:delete:own',
|
||||
'organizations:view',
|
||||
'goals:view:own',
|
||||
'goals:create:own',
|
||||
'goals:update:own',
|
||||
'goals:delete:own',
|
||||
],
|
||||
'description' => 'Employees have the ability to read, create, and update their own time entries, they can see the projects that they are members of and the clients they are assigned to.',
|
||||
],
|
||||
|
||||
@@ -10,7 +10,9 @@ use App\Models\Member;
|
||||
use App\Models\TimeEntry;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class TimeEntryFilter
|
||||
{
|
||||
@@ -29,6 +31,26 @@ class TimeEntryFilter
|
||||
$this->builder = $builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<mixed> $ids
|
||||
* @return Collection<int, string>
|
||||
*/
|
||||
public static function idArrayToCollection(array $ids): Collection
|
||||
{
|
||||
$collection = new Collection;
|
||||
foreach ($ids as $id) {
|
||||
if (! is_string($id)) {
|
||||
throw new \InvalidArgumentException('The given ID is not a string');
|
||||
}
|
||||
if ($id !== self::NONE_VALUE && ! Str::isUuid($id)) {
|
||||
throw new \InvalidArgumentException('The given ID is not a valid UUID');
|
||||
}
|
||||
$collection->push($id);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
|
||||
public function addEndFilter(?string $dateTime): self
|
||||
{
|
||||
if ($dateTime === null) {
|
||||
@@ -111,7 +133,8 @@ class TimeEntryFilter
|
||||
*/
|
||||
public function addMemberIdsFilter(?array $memberIds): self
|
||||
{
|
||||
if ($memberIds === null) {
|
||||
// An empty selection is no constraint, the same as null
|
||||
if ($memberIds === null || count($memberIds) === 0) {
|
||||
return $this;
|
||||
}
|
||||
$this->builder->whereIn('member_id', $memberIds);
|
||||
@@ -181,6 +204,10 @@ class TimeEntryFilter
|
||||
}
|
||||
$includeNone = in_array(self::NONE_VALUE, $clientIds, true);
|
||||
$clientIds = array_values(array_filter($clientIds, fn (string $id): bool => $id !== self::NONE_VALUE));
|
||||
// An empty selection (no client IDs and not filtering for "none") is no constraint, so apply nothing
|
||||
if (count($clientIds) === 0 && ! $includeNone) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->builder->where(function (Builder $builder) use ($clientIds, $includeNone): void {
|
||||
if (count($clientIds) > 0) {
|
||||
@@ -204,6 +231,10 @@ class TimeEntryFilter
|
||||
}
|
||||
$includeNone = in_array(self::NONE_VALUE, $projectIds, true);
|
||||
$projectIds = array_values(array_filter($projectIds, fn (string $id): bool => $id !== self::NONE_VALUE));
|
||||
// An empty selection (no project IDs and not filtering for "none") is no constraint, so apply nothing
|
||||
if (count($projectIds) === 0 && ! $includeNone) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->builder->where(function (Builder $builder) use ($projectIds, $includeNone): void {
|
||||
if (count($projectIds) > 0) {
|
||||
@@ -269,6 +300,10 @@ class TimeEntryFilter
|
||||
}
|
||||
$includeNone = in_array(self::NONE_VALUE, $taskIds, true);
|
||||
$taskIds = array_values(array_filter($taskIds, fn (string $id): bool => $id !== self::NONE_VALUE));
|
||||
// An empty selection (no task IDs and not filtering for "none") is no constraint, so apply nothing
|
||||
if (count($taskIds) === 0 && ! $includeNone) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->builder->where(function (Builder $builder) use ($taskIds, $includeNone): void {
|
||||
if (count($taskIds) > 0) {
|
||||
|
||||
@@ -27,7 +27,7 @@ return [
|
||||
|
|
||||
*/
|
||||
|
||||
'zip_max_files' => (int) (env('IMPORT_ZIP_MAX_FILES') ?: 100),
|
||||
'zip_max_files' => (int) (env('IMPORT_ZIP_MAX_FILES') ?: 10000),
|
||||
|
||||
'zip_max_uncompressed_size' => (int) (env('IMPORT_ZIP_MAX_UNCOMPRESSED_SIZE') ?: 500 * 1024 * 1024),
|
||||
|
||||
|
||||
161
database/factories/GoalFactory.php
Normal file
161
database/factories/GoalFactory.php
Normal file
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Enums\GoalComparison;
|
||||
use App\Enums\GoalPeriod;
|
||||
use App\Enums\GoalType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Models\Goal;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Service\Dto\GoalFiltersDto;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
* @extends Factory<Goal>
|
||||
*/
|
||||
class GoalFactory extends Factory
|
||||
{
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function definition(): array
|
||||
{
|
||||
$filters = new GoalFiltersDto;
|
||||
$filters->timeEntryType = TimeEntryType::Work;
|
||||
|
||||
return [
|
||||
'name' => $this->faker->sentence(3),
|
||||
'type' => GoalType::Personal,
|
||||
'comparison' => $this->faker->randomElement(GoalComparison::cases()),
|
||||
'target_seconds' => $this->faker->numberBetween(1, 40) * 3600,
|
||||
'period' => $this->faker->randomElement(GoalPeriod::cases()),
|
||||
'filters' => $filters,
|
||||
'timezone' => 'UTC',
|
||||
'week_start' => Weekday::Monday,
|
||||
'archived_at' => null,
|
||||
'organization_id' => Organization::factory(),
|
||||
// The member has to belong to the organization of the goal
|
||||
'member_id' => fn (array $attributes) => Member::factory()->state([
|
||||
'organization_id' => $attributes['organization_id'],
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Goal in the given organization, for a new member of that organization unless forMember() is used.
|
||||
*/
|
||||
public function forOrganization(Organization $organization): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'organization_id' => $organization->getKey(),
|
||||
'member_id' => Member::factory()->forOrganization($organization),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Personal goal of the given member.
|
||||
*/
|
||||
public function forMember(Member $member): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'type' => GoalType::Personal,
|
||||
'member_id' => $member->getKey(),
|
||||
'organization_id' => $member->organization_id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Organization goal that counts the time of the given member.
|
||||
*/
|
||||
public function organizationGoalForMember(Member $member): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'type' => GoalType::Organization,
|
||||
'member_id' => $member->getKey(),
|
||||
'organization_id' => $member->organization_id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Organization goal that counts the time of every member.
|
||||
*/
|
||||
public function forEveryMember(): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'type' => GoalType::Organization,
|
||||
'member_id' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function type(GoalType $type): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'type' => $type,
|
||||
]);
|
||||
}
|
||||
|
||||
public function archived(): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'archived_at' => $this->faker->dateTimeBetween('-1 year', 'now'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function timezone(string $timezone): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'timezone' => $timezone,
|
||||
]);
|
||||
}
|
||||
|
||||
public function weekStart(Weekday $weekStart): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'week_start' => $weekStart,
|
||||
]);
|
||||
}
|
||||
|
||||
public function atLeast(int $targetSeconds): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'comparison' => GoalComparison::AtLeast,
|
||||
'target_seconds' => $targetSeconds,
|
||||
]);
|
||||
}
|
||||
|
||||
public function lessThan(int $targetSeconds): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'comparison' => GoalComparison::LessThan,
|
||||
'target_seconds' => $targetSeconds,
|
||||
]);
|
||||
}
|
||||
|
||||
public function period(GoalPeriod $period): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'period' => $period,
|
||||
]);
|
||||
}
|
||||
|
||||
public function filters(GoalFiltersDto $filters): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'filters' => $filters,
|
||||
]);
|
||||
}
|
||||
|
||||
public function randomCreatedAt(): self
|
||||
{
|
||||
return $this->state(fn (array $attributes): array => [
|
||||
'created_at' => $this->faker->dateTimeBetween('-1 year', 'now'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
56
database/migrations/2026_09_02_000001_create_goals_table.php
Normal file
56
database/migrations/2026_09_02_000001_create_goals_table.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('goals', function (Blueprint $table): void {
|
||||
$table->uuid('id')->primary();
|
||||
$table->string('name');
|
||||
// personal: a goal a member set for themselves, organization: a goal the organization set (team goals extension)
|
||||
$table->string('type');
|
||||
$table->string('comparison');
|
||||
$table->unsignedBigInteger('target_seconds');
|
||||
$table->string('period');
|
||||
$table->jsonb('filters');
|
||||
// Timezone and week start define the periods of the goal, they are pinned on the goal like on a report
|
||||
$table->string('timezone');
|
||||
$table->string('week_start');
|
||||
$table->dateTime('archived_at')->nullable();
|
||||
$table->uuid('organization_id');
|
||||
$table->foreign('organization_id')
|
||||
->references('id')
|
||||
->on('organizations')
|
||||
->restrictOnDelete()
|
||||
->cascadeOnUpdate();
|
||||
// Member whose time entries count towards the goal, null means every member of the organization
|
||||
// (organization goals only). Personal goals always have a member.
|
||||
$table->uuid('member_id')->nullable();
|
||||
$table->foreign('member_id')
|
||||
->references('id')
|
||||
->on('members')
|
||||
->restrictOnDelete()
|
||||
->cascadeOnUpdate();
|
||||
$table->timestamps();
|
||||
$table->index(['organization_id', 'member_id']);
|
||||
$table->index(['organization_id', 'type']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('goals');
|
||||
}
|
||||
};
|
||||
@@ -4,11 +4,14 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Enums\GoalPeriod;
|
||||
use App\Enums\Role;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Events\DatabaseSeederAfterSeed;
|
||||
use App\Events\DatabaseSeederBeforeDelete;
|
||||
use App\Models\Audit;
|
||||
use App\Models\Client;
|
||||
use App\Models\Goal;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\OrganizationInvitation;
|
||||
@@ -19,6 +22,7 @@ use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Models\User;
|
||||
use App\Service\Dto\GoalFiltersDto;
|
||||
use Illuminate\Database\Seeder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Laravel\Passport\AuthCode;
|
||||
@@ -114,13 +118,28 @@ class DatabaseSeeder extends Seeder
|
||||
Tag::factory()->forOrganization($organizationAcme)->create([
|
||||
'name' => 'Code Review',
|
||||
]);
|
||||
Tag::factory()->forOrganization($organizationAcme)->create([
|
||||
$tagMeeting = Tag::factory()->forOrganization($organizationAcme)->create([
|
||||
'name' => 'Meeting',
|
||||
]);
|
||||
Tag::factory()->forOrganization($organizationAcme)->create([
|
||||
'name' => 'Research',
|
||||
]);
|
||||
|
||||
$workFilters = new GoalFiltersDto;
|
||||
$workFilters->timeEntryType = TimeEntryType::Work;
|
||||
Goal::factory()->forMember($userAcmeOwnerMember)->atLeast(6 * 3600)->period(GoalPeriod::Day)->filters($workFilters)->create([
|
||||
'name' => 'Track at least 6 hours per day',
|
||||
]);
|
||||
$meetingFilters = new GoalFiltersDto;
|
||||
$meetingFilters->setTagIds([$tagMeeting->getKey()]);
|
||||
$meetingFilters->timeEntryType = TimeEntryType::Work;
|
||||
Goal::factory()->forMember($userAcmeOwnerMember)->lessThan(5 * 3600)->period(GoalPeriod::Week)->filters($meetingFilters)->create([
|
||||
'name' => 'Less than 5 hours of meetings per week',
|
||||
]);
|
||||
Goal::factory()->forMember($userAcmeEmployeeMember)->atLeast(30 * 3600)->period(GoalPeriod::Week)->filters($workFilters)->create([
|
||||
'name' => 'Track 30 hours per week',
|
||||
]);
|
||||
|
||||
TimeEntry::factory()
|
||||
->count(10)
|
||||
->forMember($userAcmeAdminMember)
|
||||
@@ -219,6 +238,7 @@ class DatabaseSeeder extends Seeder
|
||||
// Application tables
|
||||
DB::table((new Audit)->getTable())->delete();
|
||||
DB::table((new Report)->getTable())->delete();
|
||||
DB::table((new Goal)->getTable())->delete();
|
||||
DB::table((new TimeEntry)->getTable())->delete();
|
||||
DB::table((new Task)->getTable())->delete();
|
||||
DB::table((new Tag)->getTable())->delete();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
ARG PHP_VERSION=8.3
|
||||
ARG FRANKENPHP_VERSION=1.11
|
||||
ARG FRANKENPHP_VERSION=1.13
|
||||
ARG COMPOSER_VERSION=2.8
|
||||
ARG APP_ENV
|
||||
ARG DOCKER_FILES_BASE_PATH="docker/prod/"
|
||||
|
||||
@@ -7,6 +7,7 @@ realpath_cache_ttl = 720
|
||||
memory_limit = 256M
|
||||
max_input_time = 5
|
||||
register_argc_argv = 0
|
||||
session.upload_progress.enabled = 0
|
||||
date.timezone = ${TZ:-UTC}
|
||||
|
||||
[Opcache]
|
||||
|
||||
@@ -292,6 +292,16 @@ test.describe('Command Palette', () => {
|
||||
await expect(page.locator('[role="dialog"]').getByText('Create Tags')).toBeVisible();
|
||||
});
|
||||
|
||||
test('opens create goal modal', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Create Goal');
|
||||
await selectCommand(page, 'Create Goal');
|
||||
await expect(
|
||||
page.locator('[role="dialog"]').getByRole('heading', { name: 'Create Goal' })
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('opens invite member modal', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
@@ -466,6 +476,9 @@ test.describe('Employee Command Palette Restrictions', () => {
|
||||
employee.page.getByRole('option', { name: 'Invite Member' })
|
||||
).not.toBeVisible();
|
||||
|
||||
// Employees can set personal goals for themselves
|
||||
await expect(employee.page.getByRole('option', { name: 'Create Goal' })).toBeVisible();
|
||||
|
||||
// Should still see Create Time Entry (employees can create time entries)
|
||||
await expect(
|
||||
employee.page.getByRole('option', { name: 'Create Time Entry' })
|
||||
|
||||
771
e2e/goals.spec.ts
Normal file
771
e2e/goals.spec.ts
Normal file
@@ -0,0 +1,771 @@
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { test } from '../playwright/fixtures';
|
||||
import {
|
||||
createClientViaApi,
|
||||
createGoalViaApi,
|
||||
createProjectViaApi,
|
||||
createProjectMemberViaApi,
|
||||
setupTestContext,
|
||||
createRunningTimeEntryWithStartViaApi,
|
||||
createTagViaApi,
|
||||
createTaskViaApi,
|
||||
createTimeEntryViaApi,
|
||||
deleteClientViaApi,
|
||||
deleteProjectViaApi,
|
||||
deleteTagViaApi,
|
||||
deleteTaskViaApi,
|
||||
updateGoalViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
updateUserProfileViaApi,
|
||||
} from './utils/api';
|
||||
import {
|
||||
selectTimezone,
|
||||
selectWeekStart,
|
||||
timezoneField,
|
||||
weekStartField,
|
||||
} from './utils/userSettingsFields';
|
||||
|
||||
async function goToGoalsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/goals');
|
||||
await expect(page.getByTestId('goals_view')).toBeVisible();
|
||||
}
|
||||
|
||||
function goalRow(page: Page, goalId: string) {
|
||||
return page.getByTestId('goal_row_' + goalId);
|
||||
}
|
||||
|
||||
function goalResponse(page: Page, method: 'POST' | 'PUT' | 'DELETE', status: number) {
|
||||
return page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/goals') &&
|
||||
response.request().method() === method &&
|
||||
response.status() === status
|
||||
);
|
||||
}
|
||||
|
||||
test('test that the goals page shows an empty state and the sidebar link works', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await page.getByRole('link', { name: 'Goals' }).first().click();
|
||||
await expect(page).toHaveURL(/\/goals$/);
|
||||
await expect(page.getByTestId('goal_table')).toContainText('No goals found');
|
||||
await expect(page.getByRole('button', { name: 'Create your first goal' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that creating a goal via the modal works and shows zero progress', async ({ page }) => {
|
||||
const goalName = 'Deep work ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToGoalsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Goal' }).click();
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill(goalName);
|
||||
await page.getByTestId('duration_seconds_input').fill('10h');
|
||||
await page.getByTestId('duration_seconds_input').press('Tab');
|
||||
await page.getByRole('combobox', { name: 'Period' }).click();
|
||||
await page.getByRole('option', { name: 'per day' }).click();
|
||||
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'POST', 201),
|
||||
page.getByRole('button', { name: 'Create Goal', exact: true }).last().click(),
|
||||
]);
|
||||
const body = await response.json();
|
||||
expect(body.data.name).toBe(goalName);
|
||||
expect(body.data.target_seconds).toBe(36000);
|
||||
expect(body.data.period).toBe('day');
|
||||
expect(body.data.comparison).toBe('at_least');
|
||||
expect(body.data.filters.time_entry_type).toBe('work');
|
||||
expect(body.data.type).toBe('personal');
|
||||
expect(body.data.is_archived).toBe(false);
|
||||
|
||||
const row = goalRow(page, body.data.id);
|
||||
await expect(row).toBeVisible();
|
||||
await expect(row.getByTestId('goal_name')).toHaveText(goalName);
|
||||
await expect(row.getByTestId('goal_target_description')).toHaveText(
|
||||
'At least 10h 00min per day'
|
||||
);
|
||||
await expect(row.getByTestId('goal_tracked_time')).toHaveText('0h 00min');
|
||||
await expect(row).toContainText('of 10h 00min');
|
||||
await expect(row).toContainText('In progress');
|
||||
});
|
||||
|
||||
test('test that the create goal modal validates name and target', async ({ page }) => {
|
||||
await goToGoalsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Goal' }).click();
|
||||
await page.getByRole('button', { name: 'Create Goal', exact: true }).last().click();
|
||||
await expect(page.getByRole('alert').filter({ hasText: 'name' })).toBeVisible();
|
||||
await expect(page.getByRole('alert').filter({ hasText: 'target time' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that goal progress reflects tracked time entries that match the filters', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const project = await createProjectViaApi(ctx, { name: 'Goal Project', is_public: true });
|
||||
const otherProject = await createProjectViaApi(ctx, { name: 'Other Project', is_public: true });
|
||||
await createTimeEntryViaApi(ctx, { duration: '2h', projectId: project.id });
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h 30min', projectId: otherProject.id });
|
||||
await createTimeEntryViaApi(ctx, { duration: '45min' });
|
||||
|
||||
const projectGoal = await createGoalViaApi(ctx, {
|
||||
name: 'Project goal',
|
||||
target_seconds: 4 * 3600,
|
||||
period: 'day',
|
||||
filters: { project_ids: [project.id], time_entry_type: 'work' },
|
||||
});
|
||||
const allGoal = await createGoalViaApi(ctx, {
|
||||
name: 'All time goal',
|
||||
target_seconds: 4 * 3600,
|
||||
period: 'day',
|
||||
});
|
||||
const lessThanGoal = await createGoalViaApi(ctx, {
|
||||
name: 'Less than goal',
|
||||
comparison: 'less_than',
|
||||
target_seconds: 3600,
|
||||
period: 'day',
|
||||
filters: { project_ids: [project.id], time_entry_type: 'work' },
|
||||
});
|
||||
|
||||
expect(projectGoal.progress.tracked_seconds).toBe(2 * 3600);
|
||||
expect(allGoal.progress.tracked_seconds).toBe(2 * 3600 + 90 * 60 + 45 * 60);
|
||||
expect(lessThanGoal.progress.status).toBe('exceeded');
|
||||
|
||||
await goToGoalsOverview(page);
|
||||
await expect(goalRow(page, projectGoal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
'2h 00min'
|
||||
);
|
||||
await expect(goalRow(page, projectGoal.id)).toContainText('Goal Project');
|
||||
await expect(goalRow(page, projectGoal.id)).toContainText('In progress');
|
||||
await expect(goalRow(page, allGoal.id).getByTestId('goal_tracked_time')).toHaveText('4h 15min');
|
||||
await expect(goalRow(page, allGoal.id)).toContainText('Achieved');
|
||||
await expect(goalRow(page, allGoal.id)).toContainText('All time entries');
|
||||
await expect(goalRow(page, lessThanGoal.id)).toContainText('Exceeded');
|
||||
await expect(goalRow(page, lessThanGoal.id)).toContainText('Less than 1h 00min per day');
|
||||
});
|
||||
|
||||
async function openCreateGoalModal(page: Page, name: string) {
|
||||
await goToGoalsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Goal' }).click();
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill(name);
|
||||
await page.getByTestId('duration_seconds_input').fill('10h');
|
||||
await page.getByTestId('duration_seconds_input').press('Tab');
|
||||
}
|
||||
|
||||
async function submitCreateGoalModal(page: Page) {
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'POST', 201),
|
||||
page.getByRole('button', { name: 'Create Goal', exact: true }).last().click(),
|
||||
]);
|
||||
return (await response.json()).data;
|
||||
}
|
||||
|
||||
async function selectGoalFilterOption(
|
||||
page: Page,
|
||||
filter: string,
|
||||
searchPlaceholder: string,
|
||||
option: string
|
||||
) {
|
||||
await page.getByTestId('goal_filter_' + filter).click();
|
||||
await page.getByRole('option', { name: option }).click();
|
||||
await page.getByPlaceholder(searchPlaceholder).press('Escape');
|
||||
}
|
||||
|
||||
test('test that the task filter of a goal only counts entries of the selected tasks', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const project = await createProjectViaApi(ctx, {
|
||||
name: 'Task filter project',
|
||||
is_public: true,
|
||||
});
|
||||
const task = await createTaskViaApi(ctx, { name: 'Counted task', project_id: project.id });
|
||||
const otherTask = await createTaskViaApi(ctx, { name: 'Other task', project_id: project.id });
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', projectId: project.id, taskId: task.id });
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
duration: '2h',
|
||||
projectId: project.id,
|
||||
taskId: otherTask.id,
|
||||
});
|
||||
await createTimeEntryViaApi(ctx, { duration: '30min', projectId: project.id });
|
||||
|
||||
await openCreateGoalModal(page, 'Task goal');
|
||||
await selectGoalFilterOption(page, 'task_ids', 'Search for a Task...', 'Counted task');
|
||||
await expect(page.getByTestId('goal_filter_task_ids')).toHaveText(/Tasks\s*1/);
|
||||
const goal = await submitCreateGoalModal(page);
|
||||
|
||||
expect(goal.filters.task_ids).toEqual([task.id]);
|
||||
expect(goal.progress.tracked_seconds).toBe(3600);
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_tracked_time')).toHaveText('1h 00min');
|
||||
});
|
||||
|
||||
test('test that the client filter of a goal only counts entries of projects of the selected clients', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const client = await createClientViaApi(ctx, { name: 'Counted client' });
|
||||
const otherClient = await createClientViaApi(ctx, { name: 'Other client' });
|
||||
const project = await createProjectViaApi(ctx, {
|
||||
name: 'Client project',
|
||||
client_id: client.id,
|
||||
is_public: true,
|
||||
});
|
||||
const otherProject = await createProjectViaApi(ctx, {
|
||||
name: 'Other client project',
|
||||
client_id: otherClient.id,
|
||||
is_public: true,
|
||||
});
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', projectId: project.id });
|
||||
await createTimeEntryViaApi(ctx, { duration: '2h', projectId: otherProject.id });
|
||||
await createTimeEntryViaApi(ctx, { duration: '30min' });
|
||||
|
||||
await openCreateGoalModal(page, 'Client goal');
|
||||
await selectGoalFilterOption(page, 'client_ids', 'Search for a Client...', 'Counted client');
|
||||
await expect(page.getByTestId('goal_filter_client_ids')).toHaveText(/Clients\s*1/);
|
||||
const goal = await submitCreateGoalModal(page);
|
||||
|
||||
expect(goal.filters.client_ids).toEqual([client.id]);
|
||||
expect(goal.progress.tracked_seconds).toBe(3600);
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_tracked_time')).toHaveText('1h 00min');
|
||||
});
|
||||
|
||||
test('test that the tag filter of a goal respects the tag match type', async ({ page, ctx }) => {
|
||||
const tag = await createTagViaApi(ctx, { name: 'Counted tag' });
|
||||
const otherTag = await createTagViaApi(ctx, { name: 'Other tag' });
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', tags: [tag.id] });
|
||||
await createTimeEntryViaApi(ctx, { duration: '2h', tags: [otherTag.id] });
|
||||
await createTimeEntryViaApi(ctx, { duration: '30min' });
|
||||
|
||||
await openCreateGoalModal(page, 'Contains tag goal');
|
||||
await selectGoalFilterOption(page, 'tag_ids', 'Search for a Tag...', 'Counted tag');
|
||||
await expect(page.getByTestId('goal_filter_tag_ids')).toHaveText(/Tags\s*1/);
|
||||
const containsGoal = await submitCreateGoalModal(page);
|
||||
expect(containsGoal.filters.tag_ids).toEqual([tag.id]);
|
||||
expect(containsGoal.filters.tag_match_type).toBe('contains');
|
||||
expect(containsGoal.progress.tracked_seconds).toBe(3600);
|
||||
|
||||
await openCreateGoalModal(page, 'Not contains tag goal');
|
||||
await page.getByTestId('goal_filter_tag_ids').click();
|
||||
await page.getByRole('radio', { name: 'Does Not Contain' }).click();
|
||||
await page.getByRole('option', { name: 'Counted tag' }).click();
|
||||
await page.getByPlaceholder('Search for a Tag...').press('Escape');
|
||||
const notContainsGoal = await submitCreateGoalModal(page);
|
||||
expect(notContainsGoal.filters.tag_ids).toEqual([tag.id]);
|
||||
expect(notContainsGoal.filters.tag_match_type).toBe('not_contains');
|
||||
// Entries with other tags and entries without tags count
|
||||
expect(notContainsGoal.progress.tracked_seconds).toBe(2 * 3600 + 30 * 60);
|
||||
|
||||
await expect(goalRow(page, containsGoal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
'1h 00min'
|
||||
);
|
||||
await expect(goalRow(page, notContainsGoal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
'2h 30min'
|
||||
);
|
||||
});
|
||||
|
||||
test('test that the billable filter of a goal only counts entries with the selected billable status', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', billable: true });
|
||||
await createTimeEntryViaApi(ctx, { duration: '2h', billable: false });
|
||||
|
||||
await openCreateGoalModal(page, 'Billable goal');
|
||||
await page.getByRole('combobox').filter({ hasText: 'Billable' }).click();
|
||||
await page.getByRole('option', { name: 'Billable', exact: true }).click();
|
||||
const billableGoal = await submitCreateGoalModal(page);
|
||||
expect(billableGoal.filters.billable).toBe(true);
|
||||
expect(billableGoal.progress.tracked_seconds).toBe(3600);
|
||||
|
||||
await openCreateGoalModal(page, 'Non billable goal');
|
||||
await page.getByRole('combobox').filter({ hasText: 'Billable' }).click();
|
||||
await page.getByRole('option', { name: 'Non Billable' }).click();
|
||||
const nonBillableGoal = await submitCreateGoalModal(page);
|
||||
expect(nonBillableGoal.filters.billable).toBe(false);
|
||||
expect(nonBillableGoal.progress.tracked_seconds).toBe(2 * 3600);
|
||||
|
||||
await expect(goalRow(page, billableGoal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
'1h 00min'
|
||||
);
|
||||
await expect(goalRow(page, nonBillableGoal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
'2h 00min'
|
||||
);
|
||||
});
|
||||
|
||||
test('test that the type filter of a goal only counts entries of the selected type', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h' });
|
||||
await createTimeEntryViaApi(ctx, { duration: '30min', type: 'break' });
|
||||
|
||||
await openCreateGoalModal(page, 'Break goal');
|
||||
await page.getByRole('combobox').filter({ hasText: 'Work time' }).click();
|
||||
await page.getByRole('option', { name: 'Breaks' }).click();
|
||||
const breakGoal = await submitCreateGoalModal(page);
|
||||
expect(breakGoal.filters.time_entry_type).toBe('break');
|
||||
expect(breakGoal.progress.tracked_seconds).toBe(30 * 60);
|
||||
|
||||
await openCreateGoalModal(page, 'Work and break goal');
|
||||
await page.getByRole('combobox').filter({ hasText: 'Work time' }).click();
|
||||
await page.getByRole('option', { name: 'Both' }).click();
|
||||
const bothGoal = await submitCreateGoalModal(page);
|
||||
expect(bothGoal.filters.time_entry_type).toBeNull();
|
||||
expect(bothGoal.progress.tracked_seconds).toBe(3600 + 30 * 60);
|
||||
|
||||
await expect(goalRow(page, breakGoal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
'0h 30min'
|
||||
);
|
||||
await expect(goalRow(page, bothGoal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
'1h 30min'
|
||||
);
|
||||
});
|
||||
|
||||
test('test that a running time entry counts towards the goal progress', async ({ page, ctx }) => {
|
||||
const start = new Date(Date.now() - 30 * 60 * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
await createRunningTimeEntryWithStartViaApi(ctx, 'Running work', start);
|
||||
// Close to midnight UTC the entry would start on the previous day, so the day of the goal
|
||||
// is moved to a timezone (without daylight saving time) where it is late morning instead
|
||||
const utcHour = new Date().getUTCHours();
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Running goal',
|
||||
target_seconds: 3600,
|
||||
period: 'day',
|
||||
timezone: utcHour >= 2 && utcHour < 22 ? 'UTC' : 'Asia/Tokyo',
|
||||
});
|
||||
expect(goal.progress.tracked_seconds).toBeGreaterThanOrEqual(30 * 60);
|
||||
|
||||
await goToGoalsOverview(page);
|
||||
// The entry keeps running while the page loads
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
/^0h 3[0-2]min$/
|
||||
);
|
||||
});
|
||||
|
||||
// Close to midnight UTC an entry that started a few minutes ago could fall on the previous day, so
|
||||
// the day of the goal is moved to a timezone (without daylight saving time) where it is late morning
|
||||
function timezoneAwayFromMidnight() {
|
||||
const utcHour = new Date().getUTCHours();
|
||||
return utcHour >= 2 && utcHour < 22 ? 'UTC' : 'Asia/Tokyo';
|
||||
}
|
||||
|
||||
// Navigates via the sidebar, a full page load would start with an empty query cache and hide
|
||||
// a missing goals invalidation
|
||||
async function navigateViaSidebar(page: Page, name: 'Time' | 'Goals') {
|
||||
await page.getByRole('link', { name, exact: true }).first().click();
|
||||
await expect(page).toHaveURL(new RegExp('/' + name.toLowerCase() + '$'));
|
||||
}
|
||||
|
||||
test('test that goal progress updates after creating a time entry without a page reload', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Cache goal',
|
||||
target_seconds: 3600,
|
||||
period: 'day',
|
||||
timezone: timezoneAwayFromMidnight(),
|
||||
});
|
||||
|
||||
await goToGoalsOverview(page);
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_tracked_time')).toHaveText('0h 00min');
|
||||
|
||||
await navigateViaSidebar(page, 'Time');
|
||||
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||
await page.getByRole('menuitem', { name: 'Manual time entry' }).click();
|
||||
const durationInput = page.locator('[role="dialog"] input[name="Duration"]');
|
||||
await durationInput.fill('15min');
|
||||
await durationInput.press('Tab');
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) => response.url().includes('/time-entries') && response.status() === 201
|
||||
),
|
||||
page.getByRole('button', { name: 'Create Time Entry' }).click(),
|
||||
]);
|
||||
|
||||
await navigateViaSidebar(page, 'Goals');
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_tracked_time')).toHaveText('0h 15min');
|
||||
});
|
||||
|
||||
test('test that goal progress updates after changing the project of the running time entry without a page reload', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const project = await createProjectViaApi(ctx, { name: 'Running Project', is_public: true });
|
||||
const start = new Date(Date.now() - 30 * 60 * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
||||
await createRunningTimeEntryWithStartViaApi(ctx, 'Running work', start);
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Running project goal',
|
||||
target_seconds: 3600,
|
||||
period: 'day',
|
||||
timezone: timezoneAwayFromMidnight(),
|
||||
filters: { project_ids: [project.id], time_entry_type: 'work' },
|
||||
});
|
||||
|
||||
await goToGoalsOverview(page);
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_tracked_time')).toHaveText('0h 00min');
|
||||
|
||||
await navigateViaSidebar(page, 'Time');
|
||||
await page.getByRole('button', { name: 'No Project' }).click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/time-entries') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.project_id === project.id
|
||||
),
|
||||
page.getByRole('option').filter({ hasText: project.name }).click(),
|
||||
]);
|
||||
|
||||
await navigateViaSidebar(page, 'Goals');
|
||||
// The entry keeps running while the test runs
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_tracked_time')).toHaveText(
|
||||
/^0h 3[0-2]min$/
|
||||
);
|
||||
});
|
||||
|
||||
test('test that editing a goal via the modal works', async ({ page, ctx }) => {
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Old goal name',
|
||||
target_seconds: 3600,
|
||||
period: 'week',
|
||||
});
|
||||
await goToGoalsOverview(page);
|
||||
await page.locator("[aria-label='Actions for Goal Old goal name']").click();
|
||||
await page.locator("[aria-label='Edit Goal Old goal name']").click();
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill('New goal name');
|
||||
await page.getByRole('combobox', { name: 'Target type' }).click();
|
||||
await page.getByRole('option', { name: 'Less than' }).click();
|
||||
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'PUT', 200),
|
||||
page.getByRole('button', { name: 'Update Goal' }).click(),
|
||||
]);
|
||||
const body = await response.json();
|
||||
expect(body.data.name).toBe('New goal name');
|
||||
expect(body.data.comparison).toBe('less_than');
|
||||
|
||||
const row = goalRow(page, goal.id);
|
||||
await expect(row.getByTestId('goal_name')).toHaveText('New goal name');
|
||||
await expect(row).toContainText('Less than 1h 00min per week');
|
||||
await expect(row).toContainText('On track');
|
||||
});
|
||||
|
||||
test('test that a goal whose filters point to deleted entities can still be edited', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const keptProject = await createProjectViaApi(ctx, { name: 'Kept project' });
|
||||
const deletedProject = await createProjectViaApi(ctx, { name: 'Deleted project' });
|
||||
const keptTask = await createTaskViaApi(ctx, { name: 'Kept task', project_id: keptProject.id });
|
||||
const deletedTask = await createTaskViaApi(ctx, {
|
||||
name: 'Deleted task',
|
||||
project_id: keptProject.id,
|
||||
});
|
||||
const keptTag = await createTagViaApi(ctx, { name: 'Kept tag' });
|
||||
const deletedTag = await createTagViaApi(ctx, { name: 'Deleted tag' });
|
||||
const deletedClient = await createClientViaApi(ctx, { name: 'Deleted client' });
|
||||
const filters = {
|
||||
project_ids: [keptProject.id, deletedProject.id],
|
||||
task_ids: [keptTask.id, deletedTask.id],
|
||||
// "none" is no entity, it has to survive the cleanup
|
||||
tag_ids: ['none', keptTag.id, deletedTag.id],
|
||||
// Every client of this filter gets deleted
|
||||
client_ids: [deletedClient.id],
|
||||
time_entry_type: 'work' as const,
|
||||
};
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Stale filters',
|
||||
target_seconds: 3600,
|
||||
filters,
|
||||
});
|
||||
await deleteTaskViaApi(ctx, deletedTask.id);
|
||||
await deleteProjectViaApi(ctx, deletedProject.id);
|
||||
await deleteTagViaApi(ctx, deletedTag.id);
|
||||
await deleteClientViaApi(ctx, deletedClient.id);
|
||||
|
||||
// Resending deleted IDs fails; unrelated edits can omit filters to preserve the scope.
|
||||
const rejected = await updateGoalViaApi(ctx, goal.id, { filters });
|
||||
expect(rejected.status()).toBe(422);
|
||||
const errors = (await rejected.json()).errors;
|
||||
expect(Object.keys(errors).sort()).toEqual([
|
||||
'filters.client_ids.0',
|
||||
'filters.project_ids.1',
|
||||
'filters.tag_ids.2',
|
||||
'filters.task_ids.1',
|
||||
]);
|
||||
|
||||
await goToGoalsOverview(page);
|
||||
await page.locator("[aria-label='Actions for Goal Stale filters']").click();
|
||||
await page.locator("[aria-label='Edit Goal Stale filters']").click();
|
||||
// Opening the form must preserve the scope, even after lists have loaded.
|
||||
await expect(page.getByTestId('goal_filter_project_ids')).toHaveText(/Projects\s*2/);
|
||||
await expect(page.getByTestId('goal_filter_task_ids')).toHaveText(/Tasks\s*2/);
|
||||
await expect(page.getByTestId('goal_filter_tag_ids')).toHaveText(/Tags\s*3/);
|
||||
await expect(page.getByTestId('goal_filter_client_ids')).toHaveText(/Clients\s*1/);
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill('Preserved filters');
|
||||
await page.getByRole('button', { name: 'Update Goal' }).click();
|
||||
await expect(page.getByTestId('goal_unavailable_filters')).toContainText(
|
||||
'This will count all clients'
|
||||
);
|
||||
const [preservedResponse] = await Promise.all([
|
||||
goalResponse(page, 'PUT', 200),
|
||||
page.getByRole('button', { name: 'Keep existing filters' }).click(),
|
||||
]);
|
||||
expect(preservedResponse.request().postDataJSON()).not.toHaveProperty('filters');
|
||||
expect((await preservedResponse.json()).data.filters).toMatchObject(filters);
|
||||
|
||||
await page.locator("[aria-label='Actions for Goal Preserved filters']").click();
|
||||
await page.locator("[aria-label='Edit Goal Preserved filters']").click();
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill('Cleaned filters');
|
||||
await page.getByRole('button', { name: 'Update Goal' }).click();
|
||||
await expect(page.getByTestId('goal_unavailable_filters')).toBeVisible();
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'PUT', 200),
|
||||
page.getByRole('button', { name: 'Remove unavailable items' }).click(),
|
||||
]);
|
||||
const body = await response.json();
|
||||
expect(body.data.name).toBe('Cleaned filters');
|
||||
expect(body.data.filters.project_ids).toEqual([keptProject.id]);
|
||||
expect(body.data.filters.task_ids).toEqual([keptTask.id]);
|
||||
expect(body.data.filters.tag_ids).toEqual(['none', keptTag.id]);
|
||||
// A filter whose entities are all gone is dropped, the goal no longer filters by client
|
||||
expect(body.data.filters.client_ids).toBeNull();
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_name')).toHaveText('Cleaned filters');
|
||||
});
|
||||
|
||||
test('losing access to a private project warns without silently changing a personal goal', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
test.setTimeout(120 * 1000);
|
||||
const project = await createProjectViaApi(ctx, {
|
||||
name: 'Private goal project',
|
||||
is_public: false,
|
||||
});
|
||||
const membership = await createProjectMemberViaApi(ctx, project.id, {
|
||||
member_id: employee.memberId,
|
||||
});
|
||||
const employeeCtx = {
|
||||
...(await setupTestContext(employee.page)),
|
||||
orgId: ctx.orgId,
|
||||
memberId: employee.memberId,
|
||||
};
|
||||
const goal = await createGoalViaApi(employeeCtx, {
|
||||
name: 'Private project goal',
|
||||
target_seconds: 3600,
|
||||
filters: { project_ids: [project.id], time_entry_type: 'work' },
|
||||
});
|
||||
const removed = await ctx.request.delete(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/project-members/${membership.id}`
|
||||
);
|
||||
expect(removed.status()).toBe(204);
|
||||
// The project still exists, but the employee's selectable list no longer contains it.
|
||||
const projects = await employeeCtx.request.get(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/projects?archived=all`
|
||||
);
|
||||
expect(projects.status()).toBe(200);
|
||||
expect((await projects.json()).data.map((item: { id: string }) => item.id)).not.toContain(
|
||||
project.id
|
||||
);
|
||||
|
||||
const page = employee.page;
|
||||
await goToGoalsOverview(page);
|
||||
await page.locator("[aria-label='Actions for Goal Private project goal']").click();
|
||||
await page.locator("[aria-label='Edit Goal Private project goal']").click();
|
||||
await expect(page.getByTestId('goal_filter_project_ids')).toHaveText(/Projects\s*1/);
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill('Still scoped');
|
||||
await page.getByRole('button', { name: 'Update Goal' }).click();
|
||||
await expect(page.getByTestId('goal_unavailable_filters')).toContainText(
|
||||
'Unavailable projects: 1'
|
||||
);
|
||||
await expect(page.getByTestId('goal_unavailable_filters')).toContainText(
|
||||
'This will count all projects'
|
||||
);
|
||||
await page.getByRole('button', { name: 'Back', exact: true }).click();
|
||||
await expect(page.getByTestId('goal_filter_project_ids')).toHaveText(/Projects\s*1/);
|
||||
await page.getByRole('button', { name: 'Update Goal' }).click();
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'PUT', 200),
|
||||
page.getByRole('button', { name: 'Keep existing filters' }).click(),
|
||||
]);
|
||||
expect(response.request().postDataJSON()).not.toHaveProperty('filters');
|
||||
expect((await response.json()).data.filters.project_ids).toEqual([project.id]);
|
||||
await expect(goalRow(page, goal.id).getByTestId('goal_name')).toHaveText('Still scoped');
|
||||
});
|
||||
|
||||
test('test that archiving a goal moves it to the archived tab and back', async ({ page, ctx }) => {
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Goal to archive',
|
||||
target_seconds: 3600,
|
||||
});
|
||||
await goToGoalsOverview(page);
|
||||
await expect(goalRow(page, goal.id)).toBeVisible();
|
||||
|
||||
await page.locator("[aria-label='Actions for Goal Goal to archive']").click();
|
||||
await Promise.all([
|
||||
goalResponse(page, 'PUT', 200),
|
||||
page.locator("[aria-label='Archive Goal Goal to archive']").click(),
|
||||
]);
|
||||
await expect(goalRow(page, goal.id)).not.toBeVisible();
|
||||
await expect(page.getByTestId('goal_table')).toContainText('No goals found');
|
||||
|
||||
await page.getByRole('tab', { name: 'Archived' }).click();
|
||||
const archivedRow = goalRow(page, goal.id);
|
||||
await expect(archivedRow).toBeVisible();
|
||||
await expect(archivedRow.getByTestId('goal_archived_badge')).toBeVisible();
|
||||
|
||||
await page.locator("[aria-label='Actions for Goal Goal to archive']").click();
|
||||
await Promise.all([
|
||||
goalResponse(page, 'PUT', 200),
|
||||
page.locator("[aria-label='Unarchive Goal Goal to archive']").click(),
|
||||
]);
|
||||
await expect(goalRow(page, goal.id)).not.toBeVisible();
|
||||
await page.getByRole('tab', { name: 'Active' }).click();
|
||||
await expect(goalRow(page, goal.id)).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that the period settings of a goal can be changed in the accordion', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Goal with timezone',
|
||||
target_seconds: 3600,
|
||||
period: 'week',
|
||||
timezone: 'Asia/Tokyo',
|
||||
week_start: 'friday',
|
||||
});
|
||||
await goToGoalsOverview(page);
|
||||
await page.locator("[aria-label='Actions for Goal Goal with timezone']").click();
|
||||
await page.locator("[aria-label='Edit Goal Goal with timezone']").click();
|
||||
await page.getByTestId('goal_period_settings').click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await expect(timezoneField(dialog)).toHaveText('Asia/Tokyo');
|
||||
await expect(weekStartField(dialog)).toHaveText('Friday');
|
||||
|
||||
await selectTimezone(page, dialog, 'America/New_York', 'new york');
|
||||
await selectWeekStart(page, dialog, 'Sunday');
|
||||
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'PUT', 200),
|
||||
page.getByRole('button', { name: 'Update Goal' }).click(),
|
||||
]);
|
||||
const body = await response.json();
|
||||
expect(body.data.id).toBe(goal.id);
|
||||
expect(body.data.timezone).toBe('America/New_York');
|
||||
expect(body.data.week_start).toBe('sunday');
|
||||
});
|
||||
|
||||
test('test that the period settings of a new goal default to the user settings', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Same UTC offset as the browser, so the timezone mismatch modal stays closed
|
||||
await updateUserProfileViaApi(ctx, { timezone: 'Atlantic/Reykjavik', week_start: 'wednesday' });
|
||||
await goToGoalsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Goal' }).click();
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill('Goal with defaults');
|
||||
await page.getByTestId('duration_seconds_input').fill('10h');
|
||||
await page.getByTestId('duration_seconds_input').press('Tab');
|
||||
await page.getByTestId('goal_period_settings').click();
|
||||
await expect(timezoneField(page.getByRole('dialog'))).toHaveText('Atlantic/Reykjavik');
|
||||
await expect(weekStartField(page.getByRole('dialog'))).toHaveText('Wednesday');
|
||||
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'POST', 201),
|
||||
page.getByRole('button', { name: 'Create Goal', exact: true }).last().click(),
|
||||
]);
|
||||
const body = await response.json();
|
||||
expect(body.data.timezone).toBe('Atlantic/Reykjavik');
|
||||
expect(body.data.week_start).toBe('wednesday');
|
||||
});
|
||||
|
||||
test('test that the period settings of a new goal can be set in the create modal', async ({
|
||||
page,
|
||||
}) => {
|
||||
await goToGoalsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Goal' }).click();
|
||||
await page.getByPlaceholder('e.g. Deep work on Project X').fill('Goal in New York');
|
||||
await page.getByTestId('duration_seconds_input').fill('10h');
|
||||
await page.getByTestId('duration_seconds_input').press('Tab');
|
||||
await page.getByTestId('goal_period_settings').click();
|
||||
const dialog = page.getByRole('dialog');
|
||||
await selectTimezone(page, dialog, 'America/New_York', 'new york');
|
||||
await selectWeekStart(page, dialog, 'Saturday');
|
||||
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(page, 'POST', 201),
|
||||
page.getByRole('button', { name: 'Create Goal', exact: true }).last().click(),
|
||||
]);
|
||||
const body = await response.json();
|
||||
expect(body.data.name).toBe('Goal in New York');
|
||||
expect(body.data.timezone).toBe('America/New_York');
|
||||
expect(body.data.week_start).toBe('saturday');
|
||||
});
|
||||
|
||||
test('test that the search of a goal filter can be used with the keyboard', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await createProjectViaApi(ctx, { name: 'Alpha keyboard project', is_public: true });
|
||||
await createProjectViaApi(ctx, { name: 'Beta keyboard project', is_public: true });
|
||||
await goToGoalsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Goal' }).click();
|
||||
await page.getByTestId('goal_filter_project_ids').click();
|
||||
|
||||
const search = page.getByPlaceholder('Search for a Project...');
|
||||
await search.click();
|
||||
await search.pressSequentially('alpha');
|
||||
await expect(search).toHaveValue('alpha');
|
||||
await expect(page.getByRole('option', { name: 'Beta keyboard project' })).toBeHidden();
|
||||
|
||||
// The arrow keys highlight an option while the focus stays in the search
|
||||
const alpha = page.getByRole('option', { name: 'Alpha keyboard project' });
|
||||
await search.press('ArrowDown');
|
||||
await expect(alpha).toHaveAttribute('data-highlighted', '');
|
||||
await search.press('Enter');
|
||||
await expect(search).toBeFocused();
|
||||
await expect(page.getByTestId('goal_filter_project_ids')).toHaveText(/Projects\s*1/);
|
||||
|
||||
// Escape closes the dropdown but keeps the modal and the selection
|
||||
await search.press('Escape');
|
||||
await expect(search).toBeHidden();
|
||||
await expect(page.getByPlaceholder('e.g. Deep work on Project X')).toBeVisible();
|
||||
await expect(page.getByTestId('goal_filter_project_ids')).toHaveText(/Projects\s*1/);
|
||||
});
|
||||
|
||||
test('test that deleting a goal via the more options dropdown works', async ({ page, ctx }) => {
|
||||
const goal = await createGoalViaApi(ctx, {
|
||||
name: 'Goal to delete',
|
||||
target_seconds: 3600,
|
||||
});
|
||||
await goToGoalsOverview(page);
|
||||
await expect(goalRow(page, goal.id)).toBeVisible();
|
||||
await page.locator("[aria-label='Actions for Goal Goal to delete']").click();
|
||||
await Promise.all([
|
||||
goalResponse(page, 'DELETE', 204),
|
||||
page.locator("[aria-label='Delete Goal Goal to delete']").click(),
|
||||
]);
|
||||
await expect(goalRow(page, goal.id)).not.toBeVisible();
|
||||
await expect(page.getByTestId('goal_table')).toContainText('No goals found');
|
||||
});
|
||||
|
||||
test.describe('employee', () => {
|
||||
test('employee can create and see their own goals', async ({ employee }) => {
|
||||
await goToGoalsOverview(employee.page);
|
||||
await employee.page.getByRole('button', { name: 'Create Goal' }).click();
|
||||
await employee.page.getByPlaceholder('e.g. Deep work on Project X').fill('Employee goal');
|
||||
await employee.page.getByTestId('duration_seconds_input').fill('2h');
|
||||
await employee.page.getByTestId('duration_seconds_input').press('Tab');
|
||||
const [response] = await Promise.all([
|
||||
goalResponse(employee.page, 'POST', 201),
|
||||
employee.page.getByRole('button', { name: 'Create Goal', exact: true }).last().click(),
|
||||
]);
|
||||
const body = await response.json();
|
||||
expect(body.data.type).toBe('personal');
|
||||
expect(body.data.member_id).toBe(employee.memberId);
|
||||
await expect(goalRow(employee.page, body.data.id)).toContainText('Employee goal');
|
||||
});
|
||||
});
|
||||
@@ -884,7 +884,7 @@ test('test that sorting members by billable rate works', async ({ page, ctx }) =
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// First click = desc (highest first), null rates last
|
||||
const billableHeader = table.getByText('Billable Rate').first();
|
||||
const billableHeader = table.getByRole('button', { name: /Billable Rate/ });
|
||||
await billableHeader.click();
|
||||
await expect(billableHeader.locator('svg')).toBeVisible();
|
||||
let names = await getTableRowNames(table);
|
||||
|
||||
@@ -7,6 +7,12 @@ import {
|
||||
} from './utils/mailpit';
|
||||
import { getCurrentUserViaApi } from './utils/api';
|
||||
import { registerUser } from './utils/members';
|
||||
import {
|
||||
selectTimezone,
|
||||
selectWeekStart,
|
||||
timezoneField,
|
||||
weekStartField,
|
||||
} from './utils/userSettingsFields';
|
||||
import type { Page } from '@playwright/test';
|
||||
import path from 'path';
|
||||
|
||||
@@ -40,20 +46,51 @@ test('user name can be updated', async ({ page }) => {
|
||||
await expect(page.getByLabel('Name', { exact: true })).toHaveValue('NEW NAME');
|
||||
});
|
||||
|
||||
// The tests below pick UTC+0 timezones: the browser runs in UTC, and any other offset
|
||||
// opens the timezone mismatch modal after the reload.
|
||||
test('timezone change persists across reload', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
await page.getByLabel('Timezone').selectOption('America/New_York');
|
||||
await selectTimezone(page, page, 'Africa/Sao_Tome', 'sao tome');
|
||||
await saveProfileForm(page);
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Timezone')).toHaveValue('America/New_York');
|
||||
await expect(timezoneField(page)).toHaveText('Africa/Sao_Tome');
|
||||
});
|
||||
|
||||
test('timezone can be selected with the keyboard', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
await expect(timezoneField(page)).toBeEnabled();
|
||||
await timezoneField(page).focus();
|
||||
await page.keyboard.press('Enter');
|
||||
const search = page.getByRole('combobox', { name: 'Search timezones' });
|
||||
await expect(search).toBeFocused();
|
||||
await search.fill('Africa/Abid');
|
||||
await expect(page.getByRole('option')).toHaveText(['Africa/Abidjan']);
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('Enter');
|
||||
await expect(timezoneField(page)).toHaveText('Africa/Abidjan');
|
||||
await saveProfileForm(page);
|
||||
await page.reload();
|
||||
await expect(timezoneField(page)).toHaveText('Africa/Abidjan');
|
||||
});
|
||||
|
||||
test('timezone search shows an empty state when nothing matches', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
await timezoneField(page).click();
|
||||
const search = page.getByRole('combobox', { name: 'Search timezones' });
|
||||
// Opening starts with an empty search, not one prefilled with the current timezone
|
||||
await expect(search).toHaveValue('');
|
||||
await expect(page.getByRole('option').nth(1)).toBeVisible();
|
||||
await search.fill('Atlantis');
|
||||
await expect(page.getByText('No timezone found.')).toBeVisible();
|
||||
await expect(page.getByRole('option')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('week-start change persists across reload', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
await page.getByLabel('Start of the week').selectOption('sunday');
|
||||
await selectWeekStart(page, page, 'Sunday');
|
||||
await saveProfileForm(page);
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Start of the week')).toHaveValue('sunday');
|
||||
await expect(weekStartField(page)).toHaveText('Sunday');
|
||||
});
|
||||
|
||||
test('still-running email notification setting persists across reload', async ({ page }) => {
|
||||
@@ -565,7 +602,10 @@ test('test that theme can be changed to dark and light', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
// The theme select is a Reka UI combobox (button), not a native <select>
|
||||
const themeSelect = page.locator('button[role="combobox"]');
|
||||
const themeSelect = page
|
||||
.getByRole('heading', { name: 'Theme', exact: true })
|
||||
.locator('xpath=ancestor::*[descendant::form][1]')
|
||||
.getByRole('combobox');
|
||||
|
||||
// Change theme to dark
|
||||
await themeSelect.click();
|
||||
@@ -591,7 +631,7 @@ test('test that theme can be changed to dark and light', async ({ page }) => {
|
||||
await expect(page.locator('html')).toHaveClass(/light/);
|
||||
|
||||
// Reset to system
|
||||
await page.locator('button[role="combobox"]').click();
|
||||
await themeSelect.click();
|
||||
await page.getByRole('option', { name: 'System' }).click();
|
||||
await expect(page.getByText('System default:')).toBeVisible();
|
||||
});
|
||||
|
||||
110
e2e/utils/api.ts
110
e2e/utils/api.ts
@@ -990,3 +990,113 @@ export async function getInvoicesViaApi(ctx: TestContext) {
|
||||
paid_date: string | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export async function createGoalViaApi(
|
||||
ctx: TestContext,
|
||||
data: {
|
||||
name: string;
|
||||
type?: 'personal' | 'organization';
|
||||
comparison?: 'at_least' | 'less_than';
|
||||
target_seconds: number;
|
||||
period?: 'day' | 'week' | 'month';
|
||||
// Member the goal is for, null counts every member (organization goals only)
|
||||
member_id?: string | null;
|
||||
timezone?: string;
|
||||
week_start?: string;
|
||||
filters?: {
|
||||
member_ids?: string[] | null;
|
||||
project_ids?: string[] | null;
|
||||
task_ids?: string[] | null;
|
||||
tag_ids?: string[] | null;
|
||||
tag_match_type?: 'contains' | 'not_contains' | null;
|
||||
client_ids?: string[] | null;
|
||||
billable?: boolean | null;
|
||||
time_entry_type?: 'work' | 'break' | null;
|
||||
};
|
||||
}
|
||||
) {
|
||||
const response = await ctx.request.post(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/goals`,
|
||||
{
|
||||
data: {
|
||||
name: data.name,
|
||||
type: data.type ?? 'personal',
|
||||
comparison: data.comparison ?? 'at_least',
|
||||
target_seconds: data.target_seconds,
|
||||
period: data.period ?? 'week',
|
||||
...('member_id' in data ? { member_id: data.member_id } : {}),
|
||||
...(data.timezone ? { timezone: data.timezone } : {}),
|
||||
...(data.week_start ? { week_start: data.week_start } : {}),
|
||||
filters: data.filters ?? { time_entry_type: 'work' },
|
||||
},
|
||||
}
|
||||
);
|
||||
expect(response.status()).toBe(201);
|
||||
const body = await response.json();
|
||||
return body.data as {
|
||||
id: string;
|
||||
name: string;
|
||||
type: 'personal' | 'organization';
|
||||
comparison: 'at_least' | 'less_than';
|
||||
target_seconds: number;
|
||||
period: 'day' | 'week' | 'month';
|
||||
member_id: string | null;
|
||||
member_name: string | null;
|
||||
timezone: string;
|
||||
week_start: string;
|
||||
is_archived: boolean;
|
||||
progress: {
|
||||
tracked_seconds: number;
|
||||
status: 'in_progress' | 'achieved' | 'on_track' | 'exceeded';
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export async function updateGoalViaApi(
|
||||
ctx: TestContext,
|
||||
goalId: string,
|
||||
data: Record<string, unknown>
|
||||
) {
|
||||
return ctx.request.put(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/goals/${goalId}`,
|
||||
{ data }
|
||||
);
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────
|
||||
// Entity deletion
|
||||
// ──────────────────────────────────────────────────
|
||||
|
||||
async function deleteEntityViaApi(ctx: TestContext, path: string) {
|
||||
const response = await ctx.request.delete(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/${path}`
|
||||
);
|
||||
expect(response.status()).toBe(204);
|
||||
}
|
||||
|
||||
export async function deleteProjectViaApi(ctx: TestContext, projectId: string) {
|
||||
await deleteEntityViaApi(ctx, `projects/${projectId}`);
|
||||
}
|
||||
|
||||
export async function deleteTaskViaApi(ctx: TestContext, taskId: string) {
|
||||
await deleteEntityViaApi(ctx, `tasks/${taskId}`);
|
||||
}
|
||||
|
||||
export async function deleteTagViaApi(ctx: TestContext, tagId: string) {
|
||||
await deleteEntityViaApi(ctx, `tags/${tagId}`);
|
||||
}
|
||||
|
||||
export async function deleteClientViaApi(ctx: TestContext, clientId: string) {
|
||||
await deleteEntityViaApi(ctx, `clients/${clientId}`);
|
||||
}
|
||||
|
||||
export async function deleteMemberViaApi(ctx: TestContext, memberId: string) {
|
||||
await deleteEntityViaApi(ctx, `members/${memberId}`);
|
||||
}
|
||||
|
||||
export async function makeMemberPlaceholderViaApi(ctx: TestContext, memberId: string) {
|
||||
const response = await ctx.request.post(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/members/${memberId}/make-placeholder`
|
||||
);
|
||||
expect(response.status()).toBe(204);
|
||||
}
|
||||
|
||||
14
e2e/utils/billing.ts
Normal file
14
e2e/utils/billing.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { expect } from '@playwright/test';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../../playwright/config';
|
||||
import type { TestContext } from './api';
|
||||
|
||||
/**
|
||||
* End the trial of the test organization, only works with the Billing extension. Reload the page
|
||||
* afterwards, the page props still contain the trial otherwise.
|
||||
*/
|
||||
export async function cancelTrialViaApi(ctx: TestContext): Promise<void> {
|
||||
const response = await ctx.request.post(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/trial/cancel`
|
||||
);
|
||||
expect(response.status()).toBe(204);
|
||||
}
|
||||
34
e2e/utils/userSettingsFields.ts
Normal file
34
e2e/utils/userSettingsFields.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Helpers for the shared TimezoneCombobox and WeekStartSelect components used in
|
||||
* the profile form and the goal form.
|
||||
*/
|
||||
|
||||
export function timezoneField(scope: Page | Locator) {
|
||||
// The trigger is named "Timezone: <current value>"
|
||||
return scope.getByRole('button', { name: /^Timezone/ });
|
||||
}
|
||||
|
||||
export function weekStartField(scope: Page | Locator) {
|
||||
return scope.getByRole('combobox', { name: 'Start of the week' });
|
||||
}
|
||||
|
||||
export async function selectTimezone(
|
||||
page: Page,
|
||||
scope: Page | Locator,
|
||||
timezone: string,
|
||||
search: string = timezone
|
||||
) {
|
||||
await timezoneField(scope).click();
|
||||
await page.getByRole('combobox', { name: 'Search timezones' }).fill(search);
|
||||
await page.getByRole('option', { name: timezone, exact: true }).click();
|
||||
await expect(timezoneField(scope)).toHaveText(timezone);
|
||||
}
|
||||
|
||||
export async function selectWeekStart(page: Page, scope: Page | Locator, weekdayLabel: string) {
|
||||
await weekStartField(scope).click();
|
||||
await page.getByRole('option', { name: weekdayLabel, exact: true }).click();
|
||||
await expect(weekStartField(scope)).toHaveText(weekdayLabel);
|
||||
}
|
||||
@@ -1,18 +1,18 @@
|
||||
{
|
||||
"Billing": {
|
||||
"repository": "solidtime-io/extension-billing",
|
||||
"ref": "v0.0.9"
|
||||
"ref": "v0.0.11"
|
||||
},
|
||||
"Services": {
|
||||
"repository": "solidtime-io/extension-services",
|
||||
"ref": "v0.0.4"
|
||||
"ref": "v0.0.6"
|
||||
},
|
||||
"Invoicing": {
|
||||
"repository": "solidtime-io/extension-invoicing",
|
||||
"ref": "v0.0.8"
|
||||
"ref": "v0.0.12"
|
||||
},
|
||||
"Auditing": {
|
||||
"repository": "solidtime-io/extension-auditing",
|
||||
"ref": "v0.0.4"
|
||||
"ref": "v0.0.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
|
||||
use App\Exceptions\Api\PersonalAccessClientIsNotConfiguredException;
|
||||
use App\Exceptions\Api\ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException;
|
||||
use App\Exceptions\Api\TimeEntryCanNotBeRestartedApiException;
|
||||
use App\Exceptions\Api\TimeEntryMemberCanNotBeChangedWhileRunningApiException;
|
||||
use App\Exceptions\Api\TimeEntryStillRunningApiException;
|
||||
use App\Exceptions\Api\UserIsAlreadyMemberOfOrganizationApiException;
|
||||
use App\Exceptions\Api\UserIsAlreadyMemberOfProjectApiException;
|
||||
@@ -31,6 +32,7 @@ return [
|
||||
TimeEntryStillRunningApiException::KEY => 'Time entry is still running',
|
||||
UserNotPlaceholderApiException::KEY => 'The given user is not a placeholder',
|
||||
TimeEntryCanNotBeRestartedApiException::KEY => 'Time entry is already stopped and can not be restarted',
|
||||
TimeEntryMemberCanNotBeChangedWhileRunningApiException::KEY => 'The member of a running time entry can not be changed',
|
||||
InactiveUserCanNotBeUsedApiException::KEY => 'Inactive user can not be used',
|
||||
UserIsAlreadyMemberOfOrganizationApiException::KEY => 'User is already a member of the organization',
|
||||
UserIsAlreadyMemberOfProjectApiException::KEY => 'User is already a member of the project',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { enabledExtensions } from './playwright/config';
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
@@ -7,23 +7,11 @@ import { existsSync, readFileSync } from 'node:fs';
|
||||
*/
|
||||
// require('dotenv').config();
|
||||
|
||||
/**
|
||||
/*
|
||||
* Extensions ship their e2e specs in extensions/<Name>/tests/e2e. Only the specs of extensions
|
||||
* that are enabled in modules_statuses.json (php artisan module:enable <Name>) are collected,
|
||||
* a checked out but disabled extension would fail its specs otherwise.
|
||||
*/
|
||||
function enabledExtensions(): string[] {
|
||||
const statusesFile = './modules_statuses.json';
|
||||
if (!existsSync(statusesFile)) {
|
||||
return [];
|
||||
}
|
||||
const statuses: Record<string, boolean> = JSON.parse(readFileSync(statusesFile, 'utf-8'));
|
||||
return Object.entries(statuses)
|
||||
.filter(([, enabled]) => enabled)
|
||||
.map(([name]) => name);
|
||||
}
|
||||
|
||||
/*
|
||||
*
|
||||
* Every test root gets its own testDir (instead of testDir: '.') so playwright does not walk the
|
||||
* whole repository, including node_modules, vendor and nested worktrees, to find the specs.
|
||||
*/
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
|
||||
export const PLAYWRIGHT_BASE_URL = process.env.PLAYWRIGHT_BASE_URL ?? 'http://solidtime.test';
|
||||
export const MAILPIT_BASE_URL = process.env.MAILPIT_BASE_URL ?? 'http://mailpit:8025';
|
||||
export const TEST_USER_PASSWORD = 'amazingpassword123';
|
||||
|
||||
/**
|
||||
* Extensions that are enabled in modules_statuses.json (php artisan module:enable <Name>)
|
||||
*/
|
||||
export function enabledExtensions(): string[] {
|
||||
const statusesFile = './modules_statuses.json';
|
||||
if (!existsSync(statusesFile)) {
|
||||
return [];
|
||||
}
|
||||
const statuses: Record<string, boolean> = JSON.parse(readFileSync(statusesFile, 'utf-8'));
|
||||
return Object.entries(statuses)
|
||||
.filter(([, enabled]) => enabled)
|
||||
.map(([name]) => name);
|
||||
}
|
||||
|
||||
export function isExtensionEnabled(name: string): boolean {
|
||||
return enabledExtensions().includes(name);
|
||||
}
|
||||
|
||||
@@ -1,137 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import MainContainer from '@/packages/ui/src/MainContainer.vue';
|
||||
import { CheckBadgeIcon, XMarkIcon, XCircleIcon } from '@heroicons/vue/16/solid';
|
||||
import { XMarkIcon, XCircleIcon } from '@heroicons/vue/16/solid';
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
daysLeftInTrial,
|
||||
isBillingActivated,
|
||||
isBlocked,
|
||||
isFreePlan,
|
||||
isInTrial,
|
||||
} from '@/utils/billing';
|
||||
import { isBillingActivated, isBlocked } from '@/utils/billing';
|
||||
import { useSessionStorage } from '@vueuse/core';
|
||||
import { getCurrentOrganizationId } from '@/utils/useUser';
|
||||
import { canManageBilling } from '@/utils/permissions';
|
||||
|
||||
const hideTrialBanner = useSessionStorage('showTrialBanner-' + getCurrentOrganizationId(), false);
|
||||
const showTrialBanner = computed(() => isInTrial() && !hideTrialBanner.value);
|
||||
const hideBlockedBanner = useSessionStorage(
|
||||
'showBlockedBanner-' + getCurrentOrganizationId(),
|
||||
false
|
||||
);
|
||||
const showBlockedBanner = computed(() => isBlocked() && !hideBlockedBanner.value);
|
||||
const hideFreeUpgradeBanner = useSessionStorage(
|
||||
'showFreeUpgradeBanner-' + getCurrentOrganizationId(),
|
||||
false
|
||||
);
|
||||
const showFreeUpgradeBanner = computed(
|
||||
() =>
|
||||
isFreePlan() && !isBlocked() && !hideFreeUpgradeBanner.value && !showBlackFridayBanner.value
|
||||
);
|
||||
const hideBlackFridayBanner = useSessionStorage(
|
||||
'hideBlackFridayBanner-' + getCurrentOrganizationId(),
|
||||
false
|
||||
);
|
||||
|
||||
const showBlackFridayBanner = computed(() => {
|
||||
if (hideBlackFridayBanner.value) {
|
||||
return false;
|
||||
}
|
||||
const today = new Date();
|
||||
const blackFriday = new Date(2024, 10, 30);
|
||||
return today < blackFriday;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="showBlackFridayBanner"
|
||||
class="bg-tertiary text-xs lg:text-sm pb-1 pt-2 border-b border-border-secondary">
|
||||
<MainContainer class="flex items-center justify-between">
|
||||
<div class="flex items-center space-x-1.5">
|
||||
<svg class="w-4 mr-1" viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
fill="#FF37AD"
|
||||
d="M22.498 68.97a11.845 11.845 0 1 0 0-23.687c-6.471.098-11.666 5.372-11.666 11.844s5.195 11.746 11.666 11.844m181.393-10.04a11.845 11.845 0 1 0-.003-23.688c-6.471.098-11.665 5.373-11.665 11.845c.001 6.472 5.197 11.745 11.668 11.842" />
|
||||
<path
|
||||
fill="#FCC954"
|
||||
d="M213.503 211.097a11.845 11.845 0 1 0-.003-23.687c-6.471.098-11.665 5.373-11.664 11.845s5.196 11.745 11.667 11.842M70.872 23.689a11.845 11.845 0 1 0 0-23.688C64.4.1 59.206 5.373 59.206 11.845S64.4 23.591 70.872 23.689" />
|
||||
<path
|
||||
fill="#2890E9"
|
||||
d="M140.945 105.94a9.25 9.25 0 0 1-8.974-11.484c.37-1.482.672-2.97.899-4.455a25.4 25.4 0 0 1-8.732 1.904c-5.379.205-10.195-.702-14.3-2.69a22.23 22.23 0 0 1-9.614-8.877c-4.415-7.652-4.034-17.718.964-25.645c4.765-7.568 12.836-11.664 21.586-10.995c6.74.527 12.647 3.051 17.378 7.382q1.293-3.647 2.473-7.803c4.833-17.058 6.429-34.187 6.442-34.36a9.24 9.24 0 0 1 10.041-8.37a9.25 9.25 0 0 1 8.37 10.044c-.067.767-1.768 19.03-7.068 37.735c-2.676 9.445-5.838 17.426-9.42 23.798q.396 2.13.631 4.372c.746 7.211.152 14.974-1.714 22.445a9.256 9.256 0 0 1-8.962 6.998m-20.123-43.827c-.956 0-2.64.28-3.996 2.43c-1.298 2.06-1.552 4.873-.588 6.544c1.282 2.223 5.054 2.417 7.19 2.336c2.424-.092 4.908-1.612 7.338-4.382a16 16 0 0 0-1.43-2.422c-2.007-2.787-4.547-4.212-7.998-4.482c-.13-.008-.305-.024-.516-.024" />
|
||||
<path
|
||||
fill="#F0A420"
|
||||
d="M114.361 131.268c-38.343-30.224-78.42-43.319-89.514-29.246a12.8 12.8 0 0 0-2.257 4.509a4 4 0 0 0-.156.61v.024q-.223.947-.333 1.917L.393 236.18c-3.477 20.412 16.73 36.755 35.967 29.093l117.721-46.908c2.076-.826 7.185-3.982 8.583-5.724q.556-.544 1.037-1.153c11.092-14.075-11-49.988-49.34-80.223z" />
|
||||
<path
|
||||
fill="#FCC954"
|
||||
d="M163.688 211.494c11.1-14.08-10.984-50-49.327-80.226c-38.343-30.227-78.425-43.316-89.524-29.236s10.983 50 49.326 80.226c38.343 30.227 78.425 43.316 89.525 29.236" />
|
||||
<path
|
||||
fill="#F0A420"
|
||||
d="M156.994 203.294c9.108-11.556-10.956-42.563-44.817-69.256c-33.861-26.695-68.697-38.966-77.804-27.413c-9.11 11.556 10.954 42.563 44.815 69.256c33.86 26.695 68.697 38.969 77.806 27.413" />
|
||||
<path
|
||||
fill="#2E6AC9"
|
||||
d="M76.059 249.456c-14.327.07-26.004-7.101-40.158-18.257C19.431 218.21 8.493 202.665 7.63 193.81l-4.668 27.327c2.16 7.798 9.523 17.683 20.202 26.101c8.883 7.004 17.844 11.813 27.135 12.48l25.76-10.266zm-14.332-49.6c-27.443-21.637-45.271-46.467-44.77-60.669l-4.549 26.63c.351 12.685 15.175 33.184 36.262 49.808c18.894 14.896 38.583 25.38 53.66 23.363l25.593-10.2c-20.62 1.425-42.376-10.147-66.196-28.931" />
|
||||
<path
|
||||
fill="#2890E9"
|
||||
d="M118.535 145.052a11.845 11.845 0 1 0 0-23.688c-6.471.098-11.666 5.372-11.666 11.844s5.195 11.746 11.666 11.844" />
|
||||
<path
|
||||
fill="#FF37AD"
|
||||
d="m182.412 122.007l.087-.097c.108-.116.308-.33.596-.621a45 45 0 0 1 2.8-2.56c3.56-2.98 7.45-5.54 11.594-7.63c10.128-5.125 25.208-9.307 44.985-4.747c5.943 1.37 11.87-2.336 13.241-8.278c1.37-5.942-2.336-11.87-8.278-13.24c-25.602-5.903-45.957-.506-59.922 6.566a82.5 82.5 0 0 0-15.857 10.449a66 66 0 0 0-4.215 3.866a45 45 0 0 0-1.53 1.615l-.12.135l-.042.048l-.02.022l-.007.008c-.003.005-.009.01 8.361 7.21l-8.37-7.2c-3.877 4.622-3.328 11.5 1.233 15.448s11.446 3.506 15.464-.994M73.03 43.248a11.75 11.75 0 0 0-16.23-3.664a11.76 11.76 0 0 0-3.665 16.227c.427.683 9.178 14.86 10.976 34.276c1.83 19.727-3.966 37.86-17.253 54.12c4.474 5.686 9.858 11.596 16.008 17.507c8.51-9.834 14.913-20.402 19.12-31.583c5.175-13.756 7.006-28.342 5.445-43.348c-2.487-23.874-12.874-41.11-14.402-43.535" />
|
||||
<path
|
||||
fill="#2890E9"
|
||||
d="M220.242 156.578c6.002 1.553 10.244 3.246 12.077 4.034a11.86 11.86 0 0 0 13.94-1.12a11.87 11.87 0 0 0 4.107-8.765a11.85 11.85 0 0 0-8.06-11.426c-5.618-2.495-26.905-10.92-55.044-9.423c-18.941 1.007-37.155 6.253-54.133 15.608c-16.076 8.86-31.004 21.412-44.556 37.425a199 199 0 0 0 20.17 12.607c22.882-26.08 49.283-40.217 78.7-42.085a105.9 105.9 0 0 1 32.8 3.145" />
|
||||
</svg>
|
||||
<div class="flex-1 space-x-1">
|
||||
<span class="font-medium">
|
||||
<strong>BLACK FRIDAY SALE!</strong> Use the code
|
||||
<strong>BLACKFRIDAY</strong> at checkout and get
|
||||
<strong>30% off</strong> the solidtime yearly plan.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
<Link v-if="canManageBilling()" href="/billing">
|
||||
<div
|
||||
class="text-text-primary font-semibold uppercase text-xs flex space-x-1 items-center hover:bg-white/10 rounded-lg px-2 py-1.5">
|
||||
<span>Upgrade now</span>
|
||||
</div>
|
||||
</Link>
|
||||
<button class="p-1" @click="hideBlackFridayBanner = true">
|
||||
<XMarkIcon class="w-4 opacity-50 hover:opacity-100"></XMarkIcon>
|
||||
</button>
|
||||
</div>
|
||||
</MainContainer>
|
||||
</div>
|
||||
<div
|
||||
v-if="showTrialBanner"
|
||||
class="bg-accent-600/50 text-xs lg:text-sm py-0.5 border-b border-border-secondary">
|
||||
<MainContainer class="flex items-center justify-between">
|
||||
<div class="flex items-center space-x-1.5">
|
||||
<CheckBadgeIcon class="w-4 text-text-primary/50"></CheckBadgeIcon>
|
||||
<div class="flex-1 space-x-1">
|
||||
<span class="font-medium">
|
||||
Your trial expires in {{ daysLeftInTrial() }} days.
|
||||
</span>
|
||||
<span class="hidden md:inline">
|
||||
To continue using all features & support the development of solidtime,
|
||||
please upgrade your plan.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
<Link v-if="canManageBilling()" href="/billing">
|
||||
<div
|
||||
class="text-text-primary font-semibold uppercase text-xs flex space-x-1 items-center hover:bg-white/10 rounded-lg px-2 py-1.5">
|
||||
<span>Upgrade now</span>
|
||||
</div>
|
||||
</Link>
|
||||
<button class="p-1" @click="hideTrialBanner = true">
|
||||
<XMarkIcon class="w-4 opacity-50 hover:opacity-100"></XMarkIcon>
|
||||
</button>
|
||||
</div>
|
||||
</MainContainer>
|
||||
</div>
|
||||
<div
|
||||
v-if="showBlockedBanner"
|
||||
class="bg-red-600/50 text-xs lg:text-sm py-0.5 border-b border-border-secondary">
|
||||
@@ -159,33 +43,6 @@ const showBlackFridayBanner = computed(() => {
|
||||
</div>
|
||||
</MainContainer>
|
||||
</div>
|
||||
<div
|
||||
v-if="showFreeUpgradeBanner"
|
||||
class="bg-tertiary text-xs lg:text-sm py-0.5 border-b border-border-secondary">
|
||||
<MainContainer class="flex items-center justify-between">
|
||||
<div class="flex items-center space-x-1.5">
|
||||
<XCircleIcon class="w-4 text-text-primary/50"></XCircleIcon>
|
||||
<div class="flex-1 space-x-1">
|
||||
<span class="font-medium"> You are currently using the Free Plan. </span>
|
||||
<span class="hidden md:inline">
|
||||
To unlock all premium features & support the development of solidtime,
|
||||
please upgrade your plan.</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
<Link v-if="isBillingActivated() && canManageBilling()" href="/billing">
|
||||
<div
|
||||
class="text-text-primary font-semibold uppercase text-xs flex space-x-1 items-center hover:bg-white/10 rounded-lg px-2 py-1.5">
|
||||
<span>Upgrade now</span>
|
||||
</div>
|
||||
</Link>
|
||||
<button class="p-1" @click="hideFreeUpgradeBanner = true">
|
||||
<XMarkIcon class="w-4 opacity-50 hover:opacity-100"></XMarkIcon>
|
||||
</button>
|
||||
</div>
|
||||
</MainContainer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
|
||||
86
resources/js/Components/Billing/CancelTrialModal.vue
Normal file
86
resources/js/Components/Billing/CancelTrialModal.vue
Normal file
@@ -0,0 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { router } from '@inertiajs/vue3';
|
||||
import DialogModal from '@/packages/ui/src/DialogModal.vue';
|
||||
import DangerButton from '@/packages/ui/src/Buttons/DangerButton.vue';
|
||||
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||
import { XMarkIcon } from '@heroicons/vue/16/solid';
|
||||
import { useNotificationsStore } from '@/utils/notification';
|
||||
import { getCurrentOrganizationId } from '@/utils/useUser';
|
||||
import { api } from '@/packages/api/src';
|
||||
|
||||
const show = defineModel<boolean>('show', { default: false });
|
||||
|
||||
const processing = ref(false);
|
||||
const { handleApiRequestNotifications } = useNotificationsStore();
|
||||
|
||||
const lostFeatures = [
|
||||
'Billable hours & rates',
|
||||
'Invoicing',
|
||||
'Project & task estimates',
|
||||
'Rounding of time entries',
|
||||
'PDF reports & shareable reports',
|
||||
'Team support & access management',
|
||||
];
|
||||
|
||||
async function cancelTrial() {
|
||||
// Note: The organization of this page, the current organization on the server can differ if the user switched organizations in another tab
|
||||
const organizationId = getCurrentOrganizationId();
|
||||
if (processing.value || organizationId === null) {
|
||||
return;
|
||||
}
|
||||
processing.value = true;
|
||||
try {
|
||||
await handleApiRequestNotifications(
|
||||
() => api.cancelTrial(undefined, { params: { organization: organizationId } }),
|
||||
'Your trial has been canceled',
|
||||
'Your trial could not be canceled, please try again',
|
||||
() => {
|
||||
show.value = false;
|
||||
// Reloads the shared billing props of the page, they still contain the trial otherwise
|
||||
router.reload();
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
processing.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogModal :show="show" closeable @close="show = false">
|
||||
<template #title>Cancel trial</template>
|
||||
|
||||
<template #content>
|
||||
<p class="text-sm text-text-secondary">
|
||||
Your organization switches to the Free plan right away. You will lose access to
|
||||
these Professional features:
|
||||
</p>
|
||||
<ul class="mt-4 grid gap-2 sm:grid-cols-2">
|
||||
<li
|
||||
v-for="feature in lostFeatures"
|
||||
:key="feature"
|
||||
class="flex items-center gap-2 text-sm text-text-primary">
|
||||
<XMarkIcon class="h-4 w-4 shrink-0 text-red-500/80" />
|
||||
{{ feature }}
|
||||
</li>
|
||||
</ul>
|
||||
<p class="mt-5 text-sm text-text-secondary">
|
||||
Organizations with more than one member are blocked until you upgrade or remove
|
||||
everyone except the owner.
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<SecondaryButton @click="show = false">Keep trial</SecondaryButton>
|
||||
<DangerButton
|
||||
class="ms-3"
|
||||
data-testid="confirm_cancel_trial"
|
||||
:class="{ 'opacity-25': processing }"
|
||||
:disabled="processing"
|
||||
@click="cancelTrial">
|
||||
Cancel trial
|
||||
</DangerButton>
|
||||
</template>
|
||||
</DialogModal>
|
||||
</template>
|
||||
56
resources/js/Components/Billing/SidebarPlanStatus.vue
Normal file
56
resources/js/Components/Billing/SidebarPlanStatus.vue
Normal file
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { router } from '@inertiajs/vue3';
|
||||
import { SparklesIcon } from '@heroicons/vue/16/solid';
|
||||
import { Button } from '@/packages/ui/src/Buttons';
|
||||
import TrialUpgradeModal from '@/Components/Billing/TrialUpgradeModal.vue';
|
||||
import CancelTrialModal from '@/Components/Billing/CancelTrialModal.vue';
|
||||
import { daysLeftInTrial, isBlocked, isFreePlan, isInTrial } from '@/utils/billing';
|
||||
|
||||
const showTrialUpgradeModal = ref(false);
|
||||
const showCancelTrialModal = ref(false);
|
||||
|
||||
const daysLeftLabel = computed(() => {
|
||||
const days = daysLeftInTrial();
|
||||
return days === 1 ? '1 day left' : `${days} days left`;
|
||||
});
|
||||
|
||||
function openBilling() {
|
||||
router.visit('/billing');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="isInTrial() || (isFreePlan() && !isBlocked())" class="pb-3">
|
||||
<Button
|
||||
v-if="isInTrial()"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
data-testid="sidebar_trial_days_left"
|
||||
class="w-full justify-between rounded-lg px-2.5 text-xs font-normal [&_svg]:size-3.5"
|
||||
@click="showTrialUpgradeModal = true">
|
||||
<span class="flex items-center gap-1.5 font-medium text-text-primary">
|
||||
<SparklesIcon class="h-3.5 w-3.5 text-accent-500 dark:text-accent-300" />
|
||||
Professional trial
|
||||
</span>
|
||||
<span class="text-text-secondary">{{ daysLeftLabel }}</span>
|
||||
</Button>
|
||||
<div
|
||||
v-else-if="isFreePlan() && !isBlocked()"
|
||||
class="flex items-center justify-between gap-2 rounded-lg border border-border-secondary bg-card-background py-1.5 pl-2.5 pr-1.5 text-xs">
|
||||
<span class="font-medium text-text-primary">Free plan</span>
|
||||
<Button
|
||||
size="xs"
|
||||
data-testid="sidebar_upgrade_button"
|
||||
class="h-6 bg-accent-500 px-2.5 font-semibold text-white hover:bg-accent-400"
|
||||
@click="openBilling">
|
||||
Upgrade
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<TrialUpgradeModal
|
||||
v-model:show="showTrialUpgradeModal"
|
||||
@cancel-trial="showCancelTrialModal = true" />
|
||||
<CancelTrialModal v-model:show="showCancelTrialModal" />
|
||||
</div>
|
||||
</template>
|
||||
79
resources/js/Components/Billing/TrialUpgradeModal.vue
Normal file
79
resources/js/Components/Billing/TrialUpgradeModal.vue
Normal file
@@ -0,0 +1,79 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/packages/ui/src/dialog';
|
||||
import { Button } from '@/packages/ui/src/Buttons';
|
||||
import { SparklesIcon } from '@heroicons/vue/16/solid';
|
||||
import { featureIcons } from '@/packages/ui/src/UpgradeModal/featureIcons';
|
||||
import { professionalFeatures, useUpgradeCta } from '@/packages/ui/src/UpgradeModal/useUpgradeCta';
|
||||
import { daysLeftInTrial } from '@/utils/billing';
|
||||
|
||||
const show = defineModel<boolean>('show', { default: false });
|
||||
|
||||
const emit = defineEmits<{ cancelTrial: [] }>();
|
||||
|
||||
const { goToBilling } = useUpgradeCta();
|
||||
|
||||
const daysLeftLabel = computed(() => {
|
||||
const days = daysLeftInTrial();
|
||||
return days === 1 ? '1 day' : `${days} days`;
|
||||
});
|
||||
|
||||
function cancelTrial() {
|
||||
show.value = false;
|
||||
emit('cancelTrial');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Dialog v-model:open="show">
|
||||
<DialogContent class="sm:max-w-xl p-0 overflow-hidden">
|
||||
<div class="px-8 pt-8 text-center">
|
||||
<div
|
||||
class="mx-auto inline-flex items-center gap-1.5 rounded-full border border-border-secondary bg-card-background px-3 py-1 text-xs font-medium text-text-primary">
|
||||
<SparklesIcon class="h-3.5 w-3.5 text-accent-500 dark:text-accent-300" />
|
||||
{{ daysLeftLabel }} left in your trial
|
||||
</div>
|
||||
<DialogTitle class="mt-4 text-xl font-semibold tracking-tight text-text-primary">
|
||||
Keep solidtime Professional
|
||||
</DialogTitle>
|
||||
<DialogDescription class="mt-1.5 text-sm text-text-secondary">
|
||||
Upgrade now to keep these features after your trial ends.
|
||||
</DialogDescription>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-x-6 gap-y-4 px-8 pt-8">
|
||||
<div v-for="item in professionalFeatures" :key="item.key" class="flex gap-3">
|
||||
<div
|
||||
class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-border-tertiary bg-card-background">
|
||||
<component
|
||||
:is="featureIcons[item.key]"
|
||||
class="h-3.5 w-3.5 text-text-secondary" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-medium text-text-primary">{{ item.title }}</p>
|
||||
<p class="mt-0.5 text-xs leading-relaxed text-text-tertiary">
|
||||
{{ item.description }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mx-auto flex max-w-xs flex-col items-center gap-3 px-8 pt-8 pb-6">
|
||||
<Button
|
||||
data-testid="trial_upgrade_modal_cta"
|
||||
class="w-full bg-accent-500 px-4 font-semibold text-white shadow-[0_0_24px_-6px] shadow-accent-500/60 hover:bg-accent-400"
|
||||
@click="goToBilling">
|
||||
Upgrade to Professional
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
data-testid="trial_upgrade_modal_cancel_trial"
|
||||
class="font-normal text-text-tertiary hover:text-text-primary"
|
||||
@click="cancelTrial">
|
||||
Cancel trial
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user