mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-08-08 08:12:17 +01:00
Compare commits
3 Commits
v0.11.3
...
feature/de
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42fa680bf6 | ||
|
|
b647a6af71 | ||
|
|
f223bd23c4 |
10
.env.ci
10
.env.ci
@@ -34,12 +34,7 @@ SESSION_DRIVER=database
|
||||
SESSION_LIFETIME=120
|
||||
|
||||
# Mail
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=localhost
|
||||
MAIL_PORT=1025
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=null
|
||||
MAIL_MAILER=log
|
||||
MAIL_FROM_ADDRESS="no-reply@solidtime.test"
|
||||
MAIL_FROM_NAME="solidtime"
|
||||
MAIL_REPLY_TO_ADDRESS="hello@solidtime.test"
|
||||
@@ -61,6 +56,3 @@ TELESCOPE_ENABLED=false
|
||||
|
||||
# Services
|
||||
GOTENBERG_URL=http://0.0.0.0:3000
|
||||
|
||||
# Octane
|
||||
OCTANE_SERVER=frankenphp
|
||||
|
||||
@@ -80,7 +80,8 @@ GOTENBERG_URL=http://gotenberg:3000
|
||||
# Local setup
|
||||
NGINX_HOST_NAME=solidtime.test
|
||||
NETWORK_NAME=reverse-proxy-docker-traefik_routing
|
||||
FORWARD_DB_PORT=54329
|
||||
FORWARD_DB_PORT=5432
|
||||
FORWARD_WEB_PORT=8083
|
||||
VITE_HOST_NAME=vite.solidtime.test
|
||||
VITE_APP_NAME="${APP_NAME}"
|
||||
#SAIL_XDEBUG_MODE=develop,debug,coverage
|
||||
|
||||
15
.github/PULL_REQUEST_TEMPLATE.md
vendored
15
.github/PULL_REQUEST_TEMPLATE.md
vendored
@@ -1,11 +1,8 @@
|
||||
## What does this PR do?
|
||||
<!--
|
||||
This project is early stage. The structure and APIs are still subject to change and not stable.
|
||||
Therefore, we do not currently accept any contributions, unless you are a member of the team.
|
||||
|
||||
<!-- Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. -->
|
||||
As soon as we feel comfortable enough that the application structure is stable enough, we will open up the project for contributions.
|
||||
|
||||
- Fixes #XXXX (GitHub issue number)
|
||||
|
||||
## Checklist (DO NOT REMOVE)
|
||||
|
||||
- [ ] I read the [contributing guide](https://github.com/solidtime-io/solidtime/blob/main/CONTRIBUTING.md)
|
||||
- [ ] I signed the [Contributor License Agreement](https://cla-assistant.io/solidtime-io/solidtime).
|
||||
- [ ] I commented my code, particularly in hard-to-understand areas
|
||||
We do accept contributions in the [documentation repository](https://github.com/solidtime-io/docs) f.e. to add new self-hosting guides.
|
||||
-->
|
||||
|
||||
216
.github/workflows/build-onpremise.yml
vendored
216
.github/workflows/build-onpremise.yml
vendored
@@ -1,216 +0,0 @@
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- develop
|
||||
tags:
|
||||
- '*'
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/build-onpremise.yml'
|
||||
- 'docker/prod/**'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
DOCKER_REPO: registry.on-premise.solidtime.io/solidtime/solidtime
|
||||
|
||||
name: Build - On Premise
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- runs-on: "ubuntu-24.04-arm"
|
||||
platform: "linux/arm64"
|
||||
- runs-on: "ubuntu-24.04"
|
||||
platform: "linux/amd64"
|
||||
runs-on: ${{ matrix.runs-on }}
|
||||
timeout-minutes: 90
|
||||
|
||||
steps:
|
||||
- name: "Check out code"
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
|
||||
|
||||
- name: "Get build"
|
||||
id: release-build
|
||||
run: echo "build=$(git rev-parse --short=8 HEAD)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: "Get Previous tag (normal push)"
|
||||
id: previoustag
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
|
||||
uses: "WyriHaximus/github-action-get-previous-tag@v1"
|
||||
with:
|
||||
prefix: "v"
|
||||
|
||||
- name: "Get version"
|
||||
id: release-version
|
||||
run: |
|
||||
if ${{ !startsWith(github.ref, 'refs/tags/v') }}; then
|
||||
if ${{ startsWith(steps.previoustag.outputs.tag, 'v') }}; then
|
||||
version=$(echo "${{ steps.previoustag.outputs.tag }}" | cut -c 2-)
|
||||
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "ERROR: No previous tag found";
|
||||
exit 1;
|
||||
fi
|
||||
else
|
||||
version=$(echo "${{ github.ref }}" | cut -c 12-)
|
||||
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: "Copy .env template for production"
|
||||
run: |
|
||||
cp .env.production .env
|
||||
rm .env.production .env.ci .env.example
|
||||
|
||||
- name: "Add version to .env"
|
||||
run: sed -i 's/APP_VERSION=0.0.0/APP_VERSION=${{ steps.release-version.outputs.app_version }}/g' .env
|
||||
|
||||
- name: "Add build to .env"
|
||||
run: sed -i 's/APP_BUILD=0/APP_BUILD=${{ steps.release-build.outputs.build }}/g' .env
|
||||
|
||||
- name: "Output .env"
|
||||
run: cat .env
|
||||
|
||||
- name: "Setup PHP with PECL extension"
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.3'
|
||||
extensions: mbstring, dom, fileinfo, pgsql
|
||||
|
||||
- name: "Install dependencies"
|
||||
run: composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
|
||||
if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit
|
||||
|
||||
- name: "Use Node.js"
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: "Checkout invoicing extension"
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: solidtime-io/extension-invoicing
|
||||
path: extensions/Invoicing
|
||||
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_INVOICING_EXTENSION }}
|
||||
|
||||
- name: "Install composer dependencies in invoicing extension"
|
||||
run: cd extensions/Invoicing && composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
|
||||
|
||||
- name: "Install npm dependencies in invoicing extension"
|
||||
run: cd extensions/Invoicing && npm ci
|
||||
|
||||
- name: "Activate invoicing extension"
|
||||
run: php artisan module:enable Invoicing
|
||||
|
||||
- name: "Install npm dependencies"
|
||||
run: npm ci
|
||||
|
||||
- name: "Build"
|
||||
run: npm run build
|
||||
|
||||
- name: "Prepare"
|
||||
run: |
|
||||
platform=${{ matrix.platform }}
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
|
||||
- name: "Docker meta"
|
||||
id: "meta"
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
${{ env.DOCKER_REPO }}
|
||||
|
||||
- name: "Login to solidtime OnPremise Registry"
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: registry.on-premise.solidtime.io
|
||||
username: ${{ secrets.ONPREMISE_USERNAME }}
|
||||
password: ${{ secrets.ONPREMISE_TOKEN }}
|
||||
|
||||
- name: "Set up QEMU"
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: "Set up Docker Buildx"
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: "Build and push by digest"
|
||||
id: build
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: docker/prod/Dockerfile
|
||||
build-args: |
|
||||
DOCKER_FILES_BASE_PATH=docker/prod/
|
||||
platforms: ${{ matrix.platform }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
outputs: type=image,"name=${{ env.DOCKER_REPO }}",push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: "Export digest"
|
||||
run: |
|
||||
mkdir -p ${{ runner.temp }}/digests
|
||||
digest="${{ steps.build.outputs.digest }}"
|
||||
touch "${{ runner.temp }}/digests/${digest#sha256:}"
|
||||
|
||||
- name: "Upload digest"
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: digests-${{ env.PLATFORM_PAIR }}
|
||||
path: ${{ runner.temp }}/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
merge:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
needs:
|
||||
- build
|
||||
steps:
|
||||
- name: "Download digests"
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: ${{ runner.temp }}/digests
|
||||
pattern: digests-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: "Login to solidtime OnPremise Registry"
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: registry.on-premise.solidtime.io
|
||||
username: ${{ secrets.ONPREMISE_USERNAME }}
|
||||
password: ${{ secrets.ONPREMISE_TOKEN }}
|
||||
|
||||
- name: "Set up Docker Buildx"
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: "Docker meta"
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
${{ env.DOCKER_REPO }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=pr
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
|
||||
- name: "Create manifest list and push"
|
||||
working-directory: ${{ runner.temp }}/digests
|
||||
run: |
|
||||
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
||||
$(printf '${{ env.DOCKER_REPO }}@sha256:%s ' *)
|
||||
|
||||
- name: "Inspect image"
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.DOCKER_REPO }}:${{ steps.meta.outputs.version }}
|
||||
23
.github/workflows/npm-format-check.yml
vendored
23
.github/workflows/npm-format-check.yml
vendored
@@ -1,23 +0,0 @@
|
||||
name: NPM Format Check
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
format-check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- name: "Checkout code"
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: "Use Node.js"
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: "Install npm dependencies"
|
||||
run: npm ci
|
||||
|
||||
- name: "Check code formatting"
|
||||
run: npm run format:check
|
||||
63
.github/workflows/playwright.yml
vendored
63
.github/workflows/playwright.yml
vendored
@@ -6,18 +6,10 @@ jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shardIndex: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
shardTotal: [8]
|
||||
|
||||
services:
|
||||
mailpit:
|
||||
image: 'axllent/mailpit:latest'
|
||||
ports:
|
||||
- 1025:1025
|
||||
- 8025:8025
|
||||
pgsql_test:
|
||||
image: postgres:15
|
||||
env:
|
||||
@@ -65,63 +57,22 @@ jobs:
|
||||
- name: "Build Frontend"
|
||||
run: npm run build
|
||||
|
||||
- name: "Install FrankenPHP"
|
||||
run: |
|
||||
ARCH="$(uname -m)"
|
||||
curl -fsSL "https://github.com/dunglas/frankenphp/releases/latest/download/frankenphp-linux-${ARCH}" -o /usr/local/bin/frankenphp
|
||||
chmod +x /usr/local/bin/frankenphp
|
||||
|
||||
- name: "Run Laravel Octane Server"
|
||||
run: php artisan octane:start --server=frankenphp --host=127.0.0.1 --port=8000 --workers=4 --max-requests=500 > /dev/null 2>&1 &
|
||||
env:
|
||||
OCTANE_SERVER: frankenphp
|
||||
- name: "Run Laravel Server"
|
||||
run: php artisan serve > /dev/null 2>&1 &
|
||||
|
||||
- name: "Install Playwright Browsers"
|
||||
run: npx playwright install --with-deps
|
||||
|
||||
- name: "Run Playwright tests"
|
||||
run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
|
||||
run: npx playwright test
|
||||
env:
|
||||
PLAYWRIGHT_BASE_URL: 'http://127.0.0.1:8000'
|
||||
MAILPIT_BASE_URL: 'http://localhost:8025'
|
||||
|
||||
- name: "Upload blob report"
|
||||
- name: "Upload test results"
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: blob-report-${{ matrix.shardIndex }}
|
||||
path: blob-report/
|
||||
retention-days: 7
|
||||
|
||||
merge-reports:
|
||||
if: always()
|
||||
needs: [test]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: "Checkout code"
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: "Setup node"
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: "Install dependencies"
|
||||
run: npm ci
|
||||
|
||||
- name: "Download blob reports"
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: all-blob-reports
|
||||
pattern: blob-report-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: "Merge reports"
|
||||
run: npx playwright merge-reports --reporter html ./all-blob-reports
|
||||
|
||||
- name: "Upload merged HTML report"
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: playwright-report
|
||||
path: playwright-report/
|
||||
name: test-results
|
||||
path: test-results/
|
||||
retention-days: 30
|
||||
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
# Ignore build outputs
|
||||
node_modules/
|
||||
vendor/
|
||||
storage/
|
||||
bootstrap/cache/
|
||||
public/build/
|
||||
public/hot/
|
||||
|
||||
# Ignore lock files
|
||||
package-lock.json
|
||||
composer.lock
|
||||
|
||||
# Ignore generated files
|
||||
*.min.js
|
||||
*.min.css
|
||||
|
||||
# Ignore test results
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Ignore IDE files
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# Ignore OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -3,6 +3,5 @@
|
||||
"tabWidth": 4,
|
||||
"singleQuote": true,
|
||||
"bracketSameLine": true,
|
||||
"quoteProps": "preserve",
|
||||
"printWidth": 100
|
||||
"quoteProps": "preserve"
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
# Contributing to solidtime
|
||||
|
||||
Contributions are greatly apprecited, please make sure to read the rules and vision for solidtime before contributing.
|
||||
|
||||
## Rules
|
||||
|
||||
### 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.
|
||||
|
||||
### Only work on approved issues
|
||||
|
||||
To respect your time and help us manage contributions effectively, please open an issue or start a discussion and wait for approval before submitting a pull request (PR). This does not apply to tiny fixes or changes however, please keep in mind that we might not merge PRs for various reasons.
|
||||
|
||||
### Contributor License Agreement
|
||||
|
||||
You'll also notice that we’ve set up a [Contributor License Agreement (CLA)](https://cla-assistant.io/solidtime-io/solidtime), which must be signed before any PR can be merged. Don’t worry - the process is quick and only takes a few clicks.
|
||||
|
||||
We want to be transparent about why we require the CLA and what it means for your contributions and the codebase. That’s why we’ve written a few paragraphs below outlining our plans and vision for solidtime in the **Vision** part of this document.
|
||||
|
||||
### Prevent Duplicate Work
|
||||
|
||||
Before you submit a new PR, make sure that none exists already. If you plan to work on an issue, make sure to let us and others know by commenting on the issue/discussion.
|
||||
|
||||
### Give context
|
||||
|
||||
Tell us what you thinking was behind the decisions you made while drafting the PR. Treat the PR itself as documentation for everyone who wants to go back and understand why certain decisions were made.
|
||||
|
||||
### Summarize your PR
|
||||
|
||||
Please make sure to include a short summary at the top of your PR to make it easy for us to quickly check what the PR is about, without looking at the code changes.
|
||||
|
||||
### Use Github Keywords and Auto-Link Issues
|
||||
|
||||
Use phrases like "Closes #123" or "Fixes #123" in the PR description to link the PR with the issue that you are adressing.
|
||||
|
||||
### Mention what you tested and how
|
||||
|
||||
Explain how you tested and validated the implementation.
|
||||
|
||||
### Keep Naming consistent
|
||||
|
||||
Look at existing code patterns and use naming conventions that already exist in the code base.
|
||||
|
||||
### Testing
|
||||
|
||||
We have an exhaustive test-suite of PHPUnit (Backend) and Playwright (Frontend) testing. Whereever applicable please make sure to write add tests to the codebase.
|
||||
|
||||
### Linting & Formatting
|
||||
|
||||
Make sure to run linting and formatting commands before you commit the changes.
|
||||
|
||||
For backend changes:
|
||||
|
||||
```
|
||||
composer fix
|
||||
composer analyse
|
||||
```
|
||||
|
||||
For frontend changes:
|
||||
|
||||
```
|
||||
npm run lint:fix
|
||||
npm run format
|
||||
```
|
||||
|
||||
## Vision
|
||||
|
||||
We started solidtime to provide an open infrastructure solution for time tracking—one that empowers teams and individuals to fully own their data, instead of depending on proprietary platforms. We believe infrastructure software should be open, accessible, and built to last. However, competing with established market leaders in this space requires long-term financial sustainability.
|
||||
|
||||
solidtime is licensed under the AGPL, which we believe is the best available license to strike a balance between openness and financial viability. The AGPL gives us, as the copyright holders, certain exclusive rights that we plan to leverage to fund development. To ensure we retain those rights across the entire codebase, we've put a CLA in place that contributors must sign before submitting code.
|
||||
|
||||
One of solidtime’s key advantages is that it's built to be self-hostable. This makes it a great solution for organizations like governments, healthcare providers, and enterprises that are required to keep data on their own infrastructure due to regulations or internal policies. These organizations may need custom licenses, integrations, or modifications that aren't suitable for the open-source version. To support them, we offer relicensed versions of solidtime along with support plans.
|
||||
|
||||
We’ll also provide proprietary extensions for solidtime. These will be available to enterprise customers with support plans, but also to individual users or teams who don’t need support, at much more accessible price points. For companies running solidtime on their own infrastructure, this is the easiest way to support the project while gaining additional functionality. While we plan to make it easier to build custom extensions in the future, our current APIs are still highly experimental.
|
||||
|
||||
Finally - and perhaps most importantly - we offer a hosted SaaS version called solidtime Cloud, for users who can’t or don’t want to run the software themselves. This version includes proprietary extensions, always runs the latest commit, and includes monitoring and billing features available exclusively on this hosted instance. We expect solidtime Cloud to play a critical role in funding the project long-term.
|
||||
|
||||
Having full control over the source code’s licensing also gives us the ability to change the license of the main project in the future. That said, we have no plans to do so and would only consider it in extreme cases - for example, if a malicious actor were to directly compete with our hosted service in a way that threatens the sustainability of the project, the legal interpretation of AGPL changes in a way that would make it unreasonable to use for certain companies, or a new similar license gains wide-spread adoption. Regardless, solidtime will always remain free to self-host for individuals and companies who use it as part of their work, and all previous releases will remain licensed under AGPL.
|
||||
|
||||
If you are using the open-source version of solidtime and want to support us, the best way to do so is to spread the word.
|
||||
@@ -35,9 +35,10 @@ If you have a **feature request**, please [**create a discussion**](https://gith
|
||||
|
||||
## Contributing
|
||||
|
||||
Please open an issue or start a discussion and wait for approval before submitting a pull request. This does not apply to tiny fixes or changes however, please keep in mind that we might not merge PRs for various reasons.
|
||||
This project is in a very early stage. The structure and APIs are still subject to change and not stable.
|
||||
Therefore, we do not currently accept any contributions, unless you are a member of the team.
|
||||
|
||||
Please read the [CONTRIBUTING.md](./CONTRIBUTING.md) before sumbitting a Pull Request.
|
||||
As soon as we feel comfortable enough that the application structure is stable enough, we will open up the project for contributions.
|
||||
|
||||
We do accept contributions in the [documentation repository](https://github.com/solidtime-io/docs) f.e. to add new self-hosting guides.
|
||||
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Console\Commands\Auth;
|
||||
|
||||
use App\Mail\AuthApiTokenExpirationReminderMail;
|
||||
use App\Mail\AuthApiTokenExpiredMail;
|
||||
use App\Models\Passport\Token;
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
class AuthSendReminderForExpiringApiTokensCommand extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'auth:send-mails-expiring-api-tokens '.
|
||||
' { --dry-run : Do not actually send emails or save anything to the database, just output what would happen }';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Sends emails about expiring API tokens, one week before and when they expired.';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
if ($dryRun) {
|
||||
$this->comment('Running in dry-run mode. No emails will be sent and nothing will be saved to the database.');
|
||||
}
|
||||
|
||||
$this->comment('Sending reminder emails about expiring API tokens...');
|
||||
$sentMails = 0;
|
||||
Token::query()
|
||||
->where('expires_at', '<=', Carbon::now()->addDays(7))
|
||||
->whereNull('reminder_sent_at')
|
||||
->with([
|
||||
'client',
|
||||
'user',
|
||||
])
|
||||
->whereHas('user', function (Builder $query): void {
|
||||
/** @var Builder<User> $query */
|
||||
$query->where('is_placeholder', '=', false);
|
||||
})
|
||||
->isApiToken(true)
|
||||
->orderBy('created_at', 'asc')
|
||||
->chunk(500, function (Collection $tokens) use ($dryRun, &$sentMails): void {
|
||||
/** @var Collection<int, Token> $tokens */
|
||||
foreach ($tokens as $token) {
|
||||
$user = $token->user;
|
||||
$this->info('Start sending email to user "'.$user->email.'" ('.$user->getKey().') reminding about API token '.$token->getKey());
|
||||
$sentMails++;
|
||||
if (! $dryRun) {
|
||||
Mail::to($user->email)
|
||||
->queue(new AuthApiTokenExpirationReminderMail($token, $user));
|
||||
$token->reminder_sent_at = Carbon::now();
|
||||
$token->save();
|
||||
}
|
||||
}
|
||||
});
|
||||
$this->comment('Finished sending '.$sentMails.' expiring API token emails...');
|
||||
|
||||
$this->comment('Sent emails about expired API tokens');
|
||||
$sentMails = 0;
|
||||
Token::query()
|
||||
->where('expires_at', '<=', Carbon::now())
|
||||
->whereNull('expired_info_sent_at')
|
||||
->with([
|
||||
'client',
|
||||
'user',
|
||||
])
|
||||
->whereHas('user', function (Builder $query): void {
|
||||
/** @var Builder<User> $query */
|
||||
$query->where('is_placeholder', '=', false);
|
||||
})
|
||||
->isApiToken(true)
|
||||
->orderBy('created_at', 'asc')
|
||||
->chunk(500, function (Collection $tokens) use ($dryRun, &$sentMails): void {
|
||||
/** @var Collection<int, Token> $tokens */
|
||||
foreach ($tokens as $token) {
|
||||
$user = $token->user;
|
||||
$this->info('Start sending email to user "'.$user->email.'" ('.$user->getKey().') about expired API token '.$token->getKey());
|
||||
$sentMails++;
|
||||
if (! $dryRun) {
|
||||
Mail::to($user->email)
|
||||
->queue(new AuthApiTokenExpiredMail($token, $user));
|
||||
$token->expired_info_sent_at = Carbon::now();
|
||||
$token->save();
|
||||
}
|
||||
}
|
||||
});
|
||||
$this->comment('Finished sending '.$sentMails.' expired API token emails...');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -18,31 +18,13 @@ class Kernel extends ConsoleKernel
|
||||
->when(fn (): bool => config('scheduling.tasks.time_entry_send_still_running_mails'))
|
||||
->everyTenMinutes();
|
||||
|
||||
$schedule->command('auth:send-mails-expiring-api-tokens')
|
||||
->when(fn (): bool => config('scheduling.tasks.auth_send_mails_expiring_api_tokens'))
|
||||
->everyTenMinutes();
|
||||
$schedule->command('self-host:check-for-update')
|
||||
->when(fn (): bool => config('scheduling.tasks.self_hosting_check_for_update'))
|
||||
->twiceDaily();
|
||||
|
||||
if (config('app.key') && (config('scheduling.tasks.self_hosting_check_for_update') || config('scheduling.tasks.self_hosting_telemetry'))) {
|
||||
// Convert string to a stable integer for seeding
|
||||
/** @var int $seed Take the first 8 hex chars → 32-bit int */
|
||||
$seed = hexdec(substr(hash('md5', config('app.key')), 0, 8));
|
||||
$seed = abs($seed); // Ensure it's positive
|
||||
mt_srand($seed);
|
||||
$firstHour = mt_rand(0, 23);
|
||||
$secondHour = ($firstHour + 12) % 24;
|
||||
$minuteOffset = mt_rand(0, 59);
|
||||
mt_srand(null); // Reset the random number generator
|
||||
|
||||
if (config('scheduling.tasks.self_hosting_check_for_update')) {
|
||||
$schedule->command('self-host:check-for-update')
|
||||
->twiceDailyAt($firstHour, $secondHour, $minuteOffset);
|
||||
}
|
||||
|
||||
if (config('scheduling.tasks.self_hosting_telemetry')) {
|
||||
$schedule->command('self-host:telemetry')
|
||||
->twiceDailyAt($firstHour, $secondHour, $minuteOffset);
|
||||
}
|
||||
}
|
||||
$schedule->command('self-host:telemetry')
|
||||
->when(fn (): bool => config('scheduling.tasks.self_hosting_telemetry'))
|
||||
->twiceDaily();
|
||||
|
||||
$schedule->command('self-host:database-consistency')
|
||||
->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency'))
|
||||
|
||||
@@ -20,7 +20,6 @@ enum TimeEntryAggregationType: string
|
||||
case Client = 'client';
|
||||
case Billable = 'billable';
|
||||
case Description = 'description';
|
||||
case Tag = 'tag';
|
||||
|
||||
public static function fromInterval(TimeEntryAggregationTypeInterval $timeEntryAggregationTypeInterval): TimeEntryAggregationType
|
||||
{
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
|
||||
|
||||
enum TimeEntryRoundingType: string
|
||||
{
|
||||
use LaravelEnumHelper;
|
||||
|
||||
case Up = 'up';
|
||||
case Down = 'down';
|
||||
case Nearest = 'nearest';
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Exceptions\Api;
|
||||
|
||||
class OverlappingTimeEntryApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'overlapping_time_entry';
|
||||
}
|
||||
@@ -15,7 +15,6 @@ use Filament\Resources\Resource;
|
||||
use Filament\Tables\Actions\Action;
|
||||
use Filament\Tables\Actions\BulkAction;
|
||||
use Filament\Tables\Actions\DeleteAction;
|
||||
use Filament\Tables\Actions\DeleteBulkAction;
|
||||
use Filament\Tables\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
@@ -76,8 +75,7 @@ class FailedJobResource extends Resource
|
||||
->filters([])
|
||||
->bulkActions([
|
||||
BulkAction::make('retry')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->label('Retry selected')
|
||||
->label('Retry')
|
||||
->requiresConfirmation()
|
||||
->action(function (Collection $records): void {
|
||||
/** @var FailedJob $record */
|
||||
@@ -89,13 +87,11 @@ class FailedJobResource extends Resource
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
DeleteBulkAction::make(),
|
||||
])
|
||||
->actions([
|
||||
DeleteAction::make(),
|
||||
ViewAction::make(),
|
||||
DeleteAction::make('Delete'),
|
||||
ViewAction::make('View'),
|
||||
Action::make('retry')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->label('Retry')
|
||||
->requiresConfirmation()
|
||||
->action(function (FailedJob $record): void {
|
||||
@@ -113,6 +109,7 @@ class FailedJobResource extends Resource
|
||||
return [
|
||||
'index' => ListFailedJobs::route('/'),
|
||||
'view' => ViewFailedJobs::route('/{record}'),
|
||||
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ namespace App\Filament\Resources\FailedJobResource\Pages;
|
||||
|
||||
use App\Filament\Resources\FailedJobResource;
|
||||
use App\Models\FailedJob;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Actions\Action;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
|
||||
@@ -19,8 +19,7 @@ class ListFailedJobs extends ListRecords
|
||||
{
|
||||
return [
|
||||
Action::make('retry_all')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->label('Retry all')
|
||||
->label('Retry all failed Jobs')
|
||||
->requiresConfirmation()
|
||||
->action(function (): void {
|
||||
Artisan::call('queue:retry all');
|
||||
@@ -31,8 +30,7 @@ class ListFailedJobs extends ListRecords
|
||||
}),
|
||||
|
||||
Action::make('delete_all')
|
||||
->icon('heroicon-o-trash')
|
||||
->label('Delete all')
|
||||
->label('Delete all failed Jobs')
|
||||
->requiresConfirmation()
|
||||
->color('danger')
|
||||
->action(function (): void {
|
||||
|
||||
@@ -5,7 +5,6 @@ declare(strict_types=1);
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Resources\TimeEntryResource\Pages;
|
||||
use App\Models\Member;
|
||||
use App\Models\TimeEntry;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
@@ -17,7 +16,6 @@ use Filament\Tables;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class TimeEntryResource extends Resource
|
||||
{
|
||||
@@ -53,23 +51,15 @@ class TimeEntryResource extends Resource
|
||||
->rules([
|
||||
'after_or_equal:start',
|
||||
]),
|
||||
Select::make('member_id')
|
||||
->relationship(
|
||||
name: 'member',
|
||||
titleAttribute: 'id',
|
||||
modifyQueryUsing: fn (Builder $query) => $query->with(['user', 'organization'])
|
||||
)
|
||||
->getOptionLabelFromRecordUsing(fn (Member $record): string => $record->user->email.' ('.$record->organization->name.')')
|
||||
->searchable()
|
||||
Select::make('user_id')
|
||||
->relationship(name: 'user', titleAttribute: 'email')
|
||||
->searchable(['name', 'email'])
|
||||
->required(),
|
||||
Select::make('project_id')
|
||||
->relationship(name: 'project', titleAttribute: 'name')
|
||||
->searchable(['name'])
|
||||
->nullable(),
|
||||
Select::make('task_id')
|
||||
->relationship(name: 'task', titleAttribute: 'name')
|
||||
->searchable(['name'])
|
||||
->nullable(),
|
||||
// TODO
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,28 +5,9 @@ declare(strict_types=1);
|
||||
namespace App\Filament\Resources\TimeEntryResource\Pages;
|
||||
|
||||
use App\Filament\Resources\TimeEntryResource;
|
||||
use App\Models\Member;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTimeEntry extends CreateRecord
|
||||
{
|
||||
protected static string $resource = TimeEntryResource::class;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
if (isset($data['member_id'])) {
|
||||
/** @var Member|null $member */
|
||||
$member = Member::query()->find($data['member_id']);
|
||||
if ($member !== null) {
|
||||
$data['user_id'] = $member->user_id;
|
||||
$data['organization_id'] = $member->organization_id;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ declare(strict_types=1);
|
||||
namespace App\Filament\Resources\TimeEntryResource\Pages;
|
||||
|
||||
use App\Filament\Resources\TimeEntryResource;
|
||||
use App\Models\Member;
|
||||
use Filament\Actions;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
@@ -20,22 +19,4 @@ class EditTimeEntry extends EditRecord
|
||||
->icon('heroicon-m-trash'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
if (isset($data['member_id'])) {
|
||||
/** @var Member|null $member */
|
||||
$member = Member::query()->find($data['member_id']);
|
||||
if ($member !== null) {
|
||||
$data['user_id'] = $member->user_id;
|
||||
$data['organization_id'] = $member->organization_id;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Filament\Resources;
|
||||
|
||||
use App\Filament\Resources\TokenResource\Pages;
|
||||
use App\Models\Passport\Client;
|
||||
use App\Models\Passport\Token;
|
||||
use Filament\Forms;
|
||||
use Filament\Forms\Form;
|
||||
@@ -105,11 +106,17 @@ class TokenResource extends Resource
|
||||
->queries(
|
||||
true: function (Builder $query) {
|
||||
/** @var Builder<Token> $query */
|
||||
return $query->isApiToken();
|
||||
return $query->whereHas('client', function (Builder $query) {
|
||||
/** @var Builder<Client> $query */
|
||||
return $query->whereJsonContains('grant_types', 'personal_access');
|
||||
});
|
||||
},
|
||||
false: function (Builder $query) {
|
||||
/** @var Builder<Token> $query */
|
||||
return $query->isApiToken(false);
|
||||
return $query->whereHas('client', function (Builder $query) {
|
||||
/** @var Builder<Client> $query */
|
||||
return $query->whereJsonDoesntContain('grant_types', 'personal_access');
|
||||
});
|
||||
},
|
||||
blank: function (Builder $query) {
|
||||
/** @var Builder<Token> $query */
|
||||
|
||||
@@ -35,7 +35,6 @@ class ApiTokenController extends Controller
|
||||
/** @var Builder<Client> $query */
|
||||
$query->whereJsonContains('grant_types', 'personal_access');
|
||||
})
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
|
||||
return new ApiTokenCollection($tokens);
|
||||
|
||||
@@ -14,8 +14,6 @@ use Illuminate\Http\JsonResponse;
|
||||
class ChartController extends Controller
|
||||
{
|
||||
/**
|
||||
* Get chart data for the weekly project overview.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId weeklyProjectOverview
|
||||
@@ -33,8 +31,6 @@ class ChartController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for the latest tasks.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId latestTasks
|
||||
@@ -52,8 +48,6 @@ class ChartController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for the last seven days.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId lastSevenDays
|
||||
@@ -71,8 +65,6 @@ class ChartController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for the latest team activity.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId latestTeamActivity
|
||||
@@ -89,8 +81,6 @@ class ChartController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for daily tracked hours.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId dailyTrackedHours
|
||||
@@ -102,14 +92,12 @@ class ChartController extends Controller
|
||||
$this->checkPermission($organization, 'charts:view:own');
|
||||
$user = $this->user();
|
||||
|
||||
$dailyTrackedHours = $dashboardService->getDailyTrackedHours($user, $organization, 100);
|
||||
$dailyTrackedHours = $dashboardService->getDailyTrackedHours($user, $organization, 60);
|
||||
|
||||
return response()->json($dailyTrackedHours);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for total weekly time.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId totalWeeklyTime
|
||||
@@ -127,8 +115,6 @@ class ChartController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for total weekly billable time.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId totalWeeklyBillableTime
|
||||
@@ -146,8 +132,6 @@ class ChartController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for total weekly billable amount.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId totalWeeklyBillableAmount
|
||||
@@ -170,8 +154,6 @@ class ChartController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart data for weekly history.
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*
|
||||
* @operationId weeklyHistory
|
||||
|
||||
@@ -38,17 +38,11 @@ class ClientController extends Controller
|
||||
public function index(Organization $organization, ClientIndexRequest $request): ClientCollection
|
||||
{
|
||||
$this->checkPermission($organization, 'clients:view');
|
||||
$canViewAllClients = $this->hasPermission($organization, 'clients:view:all');
|
||||
$user = $this->user();
|
||||
|
||||
$clientsQuery = Client::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->orderBy('created_at', 'desc');
|
||||
|
||||
if (! $canViewAllClients) {
|
||||
$clientsQuery->visibleByEmployee($user);
|
||||
}
|
||||
|
||||
$filterArchived = $request->getFilterArchived();
|
||||
if ($filterArchived === 'true') {
|
||||
$clientsQuery->whereNotNull('archived_at');
|
||||
|
||||
@@ -41,7 +41,6 @@ class InvitationController extends Controller
|
||||
$this->checkPermission($organization, 'invitations:view');
|
||||
|
||||
$invitations = $organization->teamInvitations()
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(config('app.pagination_per_page_default'));
|
||||
|
||||
return InvitationCollection::make($invitations);
|
||||
|
||||
@@ -60,7 +60,6 @@ class MemberController extends Controller
|
||||
$members = Member::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->with(['user'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(config('app.pagination_per_page_default'));
|
||||
|
||||
return MemberCollection::make($members);
|
||||
|
||||
@@ -46,9 +46,6 @@ class OrganizationController extends Controller
|
||||
if ($request->getEmployeesCanSeeBillableRates() !== null) {
|
||||
$organization->employees_can_see_billable_rates = $request->getEmployeesCanSeeBillableRates();
|
||||
}
|
||||
if ($request->getEmployeesCanManageTasks() !== null) {
|
||||
$organization->employees_can_manage_tasks = $request->getEmployeesCanManageTasks();
|
||||
}
|
||||
if ($request->getNumberFormat() !== null) {
|
||||
$organization->number_format = $request->getNumberFormat();
|
||||
}
|
||||
@@ -64,9 +61,6 @@ class OrganizationController extends Controller
|
||||
if ($request->getTimeFormat() !== null) {
|
||||
$organization->time_format = $request->getTimeFormat();
|
||||
}
|
||||
if ($request->getPreventOverlappingTimeEntries() !== null) {
|
||||
$organization->prevent_overlapping_time_entries = $request->getPreventOverlappingTimeEntries();
|
||||
}
|
||||
$hasBillableRate = $request->has('billable_rate');
|
||||
if ($hasBillableRate) {
|
||||
$oldBillableRate = $organization->billable_rate;
|
||||
|
||||
@@ -60,9 +60,7 @@ class ProjectController extends Controller
|
||||
$projectsQuery->whereNull('archived_at');
|
||||
}
|
||||
|
||||
$projects = $projectsQuery
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(config('app.pagination_per_page_default'));
|
||||
$projects = $projectsQuery->paginate(config('app.pagination_per_page_default'));
|
||||
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Exceptions\Api\InactiveUserCanNotBeUsedApiException;
|
||||
use App\Exceptions\Api\UserIsAlreadyMemberOfProjectApiException;
|
||||
use App\Http\Requests\V1\ProjectMember\ProjectMemberIndexRequest;
|
||||
use App\Http\Requests\V1\ProjectMember\ProjectMemberStoreRequest;
|
||||
use App\Http\Requests\V1\ProjectMember\ProjectMemberUpdateRequest;
|
||||
use App\Http\Resources\V1\ProjectMember\ProjectMemberCollection;
|
||||
@@ -42,13 +41,12 @@ class ProjectMemberController extends Controller
|
||||
*
|
||||
* @operationId getProjectMembers
|
||||
*/
|
||||
public function index(Organization $organization, Project $project, ProjectMemberIndexRequest $request): ProjectMemberCollection
|
||||
public function index(Organization $organization, Project $project): ProjectMemberCollection
|
||||
{
|
||||
$this->checkPermission($organization, 'project-members:view', $project);
|
||||
|
||||
$projectMembers = ProjectMember::query()
|
||||
->whereBelongsTo($project, 'project')
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(config('app.pagination_per_page_default'));
|
||||
|
||||
return new ProjectMemberCollection($projectMembers);
|
||||
|
||||
@@ -73,9 +73,7 @@ class ReportController extends Controller
|
||||
false,
|
||||
$report->properties->start,
|
||||
$report->properties->end,
|
||||
true,
|
||||
$report->properties->roundingType,
|
||||
$report->properties->roundingMinutes,
|
||||
true
|
||||
);
|
||||
$historyData = $timeEntryAggregationService->getAggregatedTimeEntriesWithDescriptions(
|
||||
$timeEntriesQuery->clone(),
|
||||
@@ -86,9 +84,7 @@ class ReportController extends Controller
|
||||
true,
|
||||
$report->properties->start,
|
||||
$report->properties->end,
|
||||
true,
|
||||
$report->properties->roundingType,
|
||||
$report->properties->roundingMinutes,
|
||||
true
|
||||
);
|
||||
|
||||
return new DetailedWithDataReportResource($report, $data, $historyData);
|
||||
|
||||
@@ -5,7 +5,6 @@ declare(strict_types=1);
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\Weekday;
|
||||
use App\Http\Requests\V1\Report\ReportIndexRequest;
|
||||
use App\Http\Requests\V1\Report\ReportStoreRequest;
|
||||
use App\Http\Requests\V1\Report\ReportUpdateRequest;
|
||||
use App\Http\Resources\V1\Report\DetailedReportResource;
|
||||
@@ -41,7 +40,7 @@ class ReportController extends Controller
|
||||
*
|
||||
* @operationId getReports
|
||||
*/
|
||||
public function index(Organization $organization, ReportIndexRequest $request): ReportCollection
|
||||
public function index(Organization $organization): ReportCollection
|
||||
{
|
||||
$this->checkPermission($organization, 'reports:view');
|
||||
|
||||
@@ -108,8 +107,6 @@ class ReportController extends Controller
|
||||
}
|
||||
}
|
||||
$properties->timezone = $timezone;
|
||||
$properties->roundingType = $request->getPropertyRoundingType();
|
||||
$properties->roundingMinutes = $request->getPropertyRoundingMinutes();
|
||||
$report->properties = $properties;
|
||||
if ($isPublic) {
|
||||
$report->share_secret = $reportService->generateSecret();
|
||||
@@ -151,9 +148,6 @@ class ReportController extends Controller
|
||||
$report->share_secret = null;
|
||||
$report->public_until = null;
|
||||
}
|
||||
} elseif ($report->is_public && $request->has('public_until')) {
|
||||
// Allow updating expiration date on already-public reports
|
||||
$report->public_until = $request->getPublicUntil();
|
||||
}
|
||||
$report->save();
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ declare(strict_types=1);
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Exceptions\Api\EntityStillInUseApiException;
|
||||
use App\Http\Requests\V1\Tag\TagIndexRequest;
|
||||
use App\Http\Requests\V1\Tag\TagStoreRequest;
|
||||
use App\Http\Requests\V1\Tag\TagUpdateRequest;
|
||||
use App\Http\Resources\V1\Tag\TagCollection;
|
||||
@@ -35,7 +34,7 @@ class TagController extends Controller
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*/
|
||||
public function index(Organization $organization, TagIndexRequest $request): TagCollection
|
||||
public function index(Organization $organization): TagCollection
|
||||
{
|
||||
$this->checkPermission($organization, 'tags:view');
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ use App\Http\Requests\V1\Task\TaskUpdateRequest;
|
||||
use App\Http\Resources\V1\Task\TaskCollection;
|
||||
use App\Http\Resources\V1\Task\TaskResource;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Task;
|
||||
use Illuminate\Auth\Access\AuthorizationException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -28,26 +27,6 @@ class TaskController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check scoped permission and verify user has access to the project
|
||||
*
|
||||
* @throws AuthorizationException
|
||||
*/
|
||||
private function checkScopedPermissionForProject(Organization $organization, Project $project, string $permission): void
|
||||
{
|
||||
$this->checkPermission($organization, $permission);
|
||||
|
||||
$user = $this->user();
|
||||
$hasAccess = Project::query()
|
||||
->where('id', $project->id)
|
||||
->visibleByEmployee($user)
|
||||
->exists();
|
||||
|
||||
if (! $hasAccess) {
|
||||
throw new AuthorizationException('You do not have permission to '.$permission.' in this project.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tasks
|
||||
*
|
||||
@@ -82,9 +61,7 @@ class TaskController extends Controller
|
||||
$query->whereNull('done_at');
|
||||
}
|
||||
|
||||
$tasks = $query
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(config('app.pagination_per_page_default'));
|
||||
$tasks = $query->paginate(config('app.pagination_per_page_default'));
|
||||
|
||||
return new TaskCollection($tasks);
|
||||
}
|
||||
@@ -98,15 +75,7 @@ class TaskController extends Controller
|
||||
*/
|
||||
public function store(Organization $organization, TaskStoreRequest $request): JsonResource
|
||||
{
|
||||
/** @var Project $project */
|
||||
$project = Project::query()->findOrFail($request->input('project_id'));
|
||||
|
||||
if ($this->hasPermission($organization, 'tasks:create:all')) {
|
||||
$this->checkPermission($organization, 'tasks:create:all');
|
||||
} else {
|
||||
$this->checkScopedPermissionForProject($organization, $project, 'tasks:create');
|
||||
}
|
||||
|
||||
$this->checkPermission($organization, 'tasks:create');
|
||||
$task = new Task;
|
||||
$task->name = $request->input('name');
|
||||
$task->project_id = $request->input('project_id');
|
||||
@@ -128,17 +97,7 @@ class TaskController extends Controller
|
||||
*/
|
||||
public function update(Organization $organization, Task $task, TaskUpdateRequest $request): JsonResource
|
||||
{
|
||||
// Check task belongs to organization
|
||||
if ($task->organization_id !== $organization->id) {
|
||||
throw new AuthorizationException('Task does not belong to organization');
|
||||
}
|
||||
|
||||
if ($this->hasPermission($organization, 'tasks:update:all')) {
|
||||
$this->checkPermission($organization, 'tasks:update:all');
|
||||
} else {
|
||||
$this->checkScopedPermissionForProject($organization, $task->project, 'tasks:update');
|
||||
}
|
||||
|
||||
$this->checkPermission($organization, 'tasks:update', $task);
|
||||
$task->name = $request->input('name');
|
||||
if ($this->canAccessPremiumFeatures($organization) && $request->has('estimated_time')) {
|
||||
$task->estimated_time = $request->getEstimatedTime();
|
||||
@@ -160,16 +119,7 @@ class TaskController extends Controller
|
||||
*/
|
||||
public function destroy(Organization $organization, Task $task): JsonResponse
|
||||
{
|
||||
// Check task belongs to organization
|
||||
if ($task->organization_id !== $organization->id) {
|
||||
throw new AuthorizationException('Task does not belong to organization');
|
||||
}
|
||||
|
||||
if ($this->hasPermission($organization, 'tasks:delete:all')) {
|
||||
$this->checkPermission($organization, 'tasks:delete:all');
|
||||
} else {
|
||||
$this->checkScopedPermissionForProject($organization, $task->project, 'tasks:delete');
|
||||
}
|
||||
$this->checkPermission($organization, 'tasks:delete', $task);
|
||||
|
||||
if ($task->timeEntries()->exists()) {
|
||||
throw new EntityStillInUseApiException('task', 'time_entry');
|
||||
|
||||
@@ -7,7 +7,6 @@ namespace App\Http\Controllers\Api\V1;
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\Role;
|
||||
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
|
||||
use App\Exceptions\Api\OverlappingTimeEntryApiException;
|
||||
use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
|
||||
use App\Exceptions\Api\TimeEntryCanNotBeRestartedApiException;
|
||||
use App\Exceptions\Api\TimeEntryStillRunningApiException;
|
||||
@@ -34,7 +33,6 @@ use App\Service\ReportExport\TimeEntriesDetailedExport;
|
||||
use App\Service\ReportExport\TimeEntriesReportExport;
|
||||
use App\Service\TimeEntryAggregationService;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use App\Service\TimeEntryService;
|
||||
use App\Service\TimezoneService;
|
||||
use Gotenberg\Exceptions\GotenbergApiErrored;
|
||||
use Gotenberg\Exceptions\NoOutputFileInResponse;
|
||||
@@ -46,11 +44,9 @@ use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\File;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
@@ -58,43 +54,6 @@ use Spatie\TemporaryDirectory\TemporaryDirectory;
|
||||
|
||||
class TimeEntryController extends Controller
|
||||
{
|
||||
private function assertNoOverlap(Organization $organization, Member $member, \Illuminate\Support\Carbon $start, ?\Illuminate\Support\Carbon $end, ?TimeEntry $exclude = null): void
|
||||
{
|
||||
if (! $organization->prevent_overlapping_time_entries) {
|
||||
return;
|
||||
}
|
||||
|
||||
$query = TimeEntry::query()
|
||||
->where('organization_id', $organization->getKey())
|
||||
->where('user_id', $member->user_id)
|
||||
->when($exclude !== null, function (Builder $q) use ($exclude): void {
|
||||
$q->where('id', '!=', $exclude->getKey());
|
||||
})
|
||||
->where(function (Builder $q) use ($start, $end): void {
|
||||
$q->where(function (Builder $q2) use ($start): void {
|
||||
$q2->where('end', '>', $start)
|
||||
->where('start', '<', $start);
|
||||
});
|
||||
|
||||
if ($end !== null) {
|
||||
$q->orWhere(function (Builder $q4) use ($end): void {
|
||||
$q4->where('start', '<', $end)
|
||||
->where('end', '>', $end);
|
||||
});
|
||||
// Check if the new entry completely surrounds an existing entry
|
||||
$q->orWhere(function (Builder $q6) use ($start, $end): void {
|
||||
$q6->where('start', '>=', $start)
|
||||
->where('end', '<=', $end);
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
if ($query->exists()) {
|
||||
throw new OverlappingTimeEntryApiException;
|
||||
}
|
||||
}
|
||||
|
||||
protected function checkPermission(Organization $organization, string $permission, ?TimeEntry $timeEntry = null): void
|
||||
{
|
||||
parent::checkPermission($organization, $permission);
|
||||
@@ -125,8 +84,7 @@ class TimeEntryController extends Controller
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
}
|
||||
|
||||
$canAccessPremiumFeatures = $this->canAccessPremiumFeatures($organization);
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $member, $canAccessPremiumFeatures);
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $member);
|
||||
|
||||
$totalCount = $timeEntriesQuery->count();
|
||||
|
||||
@@ -180,19 +138,10 @@ class TimeEntryController extends Controller
|
||||
/**
|
||||
* @return Builder<TimeEntry>
|
||||
*/
|
||||
private function getTimeEntriesQuery(Organization $organization, TimeEntryIndexRequest|TimeEntryIndexExportRequest $request, ?Member $member, bool $canAccessPremiumFeatures): Builder
|
||||
private function getTimeEntriesQuery(Organization $organization, TimeEntryIndexRequest|TimeEntryIndexExportRequest $request, ?Member $member): Builder
|
||||
{
|
||||
$select = TimeEntry::SELECT_COLUMNS;
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
if ($roundingType !== null && $roundingMinutes !== null) {
|
||||
$select = array_diff($select, ['start', 'end']);
|
||||
$select[] = DB::raw(app(TimeEntryService::class)->getStartSelectRawForRounding($roundingType, $roundingMinutes).' as start');
|
||||
$select[] = DB::raw(app(TimeEntryService::class)->getEndSelectRawForRounding($roundingType, $roundingMinutes).' as end');
|
||||
}
|
||||
$timeEntriesQuery = TimeEntry::query()
|
||||
->whereBelongsTo($organization, 'organization')
|
||||
->select($select)
|
||||
->orderBy('start', 'desc');
|
||||
|
||||
$filter = new TimeEntryFilter($timeEntriesQuery);
|
||||
@@ -226,19 +175,16 @@ class TimeEntryController extends Controller
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
}
|
||||
$canAccessPremiumFeatures = $this->canAccessPremiumFeatures($organization);
|
||||
$debug = $request->getDebug();
|
||||
$format = $request->getFormatValue();
|
||||
if ($format === ExportFormat::PDF && ! $canAccessPremiumFeatures) {
|
||||
if ($format === ExportFormat::PDF && ! $this->canAccessPremiumFeatures($organization)) {
|
||||
throw new FeatureIsNotAvailableInFreePlanApiException;
|
||||
}
|
||||
$user = $this->user();
|
||||
$timezone = $user->timezone;
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $member, $canAccessPremiumFeatures);
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $member);
|
||||
$timeEntriesQuery->with([
|
||||
'task',
|
||||
'client',
|
||||
@@ -261,9 +207,8 @@ class TimeEntryController extends Controller
|
||||
if ($viewFile === false) {
|
||||
throw new \LogicException('View file not found');
|
||||
}
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
|
||||
$aggregatedData = $timeEntryAggregationService->getAggregatedTimeEntries(
|
||||
$timeEntriesAggregateQuery,
|
||||
$timeEntriesQuery->clone()->reorder()->withOnly([]),
|
||||
null,
|
||||
null,
|
||||
$user->timezone,
|
||||
@@ -271,9 +216,7 @@ class TimeEntryController extends Controller
|
||||
false,
|
||||
null,
|
||||
null,
|
||||
$showBillableRate,
|
||||
$roundingType,
|
||||
$roundingMinutes,
|
||||
$showBillableRate
|
||||
);
|
||||
$html = Blade::render($viewFile, [
|
||||
'timeEntries' => $timeEntriesQuery->get(),
|
||||
@@ -375,15 +318,12 @@ class TimeEntryController extends Controller
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
}
|
||||
$canAccessPremiumFeatures = $this->canAccessPremiumFeatures($organization);
|
||||
$user = $this->user();
|
||||
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
|
||||
|
||||
$group1Type = $request->getGroup();
|
||||
$group2Type = $request->getSubGroup();
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
|
||||
$aggregatedData = $timeEntryAggregationService->getAggregatedTimeEntries(
|
||||
$timeEntriesAggregateQuery,
|
||||
@@ -394,9 +334,7 @@ class TimeEntryController extends Controller
|
||||
$request->getFillGapsInTimeGroups(),
|
||||
$request->getStart(),
|
||||
$request->getEnd(),
|
||||
$showBillableRate,
|
||||
$roundingType,
|
||||
$roundingMinutes
|
||||
$showBillableRate
|
||||
);
|
||||
|
||||
return [
|
||||
@@ -424,7 +362,6 @@ class TimeEntryController extends Controller
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
}
|
||||
$canAccessPremiumFeatures = $this->canAccessPremiumFeatures($organization);
|
||||
$format = $request->getFormatValue();
|
||||
if ($format === ExportFormat::PDF && ! $this->canAccessPremiumFeatures($organization)) {
|
||||
throw new FeatureIsNotAvailableInFreePlanApiException;
|
||||
@@ -436,8 +373,6 @@ class TimeEntryController extends Controller
|
||||
$group = $request->getGroup();
|
||||
$subGroup = $request->getSubGroup();
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
|
||||
$aggregatedData = $timeEntryAggregationService->getAggregatedTimeEntriesWithDescriptions(
|
||||
$timeEntriesAggregateQuery->clone(),
|
||||
@@ -448,9 +383,7 @@ class TimeEntryController extends Controller
|
||||
false,
|
||||
$request->getStart(),
|
||||
$request->getEnd(),
|
||||
$showBillableRate,
|
||||
$roundingType,
|
||||
$roundingMinutes
|
||||
$showBillableRate
|
||||
);
|
||||
$dataHistoryChart = $timeEntryAggregationService->getAggregatedTimeEntries(
|
||||
$timeEntriesAggregateQuery->clone(),
|
||||
@@ -461,9 +394,7 @@ class TimeEntryController extends Controller
|
||||
true,
|
||||
$request->getStart(),
|
||||
$request->getEnd(),
|
||||
$showBillableRate,
|
||||
$roundingType,
|
||||
$roundingMinutes
|
||||
$showBillableRate
|
||||
);
|
||||
$currency = $organization->currency;
|
||||
$timezone = app(TimezoneService::class)->getTimezoneFromUser($this->user());
|
||||
@@ -546,7 +477,7 @@ class TimeEntryController extends Controller
|
||||
/**
|
||||
* @return Builder<TimeEntry>
|
||||
*/
|
||||
private function getTimeEntriesAggregateQuery(Organization $organization, TimeEntryAggregateRequest|TimeEntryAggregateExportRequest|TimeEntryIndexExportRequest $request, ?Member $member): Builder
|
||||
private function getTimeEntriesAggregateQuery(Organization $organization, TimeEntryAggregateRequest|TimeEntryAggregateExportRequest $request, ?Member $member): Builder
|
||||
{
|
||||
$timeEntriesQuery = TimeEntry::query()
|
||||
->whereBelongsTo($organization, 'organization');
|
||||
@@ -588,15 +519,17 @@ class TimeEntryController extends Controller
|
||||
throw new TimeEntryStillRunningApiException;
|
||||
}
|
||||
|
||||
// Overlap check for create
|
||||
$start = Carbon::parse($request->input('start'));
|
||||
$end = $request->input('end') !== null ? Carbon::parse($request->input('end')) : null;
|
||||
$this->assertNoOverlap($organization, $member, $start, $end);
|
||||
|
||||
$project = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id')) : null;
|
||||
$client = $project?->client;
|
||||
$task = $request->input('task_id') !== null ? $project->tasks()->findOrFail((string) $request->input('task_id')) : null;
|
||||
|
||||
if ($project !== null) {
|
||||
RecalculateSpentTimeForProject::dispatch($project);
|
||||
}
|
||||
if ($task !== null) {
|
||||
RecalculateSpentTimeForTask::dispatch($task);
|
||||
}
|
||||
|
||||
$timeEntry = new TimeEntry;
|
||||
$timeEntry->fill($request->validated());
|
||||
$timeEntry->client()->associate($client);
|
||||
@@ -606,13 +539,6 @@ class TimeEntryController extends Controller
|
||||
$timeEntry->setComputedAttributeValue('billable_rate');
|
||||
$timeEntry->save();
|
||||
|
||||
if ($project !== null) {
|
||||
RecalculateSpentTimeForProject::dispatch($project);
|
||||
}
|
||||
if ($task !== null) {
|
||||
RecalculateSpentTimeForTask::dispatch($task);
|
||||
}
|
||||
|
||||
return new TimeEntryResource($timeEntry);
|
||||
}
|
||||
|
||||
@@ -637,13 +563,6 @@ class TimeEntryController extends Controller
|
||||
throw new TimeEntryCanNotBeRestartedApiException;
|
||||
}
|
||||
|
||||
// Overlap check for update (exclude current)
|
||||
/** @var Member $effectiveMember */
|
||||
$effectiveMember = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : $timeEntry->member;
|
||||
$effectiveStart = $request->has('start') ? Carbon::parse($request->input('start')) : $timeEntry->start;
|
||||
$effectiveEnd = $request->has('end') ? ($request->input('end') !== null ? Carbon::parse($request->input('end')) : null) : $timeEntry->end;
|
||||
$this->assertNoOverlap($organization, $effectiveMember, $effectiveStart, $effectiveEnd, $timeEntry);
|
||||
|
||||
$oldProject = $timeEntry->project;
|
||||
$oldTask = $timeEntry->task;
|
||||
|
||||
|
||||
@@ -41,7 +41,6 @@ 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');
|
||||
|
||||
/** @var BillingContract $billing */
|
||||
$billing = app(BillingContract::class);
|
||||
@@ -51,7 +50,6 @@ class HandleInertiaRequests extends Middleware
|
||||
return array_merge(parent::share($request), [
|
||||
'has_billing_extension' => $hasBilling,
|
||||
'has_invoicing_extension' => $hasInvoicing,
|
||||
'has_services_extension' => $hasServices,
|
||||
'billing' => $currentOrganization !== null ? [
|
||||
'has_subscription' => $billing->hasSubscription($currentOrganization),
|
||||
'has_trial' => $billing->hasTrial($currentOrganization),
|
||||
|
||||
@@ -21,11 +21,6 @@ class InvitationIndexRequest extends BaseFormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => [
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,11 +21,6 @@ class MemberIndexRequest extends BaseFormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => [
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,12 +39,6 @@ class OrganizationUpdateRequest extends BaseFormRequest
|
||||
'employees_can_see_billable_rates' => [
|
||||
'boolean',
|
||||
],
|
||||
'employees_can_manage_tasks' => [
|
||||
'boolean',
|
||||
],
|
||||
'prevent_overlapping_time_entries' => [
|
||||
'boolean',
|
||||
],
|
||||
'number_format' => [
|
||||
Rule::enum(NumberFormat::class),
|
||||
],
|
||||
@@ -104,14 +98,4 @@ class OrganizationUpdateRequest extends BaseFormRequest
|
||||
{
|
||||
return $this->has('employees_can_see_billable_rates') ? $this->boolean('employees_can_see_billable_rates') : null;
|
||||
}
|
||||
|
||||
public function getEmployeesCanManageTasks(): ?bool
|
||||
{
|
||||
return $this->has('employees_can_manage_tasks') ? $this->boolean('employees_can_manage_tasks') : null;
|
||||
}
|
||||
|
||||
public function getPreventOverlappingTimeEntries(): ?bool
|
||||
{
|
||||
return $this->has('prevent_overlapping_time_entries') ? $this->boolean('prevent_overlapping_time_entries') : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\ProjectMember;
|
||||
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
class ProjectMemberIndexRequest extends BaseFormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => [
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\Report;
|
||||
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
class ReportIndexRequest extends BaseFormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => [
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -6,15 +6,12 @@ namespace App\Http\Requests\V1\Report;
|
||||
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Organization;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Validation\Rule as LegacyValidationRule;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
@@ -25,7 +22,7 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|LegacyValidationRule|\Closure>>
|
||||
* @return array<string, array<string|ValidationRule|LegacyValidationRule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -83,14 +80,7 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
],
|
||||
'properties.client_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
if (! Str::isUuid($value)) {
|
||||
$fail('The '.$attribute.' must be a valid UUID.');
|
||||
}
|
||||
},
|
||||
'uuid',
|
||||
],
|
||||
// Filter by project IDs, project IDs are OR combined
|
||||
'properties.project_ids' => [
|
||||
@@ -99,14 +89,7 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
],
|
||||
'properties.project_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
if (! Str::isUuid($value)) {
|
||||
$fail('The '.$attribute.' must be a valid UUID.');
|
||||
}
|
||||
},
|
||||
'uuid',
|
||||
],
|
||||
// Filter by tag IDs, tag IDs are OR combined
|
||||
'properties.tag_ids' => [
|
||||
@@ -115,14 +98,7 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
],
|
||||
'properties.tag_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
if (! Str::isUuid($value)) {
|
||||
$fail('The '.$attribute.' must be a valid UUID.');
|
||||
}
|
||||
},
|
||||
'uuid',
|
||||
],
|
||||
'properties.task_ids' => [
|
||||
'nullable',
|
||||
@@ -130,14 +106,7 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
],
|
||||
'properties.task_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
if (! Str::isUuid($value)) {
|
||||
$fail('The '.$attribute.' must be a valid UUID.');
|
||||
}
|
||||
},
|
||||
'uuid',
|
||||
],
|
||||
'properties.group' => [
|
||||
'required',
|
||||
@@ -159,18 +128,6 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
'nullable',
|
||||
'timezone:all',
|
||||
],
|
||||
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
|
||||
'properties.rounding_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TimeEntryRoundingType::class),
|
||||
],
|
||||
// Defines the length of the interval that the time entry rounding rounds to.
|
||||
'properties.rounding_minutes' => [
|
||||
'nullable',
|
||||
'numeric',
|
||||
'integer',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -248,22 +205,4 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
{
|
||||
return TimeEntryAggregationTypeInterval::from($this->input('properties.history_group'));
|
||||
}
|
||||
|
||||
public function getPropertyRoundingType(): ?TimeEntryRoundingType
|
||||
{
|
||||
if (! $this->has('properties.rounding_type') || $this->input('properties.rounding_type') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TimeEntryRoundingType::from($this->input('properties.rounding_type'));
|
||||
}
|
||||
|
||||
public function getPropertyRoundingMinutes(): ?int
|
||||
{
|
||||
if (! $this->has('properties.rounding_minutes') || $this->input('properties.rounding_minutes') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $this->input('properties.rounding_minutes');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\Tag;
|
||||
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
class TagIndexRequest extends BaseFormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => [
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,6 @@ class TaskIndexRequest extends BaseFormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => [
|
||||
'integer',
|
||||
'min:1',
|
||||
'max:2147483647',
|
||||
],
|
||||
'project_id' => [
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
|
||||
@@ -7,7 +7,6 @@ namespace App\Http\Requests\V1\TimeEntry;
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
@@ -16,7 +15,6 @@ use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Models\User;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
@@ -31,7 +29,7 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule|\Closure>>
|
||||
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -95,15 +93,10 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
],
|
||||
'project_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by client IDs, client IDs are OR combined
|
||||
'client_ids' => [
|
||||
@@ -112,15 +105,10 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
],
|
||||
'client_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by tag IDs, tag IDs are OR combined
|
||||
'tag_ids' => [
|
||||
@@ -129,15 +117,10 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
],
|
||||
'tag_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by task IDs, task IDs are OR combined
|
||||
'task_ids' => [
|
||||
@@ -146,14 +129,9 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
],
|
||||
'task_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
|
||||
'start' => [
|
||||
@@ -186,18 +164,6 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
|
||||
'rounding_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TimeEntryRoundingType::class),
|
||||
],
|
||||
// Defines the length of the interval that the time entry rounding rounds to.
|
||||
'rounding_minutes' => [
|
||||
'nullable',
|
||||
'numeric',
|
||||
'integer',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -245,22 +211,4 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
{
|
||||
return ExportFormat::from($this->validated('format'));
|
||||
}
|
||||
|
||||
public function getRoundingType(): ?TimeEntryRoundingType
|
||||
{
|
||||
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TimeEntryRoundingType::from($this->validated('rounding_type'));
|
||||
}
|
||||
|
||||
public function getRoundingMinutes(): ?int
|
||||
{
|
||||
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $this->validated('rounding_minutes');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ declare(strict_types=1);
|
||||
namespace App\Http\Requests\V1\TimeEntry;
|
||||
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
@@ -14,7 +13,6 @@ use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Models\User;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
@@ -29,7 +27,7 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule|\Closure>>
|
||||
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -81,15 +79,10 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
],
|
||||
'project_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by client IDs, client IDs are OR combined
|
||||
'client_ids' => [
|
||||
@@ -98,15 +91,10 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
],
|
||||
'client_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by tag IDs, tag IDs are OR combined
|
||||
'tag_ids' => [
|
||||
@@ -115,15 +103,10 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
],
|
||||
'tag_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by task IDs, task IDs are OR combined
|
||||
'task_ids' => [
|
||||
@@ -132,14 +115,9 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
],
|
||||
'task_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
|
||||
'start' => [
|
||||
@@ -168,18 +146,6 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
|
||||
'rounding_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TimeEntryRoundingType::class),
|
||||
],
|
||||
// Defines the length of the interval that the time entry rounding rounds to.
|
||||
'rounding_minutes' => [
|
||||
'nullable',
|
||||
'numeric',
|
||||
'integer',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -207,22 +173,4 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
{
|
||||
return $this->input('end') !== null ? Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('end'), 'UTC') : null;
|
||||
}
|
||||
|
||||
public function getRoundingType(): ?TimeEntryRoundingType
|
||||
{
|
||||
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TimeEntryRoundingType::from($this->validated('rounding_type'));
|
||||
}
|
||||
|
||||
public function getRoundingMinutes(): ?int
|
||||
{
|
||||
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $this->validated('rounding_minutes');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,14 +5,11 @@ declare(strict_types=1);
|
||||
namespace App\Http\Requests\V1\TimeEntry;
|
||||
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
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\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
@@ -27,7 +24,7 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule|\Closure>>
|
||||
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -59,23 +56,6 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
}),
|
||||
],
|
||||
// Filter by client IDs, client IDs are OR combined
|
||||
'client_ids' => [
|
||||
'array',
|
||||
'min:1',
|
||||
],
|
||||
'client_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
],
|
||||
// Filter by project IDs, project IDs are OR combined
|
||||
'project_ids' => [
|
||||
'array',
|
||||
@@ -83,15 +63,11 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
],
|
||||
'project_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
'uuid',
|
||||
new ExistsEloquent(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
}),
|
||||
],
|
||||
// Filter by tag IDs, tag IDs are OR combined
|
||||
'tag_ids' => [
|
||||
@@ -100,15 +76,11 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
],
|
||||
'tag_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
'uuid',
|
||||
new ExistsEloquent(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
}),
|
||||
],
|
||||
// Filter by task IDs, task IDs are OR combined
|
||||
'task_ids' => [
|
||||
@@ -117,15 +89,11 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
],
|
||||
'task_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Task> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
'uuid',
|
||||
new ExistsEloquent(Task::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Task> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
}),
|
||||
],
|
||||
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
|
||||
'start' => [
|
||||
@@ -165,18 +133,6 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
|
||||
'rounding_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TimeEntryRoundingType::class),
|
||||
],
|
||||
// Defines the length of the interval that the time entry rounding rounds to.
|
||||
'rounding_minutes' => [
|
||||
'nullable',
|
||||
'numeric',
|
||||
'integer',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -214,22 +170,4 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
{
|
||||
return ExportFormat::from($this->validated('format'));
|
||||
}
|
||||
|
||||
public function getRoundingType(): ?TimeEntryRoundingType
|
||||
{
|
||||
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TimeEntryRoundingType::from($this->validated('rounding_type'));
|
||||
}
|
||||
|
||||
public function getRoundingMinutes(): ?int
|
||||
{
|
||||
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $this->validated('rounding_minutes');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\TimeEntry;
|
||||
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
@@ -12,11 +11,8 @@ use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Validation\Rule as RuleContract;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
@@ -27,7 +23,7 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule|RuleContract|\Closure>>
|
||||
* @return array<string, array<string|ValidationRule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -59,15 +55,10 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
],
|
||||
'client_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Client> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by project IDs, project IDs are OR combined
|
||||
'project_ids' => [
|
||||
@@ -76,15 +67,10 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
],
|
||||
'project_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by tag IDs, tag IDs are OR combined
|
||||
'tag_ids' => [
|
||||
@@ -93,15 +79,10 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
],
|
||||
'tag_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Tag> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter by task IDs, task IDs are OR combined
|
||||
'task_ids' => [
|
||||
@@ -110,15 +91,10 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
],
|
||||
'task_ids.*' => [
|
||||
'string',
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryFilter::NONE_VALUE) {
|
||||
return;
|
||||
}
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Task> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid()->validate($attribute, $value, $fail);
|
||||
},
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Task> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
|
||||
'start' => [
|
||||
@@ -160,18 +136,6 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
|
||||
'rounding_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TimeEntryRoundingType::class),
|
||||
],
|
||||
// Defines the length of the interval that the time entry rounding rounds to.
|
||||
'rounding_minutes' => [
|
||||
'nullable',
|
||||
'numeric',
|
||||
'integer',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -189,22 +153,4 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
{
|
||||
return $this->has('offset') ? (int) $this->validated('offset', 0) : 0;
|
||||
}
|
||||
|
||||
public function getRoundingType(): ?TimeEntryRoundingType
|
||||
{
|
||||
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TimeEntryRoundingType::from($this->validated('rounding_type'));
|
||||
}
|
||||
|
||||
public function getRoundingMinutes(): ?int
|
||||
{
|
||||
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $this->validated('rounding_minutes');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,8 @@ use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Service\PermissionStore;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
@@ -44,16 +42,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
||||
'required_with:task_id',
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||
|
||||
// If user doesn't have 'all' permission for time entries or projects, only allow access to public projects or projects they're a member of
|
||||
$permissionStore = app(PermissionStore::class);
|
||||
if (! $permissionStore->has($this->organization, 'time-entries:create:all')
|
||||
&& ! $permissionStore->has($this->organization, 'projects:view:all')) {
|
||||
$builder = $builder->visibleByEmployee(Auth::user());
|
||||
}
|
||||
|
||||
return $builder;
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// ID of the task that the time entry should belong to
|
||||
@@ -90,7 +79,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
||||
'description' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:5000',
|
||||
'max:500',
|
||||
],
|
||||
// List of tag IDs
|
||||
'tags' => [
|
||||
|
||||
@@ -10,10 +10,8 @@ use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Service\PermissionStore;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
@@ -56,16 +54,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
||||
'required_with:task_id',
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||
|
||||
// If user doesn't have 'all' permission for time entries or projects, only allow access to public projects or projects they're a member of
|
||||
$permissionStore = app(PermissionStore::class);
|
||||
if (! $permissionStore->has($this->organization, 'time-entries:update:all')
|
||||
&& ! $permissionStore->has($this->organization, 'projects:view:all')) {
|
||||
$builder = $builder->visibleByEmployee(Auth::user());
|
||||
}
|
||||
|
||||
return $builder;
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// ID of the task that the time entry should belong to
|
||||
@@ -90,7 +79,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
||||
'changes.description' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:5000',
|
||||
'max:500',
|
||||
],
|
||||
// List of tag IDs
|
||||
'changes.tags' => [
|
||||
|
||||
@@ -10,10 +10,8 @@ use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Service\PermissionStore;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
@@ -44,16 +42,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
'required_with:task_id',
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||
|
||||
// If user doesn't have 'all' permission for time entries or projects, only allow access to public projects or projects they're a member of
|
||||
$permissionStore = app(PermissionStore::class);
|
||||
if (! $permissionStore->has($this->organization, 'time-entries:update:all')
|
||||
&& ! $permissionStore->has($this->organization, 'projects:view:all')) {
|
||||
$builder = $builder->visibleByEmployee(Auth::user());
|
||||
}
|
||||
|
||||
return $builder;
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
})->uuid(),
|
||||
],
|
||||
// ID of the task that the time entry should belong to
|
||||
@@ -88,7 +77,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
'description' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:5000',
|
||||
'max:500',
|
||||
],
|
||||
// List of tag IDs
|
||||
'tags' => [
|
||||
|
||||
@@ -4,10 +4,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Resources\V1\Client;
|
||||
|
||||
use App\Http\Resources\PaginatedResourceCollection;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class ClientCollection extends ResourceCollection implements PaginatedResourceCollection
|
||||
class ClientCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* The resource that this resource collects.
|
||||
|
||||
@@ -53,10 +53,6 @@ class OrganizationResource extends BaseResource
|
||||
'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 */
|
||||
'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 */
|
||||
'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_overlapping_time_entries' => $this->resource->prevent_overlapping_time_entries,
|
||||
/** @var string $currency Currency code (ISO 4217) */
|
||||
'currency' => $this->resource->currency,
|
||||
/** @var string $currency_symbol Currency symbol */
|
||||
|
||||
@@ -58,10 +58,6 @@ class DetailedReportResource extends BaseResource
|
||||
'tag_ids' => $this->resource->properties->tagIds?->toArray(),
|
||||
/** @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' => $this->resource->properties->roundingType?->value,
|
||||
/** @var int|null $rounding_minutes Rounding minutes for time entries */
|
||||
'rounding_minutes' => $this->resource->properties->roundingMinutes,
|
||||
],
|
||||
/** @var string $created_at Date when the report was created */
|
||||
'created_at' => $this->formatDateTime($this->resource->created_at),
|
||||
|
||||
@@ -4,10 +4,9 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Resources\V1\Tag;
|
||||
|
||||
use App\Http\Resources\PaginatedResourceCollection;
|
||||
use Illuminate\Http\Resources\Json\ResourceCollection;
|
||||
|
||||
class TagCollection extends ResourceCollection implements PaginatedResourceCollection
|
||||
class TagCollection extends ResourceCollection
|
||||
{
|
||||
/**
|
||||
* The resource that this resource collects.
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Passport\Token;
|
||||
use App\Models\User;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
class AuthApiTokenExpirationReminderMail extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public Token $token;
|
||||
|
||||
public User $user;
|
||||
|
||||
/**
|
||||
* Create a new message instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct(Token $token, User $user)
|
||||
{
|
||||
$this->token = $token;
|
||||
$this->user = $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the message.
|
||||
*/
|
||||
public function build(): self
|
||||
{
|
||||
return $this->markdown('emails.auth-api-expiration-reminder', [
|
||||
'profileUrl' => URL::to('user/profile'),
|
||||
'tokenName' => $this->token->name,
|
||||
])
|
||||
->subject(__('Your API token will expire in 7 days!'));
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Passport\Token;
|
||||
use App\Models\User;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
class AuthApiTokenExpiredMail extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public Token $token;
|
||||
|
||||
public User $user;
|
||||
|
||||
/**
|
||||
* Create a new message instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct(Token $token, User $user)
|
||||
{
|
||||
$this->token = $token;
|
||||
$this->user = $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the message.
|
||||
*/
|
||||
public function build(): self
|
||||
{
|
||||
return $this->markdown('emails.auth-api-token-expired', [
|
||||
'profileUrl' => URL::to('user/profile'),
|
||||
'tokenName' => $this->token->name,
|
||||
])
|
||||
->subject(__('Your API token has expired!'));
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ namespace App\Models;
|
||||
use App\Models\Concerns\CustomAuditable;
|
||||
use App\Models\Concerns\HasUuids;
|
||||
use Database\Factories\ClientFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -63,18 +62,6 @@ class Client extends Model implements AuditableContract
|
||||
return $this->hasMany(Project::class, 'client_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Client> $builder
|
||||
* @return Builder<Client>
|
||||
*/
|
||||
public function scopeVisibleByEmployee(Builder $builder, User $user): Builder
|
||||
{
|
||||
return $builder->whereHas('projects', function (Builder $builder) use ($user): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
return $builder->visibleByEmployee($user);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Attribute<bool, never>
|
||||
*/
|
||||
|
||||
@@ -35,7 +35,6 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
* @property int|null $billable_rate
|
||||
* @property string $user_id
|
||||
* @property bool $employees_can_see_billable_rates
|
||||
* @property bool $employees_can_manage_tasks
|
||||
* @property User $owner
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $updated_at
|
||||
@@ -71,8 +70,6 @@ class Organization extends JetstreamTeam implements AuditableContract
|
||||
'personal_team' => 'boolean',
|
||||
'currency' => 'string',
|
||||
'employees_can_see_billable_rates' => 'boolean',
|
||||
'employees_can_manage_tasks' => 'boolean',
|
||||
'prevent_overlapping_time_entries' => 'boolean',
|
||||
'number_format' => NumberFormat::class,
|
||||
'currency_format' => CurrencyFormat::class,
|
||||
'date_format' => DateFormat::class,
|
||||
|
||||
@@ -6,7 +6,6 @@ namespace App\Models\Passport;
|
||||
|
||||
use App\Models\User;
|
||||
use Database\Factories\Passport\TokenFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Carbon;
|
||||
@@ -19,15 +18,11 @@ use Laravel\Passport\Token as PassportToken;
|
||||
* @property null|string $name
|
||||
* @property array<string> $scopes
|
||||
* @property bool $revoked
|
||||
* @property Carbon|null $reminder_sent_at
|
||||
* @property Carbon|null $expired_info_sent_at
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $updated_at
|
||||
* @property Carbon|null $expires_at
|
||||
* @property-read Client|null $client
|
||||
* @property-read User|null $user
|
||||
*
|
||||
* @method Builder<Token> isApiToken(bool $isApiToken = true)
|
||||
*/
|
||||
class Token extends PassportToken
|
||||
{
|
||||
@@ -57,40 +52,4 @@ class Token extends PassportToken
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'scopes' => 'array',
|
||||
'revoked' => 'bool',
|
||||
'expires_at' => 'datetime',
|
||||
'reminder_sent_at' => 'datetime',
|
||||
'expired_info_sent_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<static> $query
|
||||
* @return Builder<static>
|
||||
*/
|
||||
public function scopeIsApiToken(Builder $query, bool $isApiToken = true): Builder
|
||||
{
|
||||
if ($isApiToken) {
|
||||
return $query->whereHas('client', function (Builder $query): void {
|
||||
/** @var Builder<Client> $query */
|
||||
$query->whereJsonContains('grant_types', 'personal_access');
|
||||
});
|
||||
} else {
|
||||
return $query->whereHas('client', function (Builder $query): void {
|
||||
/** @var Builder<Client> $query */
|
||||
$query->whereJsonDoesntContain('grant_types', 'personal_access');
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,26 +77,6 @@ class TimeEntry extends Model implements AuditableContract
|
||||
'still_active_email_sent_at' => 'datetime',
|
||||
];
|
||||
|
||||
public const array SELECT_COLUMNS = [
|
||||
'id',
|
||||
'description',
|
||||
'start',
|
||||
'end',
|
||||
'billable_rate',
|
||||
'billable',
|
||||
'user_id',
|
||||
'organization_id',
|
||||
'project_id',
|
||||
'task_id',
|
||||
'tags',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'member_id',
|
||||
'client_id',
|
||||
'is_imported',
|
||||
'still_active_email_sent_at',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that are computed. (f.e. for performance reasons)
|
||||
* These attributes can be regenerated at any time.
|
||||
|
||||
@@ -6,7 +6,6 @@ namespace App\Policies;
|
||||
|
||||
use App\Models\Organization;
|
||||
use App\Models\User;
|
||||
use App\Service\PermissionStore;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||
|
||||
@@ -59,7 +58,7 @@ class OrganizationPolicy
|
||||
return true;
|
||||
}
|
||||
|
||||
return app(PermissionStore::class)->userHas($organization, $user, 'organizations:update');
|
||||
return $user->ownsTeam($organization);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -94,11 +94,8 @@ class JetstreamServiceProvider extends ServiceProvider
|
||||
'tasks:view',
|
||||
'tasks:view:all',
|
||||
'tasks:create',
|
||||
'tasks:create:all',
|
||||
'tasks:update',
|
||||
'tasks:update:all',
|
||||
'tasks:delete',
|
||||
'tasks:delete:all',
|
||||
'time-entries:view:all',
|
||||
'time-entries:create:all',
|
||||
'time-entries:update:all',
|
||||
@@ -112,7 +109,6 @@ class JetstreamServiceProvider extends ServiceProvider
|
||||
'tags:update',
|
||||
'tags:delete',
|
||||
'clients:view',
|
||||
'clients:view:all',
|
||||
'clients:create',
|
||||
'clients:update',
|
||||
'clients:delete',
|
||||
@@ -161,11 +157,8 @@ class JetstreamServiceProvider extends ServiceProvider
|
||||
'tasks:view',
|
||||
'tasks:view:all',
|
||||
'tasks:create',
|
||||
'tasks:create:all',
|
||||
'tasks:update',
|
||||
'tasks:update:all',
|
||||
'tasks:delete',
|
||||
'tasks:delete:all',
|
||||
'time-entries:view:all',
|
||||
'time-entries:create:all',
|
||||
'time-entries:update:all',
|
||||
@@ -179,7 +172,6 @@ class JetstreamServiceProvider extends ServiceProvider
|
||||
'tags:update',
|
||||
'tags:delete',
|
||||
'clients:view',
|
||||
'clients:view:all',
|
||||
'clients:create',
|
||||
'clients:update',
|
||||
'clients:delete',
|
||||
@@ -225,11 +217,8 @@ class JetstreamServiceProvider extends ServiceProvider
|
||||
'tasks:view',
|
||||
'tasks:view:all',
|
||||
'tasks:create',
|
||||
'tasks:create:all',
|
||||
'tasks:update',
|
||||
'tasks:update:all',
|
||||
'tasks:delete',
|
||||
'tasks:delete:all',
|
||||
'time-entries:view:all',
|
||||
'time-entries:create:all',
|
||||
'time-entries:update:all',
|
||||
@@ -243,7 +232,6 @@ class JetstreamServiceProvider extends ServiceProvider
|
||||
'tags:update',
|
||||
'tags:delete',
|
||||
'clients:view',
|
||||
'clients:view:all',
|
||||
'clients:create',
|
||||
'clients:update',
|
||||
'clients:delete',
|
||||
@@ -268,13 +256,12 @@ class JetstreamServiceProvider extends ServiceProvider
|
||||
'projects:view',
|
||||
'tags:view',
|
||||
'tasks:view',
|
||||
'clients:view',
|
||||
'time-entries:view:own',
|
||||
'time-entries:create:own',
|
||||
'time-entries:update:own',
|
||||
'time-entries:delete:own',
|
||||
'organizations:view',
|
||||
])->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.');
|
||||
])->description('Employees have the ability to read, create, and update their own time entries and they can see the projects that they are members of.');
|
||||
|
||||
Jetstream::role(Role::Placeholder->value, 'Placeholder', [
|
||||
])->description('Placeholders are used for importing data. They cannot log in and have no permissions.');
|
||||
|
||||
@@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Brick\Money\ISOCurrencyProvider;
|
||||
use Brick\Money\Money;
|
||||
|
||||
class CurrencyService
|
||||
@@ -375,12 +374,4 @@ class CurrencyService
|
||||
|
||||
return $currencyCode;
|
||||
}
|
||||
|
||||
public function getRandomCurrencyCode(): string
|
||||
{
|
||||
$currencies = ISOCurrencyProvider::getInstance()->getAvailableCurrencies();
|
||||
$currencyCodes = array_keys($currencies);
|
||||
|
||||
return $currencyCodes[array_rand($currencyCodes)];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -266,8 +266,7 @@ class DashboardService
|
||||
) as aggregate'))
|
||||
->where('billable', '=', true)
|
||||
->whereNotNull('billable_rate')
|
||||
->where('user_id', '=', $user->getKey())
|
||||
->where('organization_id', '=', $organization->getKey());
|
||||
->where('user_id', '=', $user->id);
|
||||
|
||||
$query = $this->constrainDateByPossibleDates($query, $possibleDays, $timezone);
|
||||
/** @var Collection<int, object{aggregate: int}> $resultDb */
|
||||
|
||||
@@ -6,9 +6,7 @@ namespace App\Service\Dto;
|
||||
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Database\Eloquent\Castable;
|
||||
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
@@ -61,10 +59,6 @@ class ReportPropertiesDto implements Castable
|
||||
*/
|
||||
public ?Collection $taskIds = null;
|
||||
|
||||
public ?TimeEntryRoundingType $roundingType = null;
|
||||
|
||||
public ?int $roundingMinutes = null;
|
||||
|
||||
/**
|
||||
* Get the caster class to use when casting from / to this cast target.
|
||||
*
|
||||
@@ -121,10 +115,6 @@ class ReportPropertiesDto implements Castable
|
||||
$dto->historyGroup = TimeEntryAggregationTypeInterval::from($data->historyGroup);
|
||||
$dto->weekStart = Weekday::from($data->weekStart);
|
||||
$dto->timezone = $data->timezone;
|
||||
// Note: roundingType was added later so it is possible that the value is missing in persisted reports in the DB
|
||||
$dto->roundingType = isset($data->roundingType) ? TimeEntryRoundingType::from($data->roundingType) : null;
|
||||
// Note: roundingMinutes was added later so it is possible that the value is missing in persisted reports in the DB
|
||||
$dto->roundingMinutes = isset($data->roundingMinutes) ? (int) $data->roundingMinutes : null;
|
||||
|
||||
return $dto;
|
||||
}
|
||||
@@ -150,8 +140,6 @@ class ReportPropertiesDto implements Castable
|
||||
'historyGroup' => $value->historyGroup->value,
|
||||
'weekStart' => $value->weekStart->value,
|
||||
'timezone' => $value->timezone,
|
||||
'roundingType' => $value->roundingType?->value,
|
||||
'roundingMinutes' => $value->roundingMinutes,
|
||||
];
|
||||
|
||||
$jsonString = json_encode($data);
|
||||
@@ -175,7 +163,7 @@ class ReportPropertiesDto implements Castable
|
||||
if (! is_string($id)) {
|
||||
throw new \InvalidArgumentException('The given ID is not a string');
|
||||
}
|
||||
if ($id !== TimeEntryFilter::NONE_VALUE && ! Str::isUuid($id)) {
|
||||
if (! Str::isUuid($id)) {
|
||||
throw new \InvalidArgumentException('The given ID is not a valid UUID');
|
||||
}
|
||||
$collection->push($id);
|
||||
|
||||
@@ -167,7 +167,7 @@ class ExportService
|
||||
$client->id,
|
||||
$client->name,
|
||||
$client->organization_id,
|
||||
$client->archived_at?->toIso8601ZuluString() ?? '',
|
||||
$client->archived_at ?? '',
|
||||
$client->created_at?->toIso8601ZuluString() ?? '',
|
||||
$client->updated_at?->toIso8601ZuluString() ?? '',
|
||||
]);
|
||||
|
||||
@@ -112,7 +112,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
$timeEntry->project_id = $projectId;
|
||||
$timeEntry->client_id = $clientId;
|
||||
$timeEntry->organization_id = $this->organization->id;
|
||||
if (strlen($record['Description']) > 5000) {
|
||||
if (strlen($record['Description']) > 500) {
|
||||
throw new ImportException('Time entry description is too long');
|
||||
}
|
||||
$timeEntry->description = $record['Description'];
|
||||
|
||||
@@ -107,7 +107,7 @@ class HarvestTimeEntriesImporter extends DefaultImporter
|
||||
$timeEntry->project_id = $projectId;
|
||||
$timeEntry->client_id = $clientId;
|
||||
$timeEntry->organization_id = $this->organization->id;
|
||||
if (strlen($record['Notes']) > 5000) {
|
||||
if (strlen($record['Notes']) > 500) {
|
||||
throw new ImportException('Time entry note is too long');
|
||||
}
|
||||
$timeEntry->description = $record['Notes'];
|
||||
|
||||
@@ -247,7 +247,7 @@ class SolidtimeImporter extends DefaultImporter
|
||||
$timeEntry->project_id = $projectId;
|
||||
$timeEntry->client_id = $clientId;
|
||||
$timeEntry->organization_id = $this->organization->id;
|
||||
if (strlen($timeEntryRow['description']) > 5000) {
|
||||
if (strlen($timeEntryRow['description']) > 500) {
|
||||
throw new ImportException('Time entry description is too long');
|
||||
}
|
||||
$timeEntry->description = $timeEntryRow['description'];
|
||||
|
||||
@@ -196,7 +196,6 @@ class MemberService
|
||||
|
||||
$placeholderUser = $user->replicate();
|
||||
$placeholderUser->is_placeholder = true;
|
||||
$placeholderUser->current_team_id = $member->organization_id;
|
||||
$placeholderUser->save();
|
||||
|
||||
$member->user()->associate($placeholderUser);
|
||||
|
||||
@@ -71,19 +71,7 @@ class PermissionStore
|
||||
/** @var Role|null $roleObj */
|
||||
$roleObj = Jetstream::findRole($role);
|
||||
|
||||
$permissions = $roleObj->permissions ?? [];
|
||||
|
||||
// If the organization allows employees to manage tasks and the user is an employee,
|
||||
// add the task management permissions for accessible projects
|
||||
if ($role === \App\Enums\Role::Employee->value && $organization->employees_can_manage_tasks) {
|
||||
$permissions = array_merge($permissions, [
|
||||
'tasks:create',
|
||||
'tasks:update',
|
||||
'tasks:delete',
|
||||
]);
|
||||
}
|
||||
|
||||
return $permissions;
|
||||
return $roleObj->permissions ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,11 +6,9 @@ namespace App\Service;
|
||||
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Models\Client;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Models\User;
|
||||
@@ -18,7 +16,6 @@ use Carbon\CarbonTimeZone;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class TimeEntryAggregationService
|
||||
@@ -44,24 +41,12 @@ class TimeEntryAggregationService
|
||||
* cost: int|null
|
||||
* }
|
||||
*/
|
||||
public function getAggregatedTimeEntries(Builder $timeEntriesQuery, ?TimeEntryAggregationType $group1Type, ?TimeEntryAggregationType $group2Type, string $timezone, Weekday $startOfWeek, bool $fillGapsInTimeGroups, ?Carbon $start, ?Carbon $end, bool $showBillableRate, ?TimeEntryRoundingType $roundingType, ?int $roundingMinutes): array
|
||||
public function getAggregatedTimeEntries(Builder $timeEntriesQuery, ?TimeEntryAggregationType $group1Type, ?TimeEntryAggregationType $group2Type, string $timezone, Weekday $startOfWeek, bool $fillGapsInTimeGroups, ?Carbon $start, ?Carbon $end, bool $showBillableRate): array
|
||||
{
|
||||
$fillGapsInTimeGroupsIsPossible = $fillGapsInTimeGroups && $start !== null && $end !== null;
|
||||
/** @var Builder<TimeEntry> $baseTotalsQuery */
|
||||
$baseTotalsQuery = $timeEntriesQuery->clone();
|
||||
$group1Select = null;
|
||||
$group2Select = null;
|
||||
$groupBy = null;
|
||||
// If any grouping is by tag, expand rows per tag and ensure a NULL row for entries without tags
|
||||
if (($group1Type === TimeEntryAggregationType::Tag) || ($group2Type === TimeEntryAggregationType::Tag)) {
|
||||
$timeEntriesQuery->crossJoin(DB::raw(
|
||||
"LATERAL (\n".
|
||||
" SELECT jsonb_array_elements_text(coalesce(tags, '[]'::jsonb)) AS tag\n".
|
||||
" UNION ALL\n".
|
||||
" SELECT ''::text AS tag WHERE coalesce(jsonb_array_length(tags), 0) = 0\n".
|
||||
') AS tag(tag)'
|
||||
));
|
||||
}
|
||||
if ($group1Type !== null) {
|
||||
$group1Select = $this->getGroupByQuery($group1Type, $timezone, $startOfWeek);
|
||||
$groupBy = ['group_1'];
|
||||
@@ -71,14 +56,15 @@ class TimeEntryAggregationService
|
||||
}
|
||||
}
|
||||
|
||||
$startRawSelect = app(TimeEntryService::class)->getStartSelectRawForRounding($roundingType, $roundingMinutes);
|
||||
$endRawSelect = app(TimeEntryService::class)->getEndSelectRawForRounding($roundingType, $roundingMinutes);
|
||||
|
||||
$timeEntriesQuery->selectRaw(
|
||||
($group1Select !== null ? $group1Select.' as group_1,' : '').
|
||||
($group2Select !== null ? $group2Select.' as group_2,' : '').
|
||||
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')))) as aggregate,'.
|
||||
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')) * (coalesce(billable_rate, 0)::float/60/60))) as cost'
|
||||
' round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate,'.
|
||||
' round(
|
||||
sum(
|
||||
extract(epoch from (coalesce("end", now()) - start)) * (coalesce(billable_rate, 0)::float/60/60)
|
||||
)
|
||||
) as cost'
|
||||
);
|
||||
if ($groupBy !== null) {
|
||||
$timeEntriesQuery->groupBy($groupBy);
|
||||
@@ -98,26 +84,6 @@ class TimeEntryAggregationService
|
||||
$group1Response = [];
|
||||
$group1ResponseSum = 0;
|
||||
$group1ResponseCost = 0;
|
||||
// If Tag is subgroup, prepare base totals per primary group without tag expansion
|
||||
$baseTotalsPerGroup1Map = [];
|
||||
if ($group2Type === TimeEntryAggregationType::Tag) {
|
||||
$baseTotalsPerGroup1Query = $baseTotalsQuery->clone();
|
||||
$baseTotalsPerGroup1 = $baseTotalsPerGroup1Query
|
||||
->selectRaw(
|
||||
$group1Select.' as group_1,'.
|
||||
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')))) as aggregate,'.
|
||||
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')) * (coalesce(billable_rate, 0)::float/60/60))) as cost'
|
||||
)
|
||||
->groupBy('group_1')
|
||||
->get();
|
||||
foreach ($baseTotalsPerGroup1 as $row) {
|
||||
/** @var object{group_1: mixed, aggregate: int|null, cost: int|null} $row */
|
||||
$baseTotalsPerGroup1Map[(string) ($row->group_1 ?? '')] = [
|
||||
'aggregate' => (int) ($row->aggregate ?? 0),
|
||||
'cost' => (int) ($row->cost ?? 0),
|
||||
];
|
||||
}
|
||||
}
|
||||
foreach ($groupedAggregates as $group1 => $group1Aggregates) {
|
||||
/** @var string|int $group1 */
|
||||
$group2Response = [];
|
||||
@@ -137,14 +103,6 @@ class TimeEntryAggregationService
|
||||
$group2ResponseSum += (int) $aggregate->get(0)->aggregate;
|
||||
$group2ResponseCost += (int) $aggregate->get(0)->cost;
|
||||
}
|
||||
// Override primary group totals when Tag is subgroup to avoid double counting
|
||||
if ($group2Type === TimeEntryAggregationType::Tag) {
|
||||
$keyForMap = (string) $group1;
|
||||
if (array_key_exists($keyForMap, $baseTotalsPerGroup1Map)) {
|
||||
$group2ResponseSum = $baseTotalsPerGroup1Map[$keyForMap]['aggregate'];
|
||||
$group2ResponseCost = $baseTotalsPerGroup1Map[$keyForMap]['cost'];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
/** @var Collection<int, object{aggregate: int, cost: int}> $group1Aggregates */
|
||||
$group2ResponseSum = (int) $group1Aggregates->get(0)->aggregate;
|
||||
@@ -163,23 +121,6 @@ class TimeEntryAggregationService
|
||||
$group1ResponseCost += $group2ResponseCost;
|
||||
}
|
||||
|
||||
// If Tag is selected in any grouping, compute overall totals from base (non-tag-expanded) query to avoid double counting
|
||||
$hasTagGrouping = ($group1Type === TimeEntryAggregationType::Tag) || ($group2Type === TimeEntryAggregationType::Tag);
|
||||
if ($hasTagGrouping) {
|
||||
// Reset selects and ordering on the cloned base query
|
||||
$baseTotals = $baseTotalsQuery
|
||||
->selectRaw(
|
||||
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')))) as aggregate,'.
|
||||
' round(sum(extract(epoch from ('.$endRawSelect.' - '.$startRawSelect.')) * (coalesce(billable_rate, 0)::float/60/60))) as cost'
|
||||
)
|
||||
->first();
|
||||
if ($baseTotals !== null) {
|
||||
/** @var object{aggregate: int|null, cost: int|null} $baseTotals */
|
||||
$group1ResponseSum = (int) ($baseTotals->aggregate ?? 0);
|
||||
$group1ResponseCost = (int) ($baseTotals->cost ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
if ($fillGapsInTimeGroupsIsPossible) {
|
||||
$group1Response = $this->fillGapsInTimeGroups($group1Response, $group1Type, $group2Type, $timezone, $startOfWeek, $start, $end);
|
||||
}
|
||||
@@ -223,9 +164,9 @@ class TimeEntryAggregationService
|
||||
* cost: int|null
|
||||
* }
|
||||
*/
|
||||
public function getAggregatedTimeEntriesWithDescriptions(Builder $timeEntriesQuery, ?TimeEntryAggregationType $group1Type, ?TimeEntryAggregationType $group2Type, string $timezone, Weekday $startOfWeek, bool $fillGapsInTimeGroups, ?Carbon $start, ?Carbon $end, bool $showBillableRate, ?TimeEntryRoundingType $roundingType, ?int $roundingMinutes): array
|
||||
public function getAggregatedTimeEntriesWithDescriptions(Builder $timeEntriesQuery, ?TimeEntryAggregationType $group1Type, ?TimeEntryAggregationType $group2Type, string $timezone, Weekday $startOfWeek, bool $fillGapsInTimeGroups, ?Carbon $start, ?Carbon $end, bool $showBillableRate): array
|
||||
{
|
||||
$aggregatedTimeEntries = $this->getAggregatedTimeEntries($timeEntriesQuery, $group1Type, $group2Type, $timezone, $startOfWeek, $fillGapsInTimeGroups, $start, $end, $showBillableRate, $roundingType, $roundingMinutes);
|
||||
$aggregatedTimeEntries = $this->getAggregatedTimeEntries($timeEntriesQuery, $group1Type, $group2Type, $timezone, $startOfWeek, $fillGapsInTimeGroups, $start, $end, $showBillableRate);
|
||||
|
||||
$keysGroup1 = [];
|
||||
$keysGroup2 = [];
|
||||
@@ -353,17 +294,6 @@ class TimeEntryAggregationService
|
||||
'color' => null,
|
||||
];
|
||||
}
|
||||
} elseif ($type === TimeEntryAggregationType::Tag) {
|
||||
$tags = Tag::query()
|
||||
->whereIn('id', $keys)
|
||||
->select('id', 'name')
|
||||
->get();
|
||||
foreach ($tags as $tag) {
|
||||
$descriptorMap[$tag->id] = [
|
||||
'description' => $tag->name,
|
||||
'color' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $descriptorMap;
|
||||
@@ -506,8 +436,6 @@ class TimeEntryAggregationService
|
||||
return 'billable';
|
||||
} elseif ($group === TimeEntryAggregationType::Description) {
|
||||
return 'description';
|
||||
} elseif ($group === TimeEntryAggregationType::Tag) {
|
||||
return 'tag';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,6 @@ use Illuminate\Support\Facades\Log;
|
||||
|
||||
class TimeEntryFilter
|
||||
{
|
||||
public const string NONE_VALUE = 'none';
|
||||
|
||||
/**
|
||||
* @var Builder<TimeEntry>
|
||||
*/
|
||||
@@ -151,17 +149,7 @@ class TimeEntryFilter
|
||||
if ($clientIds === null) {
|
||||
return $this;
|
||||
}
|
||||
$includeNone = in_array(self::NONE_VALUE, $clientIds, true);
|
||||
$clientIds = array_values(array_filter($clientIds, fn (string $id): bool => $id !== self::NONE_VALUE));
|
||||
|
||||
$this->builder->where(function (Builder $builder) use ($clientIds, $includeNone): void {
|
||||
if (count($clientIds) > 0) {
|
||||
$builder->whereIn('client_id', $clientIds);
|
||||
}
|
||||
if ($includeNone) {
|
||||
$builder->orWhereNull('client_id');
|
||||
}
|
||||
});
|
||||
$this->builder->whereIn('client_id', $clientIds);
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -174,17 +162,7 @@ class TimeEntryFilter
|
||||
if ($projectIds === null) {
|
||||
return $this;
|
||||
}
|
||||
$includeNone = in_array(self::NONE_VALUE, $projectIds, true);
|
||||
$projectIds = array_values(array_filter($projectIds, fn (string $id): bool => $id !== self::NONE_VALUE));
|
||||
|
||||
$this->builder->where(function (Builder $builder) use ($projectIds, $includeNone): void {
|
||||
if (count($projectIds) > 0) {
|
||||
$builder->whereIn('project_id', $projectIds);
|
||||
}
|
||||
if ($includeNone) {
|
||||
$builder->orWhereNull('project_id');
|
||||
}
|
||||
});
|
||||
$this->builder->whereIn('project_id', $projectIds);
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -197,18 +175,10 @@ class TimeEntryFilter
|
||||
if ($tagIds === null) {
|
||||
return $this;
|
||||
}
|
||||
$includeNone = in_array(self::NONE_VALUE, $tagIds, true);
|
||||
$tagIds = array_values(array_filter($tagIds, fn (string $id): bool => $id !== self::NONE_VALUE));
|
||||
|
||||
$this->builder->where(function (Builder $builder) use ($tagIds, $includeNone): void {
|
||||
$this->builder->where(function (Builder $builder) use ($tagIds): void {
|
||||
foreach ($tagIds as $tagId) {
|
||||
$builder->orWhereJsonContains('tags', $tagId);
|
||||
}
|
||||
if ($includeNone) {
|
||||
$builder->orWhere(function (Builder $query): void {
|
||||
$query->whereJsonLength('tags', 0)->orWhereNull('tags');
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return $this;
|
||||
@@ -222,17 +192,7 @@ class TimeEntryFilter
|
||||
if ($taskIds === null) {
|
||||
return $this;
|
||||
}
|
||||
$includeNone = in_array(self::NONE_VALUE, $taskIds, true);
|
||||
$taskIds = array_values(array_filter($taskIds, fn (string $id): bool => $id !== self::NONE_VALUE));
|
||||
|
||||
$this->builder->where(function (Builder $builder) use ($taskIds, $includeNone): void {
|
||||
if (count($taskIds) > 0) {
|
||||
$builder->whereIn('task_id', $taskIds);
|
||||
}
|
||||
if ($includeNone) {
|
||||
$builder->orWhereNull('task_id');
|
||||
}
|
||||
});
|
||||
$this->builder->whereIn('task_id', $taskIds);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use Illuminate\Support\Carbon;
|
||||
use LogicException;
|
||||
|
||||
class TimeEntryService
|
||||
{
|
||||
public function getStartSelectRawForRounding(?TimeEntryRoundingType $roundingType, ?int $roundingMinutes): string
|
||||
{
|
||||
if ($roundingType === null || $roundingMinutes === null) {
|
||||
return 'start';
|
||||
}
|
||||
if ($roundingMinutes < 1) {
|
||||
throw new LogicException('Rounding minutes must be greater than 0');
|
||||
}
|
||||
|
||||
return 'date_bin(\'1 minutes\', start, TIMESTAMP \'1970-01-01\')';
|
||||
}
|
||||
|
||||
public function getEndSelectRawForRounding(?TimeEntryRoundingType $roundingType, ?int $roundingMinutes): string
|
||||
{
|
||||
if ($roundingType === null || $roundingMinutes === null) {
|
||||
return 'coalesce("end", \''.Carbon::now()->toDateTimeString().'\')';
|
||||
}
|
||||
if ($roundingMinutes < 1) {
|
||||
throw new LogicException('Rounding minutes must be greater than 0');
|
||||
}
|
||||
$end = 'coalesce("end", \''.Carbon::now()->toDateTimeString().'\')';
|
||||
$start = $this->getStartSelectRawForRounding($roundingType, $roundingMinutes);
|
||||
if ($roundingType === TimeEntryRoundingType::Down) {
|
||||
return 'date_bin(\''.$roundingMinutes.' minutes\', '.$end.', '.$start.')';
|
||||
} elseif ($roundingType === TimeEntryRoundingType::Up) {
|
||||
// If end is already on a boundary, keep it; otherwise round up to next boundary
|
||||
return 'CASE WHEN '.$end.' = date_bin(\''.$roundingMinutes.' minutes\', '.$end.', '.$start.') '.
|
||||
'THEN '.$end.' '.
|
||||
'ELSE date_bin(\''.$roundingMinutes.' minutes\', '.$end.' + interval \''.$roundingMinutes.' minutes\', '.$start.') '.
|
||||
'END';
|
||||
} elseif ($roundingType === TimeEntryRoundingType::Nearest) {
|
||||
return 'date_bin(\''.$roundingMinutes.' minutes\', '.$end.' + interval \''.($roundingMinutes / 2).' minutes\', '.$start.')';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,8 +118,7 @@
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"dont-discover": [
|
||||
"laravel/telescope",
|
||||
"nwidart/laravel-modules"
|
||||
"laravel/telescope"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -9,7 +9,6 @@ use App\Enums\NumberFormat;
|
||||
use App\Enums\TimeFormat;
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Nwidart\Modules\LaravelModulesServiceProvider;
|
||||
|
||||
return [
|
||||
|
||||
@@ -198,7 +197,6 @@ return [
|
||||
App\Providers\FortifyServiceProvider::class,
|
||||
App\Providers\JetstreamServiceProvider::class,
|
||||
// Warning: Do not add TelescopeServiceProvider here since it is already conditionally registered in AppServiceProvider
|
||||
LaravelModulesServiceProvider::class,
|
||||
])->toArray(),
|
||||
|
||||
/*
|
||||
|
||||
@@ -6,7 +6,6 @@ return [
|
||||
|
||||
'tasks' => [
|
||||
'time_entry_send_still_running_mails' => (bool) env('SCHEDULING_TASK_TIME_ENTRY_SEND_STILL_RUNNING_MAILS', true),
|
||||
'auth_send_mails_expiring_api_tokens' => (bool) env('SCHEDULING_TASK_AUTH_SEND_MAILS_EXPIRING_API_TOKENS', true),
|
||||
'self_hosting_check_for_update' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_CHECK_FOR_UPDATE', true),
|
||||
'self_hosting_telemetry' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_TELEMETRY', true),
|
||||
'self_hosting_database_consistency' => (bool) env('SCHEDULING_TASK_SELF_HOSTING_DATABASE_CONSISTENCY', false),
|
||||
|
||||
@@ -11,7 +11,6 @@ use App\Enums\NumberFormat;
|
||||
use App\Enums\TimeFormat;
|
||||
use App\Models\Organization;
|
||||
use App\Models\User;
|
||||
use App\Service\CurrencyService;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
@@ -28,7 +27,7 @@ class OrganizationFactory extends Factory
|
||||
{
|
||||
return [
|
||||
'name' => $this->faker->unique()->company(),
|
||||
'currency' => app(CurrencyService::class)->getRandomCurrencyCode(),
|
||||
'currency' => $this->faker->currencyCode(),
|
||||
'billable_rate' => null,
|
||||
'user_id' => User::factory(),
|
||||
'personal_team' => true,
|
||||
|
||||
@@ -36,22 +36,6 @@ class ClientFactory extends BaseClientFactory
|
||||
];
|
||||
}
|
||||
|
||||
public function desktopClient(): self
|
||||
{
|
||||
return $this->state(fn (array $attributes) => [
|
||||
'name' => 'Desktop',
|
||||
'grant_types' => ['urn:ietf:params:oauth:grant-type:device_code', 'refresh_token', 'authorization_code', 'implicit'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function apiClient(): self
|
||||
{
|
||||
return $this->state(fn (array $attributes) => [
|
||||
'name' => 'API',
|
||||
'grant_types' => ['urn:ietf:params:oauth:grant-type:device_code', 'refresh_token', 'client_credentials', 'personal_access'],
|
||||
]);
|
||||
}
|
||||
|
||||
public function personalAccessClient(): self
|
||||
{
|
||||
return $this->state(function (array $attributes) {
|
||||
|
||||
@@ -31,8 +31,6 @@ class TokenFactory extends Factory
|
||||
'created_at' => $this->faker->dateTime,
|
||||
'updated_at' => $this->faker->dateTime,
|
||||
'expires_at' => $this->faker->dateTime,
|
||||
'reminder_sent_at' => null,
|
||||
'expired_info_sent_at' => null,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -153,16 +153,6 @@ class TimeEntryFactory extends Factory
|
||||
});
|
||||
}
|
||||
|
||||
public function endWithDuration(Carbon $end, int $durationInSeconds): self
|
||||
{
|
||||
return $this->state(function (array $attributes) use ($end, $durationInSeconds): array {
|
||||
return [
|
||||
'start' => $end->copy()->utc()->subSeconds($durationInSeconds),
|
||||
'end' => $end->copy()->utc(),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public function start(Carbon $start): self
|
||||
{
|
||||
return $this->state(function (array $attributes) use ($start): array {
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
<?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::table('oauth_access_tokens', function (Blueprint $table): void {
|
||||
$table->dateTime('reminder_sent_at')->nullable();
|
||||
$table->dateTime('expired_info_sent_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('oauth_access_tokens', function (Blueprint $table): void {
|
||||
$table->dropColumn('reminder_sent_at');
|
||||
$table->dropColumn('expired_info_sent_at');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
<?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::table('organizations', function (Blueprint $table): void {
|
||||
$table->boolean('prevent_overlapping_time_entries')->default(false)->after('employees_can_see_billable_rates');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('organizations', function (Blueprint $table): void {
|
||||
$table->dropColumn('prevent_overlapping_time_entries');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
<?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::table('time_entries', function (Blueprint $table): void {
|
||||
$table->string('description', 5000)->change();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('time_entries', function (Blueprint $table): void {
|
||||
$table->string('description', 500)->change();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
<?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::table('organizations', function (Blueprint $table): void {
|
||||
$table->boolean('employees_can_manage_tasks')->default(false)->after('employees_can_see_billable_rates');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('organizations', function (Blueprint $table): void {
|
||||
$table->dropColumn('employees_can_manage_tasks');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -435,7 +435,7 @@ CREATE TABLE public.tasks (
|
||||
|
||||
CREATE TABLE public.time_entries (
|
||||
id uuid NOT NULL,
|
||||
description character varying(5000) NOT NULL,
|
||||
description character varying(500) NOT NULL,
|
||||
start timestamp(0) without time zone NOT NULL,
|
||||
"end" timestamp(0) without time zone,
|
||||
billable_rate integer,
|
||||
|
||||
@@ -5,6 +5,8 @@ services:
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
WWWGROUP: '${WWWGROUP}'
|
||||
ports:
|
||||
- '${FORWARD_WEB_PORT:-8083}:80'
|
||||
image: sail-8.3/app
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
@@ -107,7 +109,7 @@ services:
|
||||
- sail
|
||||
- reverse-proxy
|
||||
playwright:
|
||||
image: mcr.microsoft.com/playwright:v1.58.1-jammy
|
||||
image: mcr.microsoft.com/playwright:v1.51.1-jammy
|
||||
command: ['npx', 'playwright', 'test', '--ui-port=8080', '--ui-host=0.0.0.0']
|
||||
working_dir: /src
|
||||
extra_hosts:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# Source: https://helgesver.re/articles/laravel-sail-create-minio-bucket-automatically
|
||||
|
||||
/usr/bin/mc alias set local ${S3_ENDPOINT} ${S3_ACCESS_KEY_ID} ${S3_SECRET_ACCESS_KEY};
|
||||
/usr/bin/mc config host add local ${S3_ENDPOINT} ${S3_ACCESS_KEY_ID} ${S3_SECRET_ACCESS_KEY};
|
||||
/usr/bin/mc rm -r --force local/${S3_BUCKET};
|
||||
/usr/bin/mc mb --ignore-existing local/${S3_BUCKET};
|
||||
/usr/bin/mc anonymous set public local/${S3_BUCKET};
|
||||
|
||||
@@ -16,7 +16,7 @@ RUN CGO_ENABLED=1 \
|
||||
XCADDY_GO_BUILD_FLAGS="-ldflags='-w -s' -tags=nobadger,nomysql,nopgx" \
|
||||
CGO_CFLAGS=$(php-config --includes) \
|
||||
CGO_LDFLAGS="$(php-config --ldflags) $(php-config --libs)" \
|
||||
xcaddy build v2.10.0 \
|
||||
xcaddy build \
|
||||
--output /usr/local/bin/frankenphp \
|
||||
--with github.com/dunglas/frankenphp=./ \
|
||||
--with github.com/dunglas/frankenphp/caddy=./caddy/ \
|
||||
|
||||
189
e2e/auth.spec.ts
189
e2e/auth.spec.ts
@@ -1,6 +1,5 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { getPasswordResetUrl } from './utils/mailpit';
|
||||
|
||||
async function registerNewUser(page, email, password) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/register');
|
||||
@@ -36,198 +35,14 @@ test('can register and delete account', async ({ page }) => {
|
||||
await registerNewUser(page, email, password);
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
await page.getByRole('button', { name: 'Delete Account' }).click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
await page.getByPlaceholder('Password').fill(password);
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'Delete Account' }).click();
|
||||
await page.getByRole('button', { name: 'Delete Account' }).click();
|
||||
await page.waitForURL(PLAYWRIGHT_BASE_URL + '/login');
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/login');
|
||||
await page.getByLabel('Email').fill(email);
|
||||
await page.getByLabel('Password').fill(password);
|
||||
await page.getByRole('button', { name: 'Log in' }).click();
|
||||
await expect(page.getByRole('alert')).toContainText(
|
||||
await expect(page.getByRole('paragraph')).toContainText(
|
||||
'These credentials do not match our records.'
|
||||
);
|
||||
});
|
||||
|
||||
test('shows error for invalid email on forgot password', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/forgot-password');
|
||||
|
||||
// Request password reset with non-existent email
|
||||
await page.getByLabel('Email').fill('nonexistent@example.com');
|
||||
await page.getByRole('button', { name: 'Email Password Reset Link' }).click();
|
||||
|
||||
// Should show error message
|
||||
await expect(page.getByText("We can't find a user with that email address.")).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows browser validation for invalid email format on forgot password', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/forgot-password');
|
||||
|
||||
// Request password reset with invalid email format
|
||||
const emailInput = page.getByLabel('Email');
|
||||
await emailInput.fill('notanemail');
|
||||
|
||||
// Check for browser validation - the input should be invalid
|
||||
const isInvalid = await emailInput.evaluate((el: HTMLInputElement) => !el.validity.valid);
|
||||
expect(isInvalid).toBe(true);
|
||||
});
|
||||
|
||||
test('shows browser validation for empty email on forgot password', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/forgot-password');
|
||||
|
||||
// The email input is required, so it should be invalid when empty
|
||||
const emailInput = page.getByLabel('Email');
|
||||
|
||||
// Check for browser validation - the input should be invalid because it's required and empty
|
||||
const isInvalid = await emailInput.evaluate((el: HTMLInputElement) => el.validity.valueMissing);
|
||||
expect(isInvalid).toBe(true);
|
||||
});
|
||||
|
||||
test('can reset password via email link', async ({ page, request }) => {
|
||||
// First register a new user
|
||||
const email = `john+${Math.round(Math.random() * 10000)}@doe.com`;
|
||||
const originalPassword = 'suchagreatpassword123';
|
||||
const newPassword = 'mynewsecurepassword456';
|
||||
await registerNewUser(page, email, originalPassword);
|
||||
|
||||
// Log out
|
||||
await page.getByTestId('current_user_button').click();
|
||||
await page.getByText('Log Out').click();
|
||||
await page.waitForURL(PLAYWRIGHT_BASE_URL + '/login');
|
||||
|
||||
// Request password reset
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/forgot-password');
|
||||
await page.getByLabel('Email').fill(email);
|
||||
await page.getByRole('button', { name: 'Email Password Reset Link' }).click();
|
||||
await expect(page.getByText('We have emailed your password reset link.')).toBeVisible();
|
||||
|
||||
// Get password reset URL from email
|
||||
const resetUrl = await getPasswordResetUrl(request, email);
|
||||
|
||||
// Navigate to reset page
|
||||
await page.goto(resetUrl);
|
||||
|
||||
// Fill in new password
|
||||
await page.getByLabel('Password', { exact: true }).fill(newPassword);
|
||||
await page.getByLabel('Confirm Password').fill(newPassword);
|
||||
await page.getByRole('button', { name: 'Reset Password' }).click();
|
||||
|
||||
// Should redirect to login page after successful reset
|
||||
await page.waitForURL(PLAYWRIGHT_BASE_URL + '/login');
|
||||
|
||||
// Try logging in with new password
|
||||
await page.getByLabel('Email').fill(email);
|
||||
await page.getByLabel('Password').fill(newPassword);
|
||||
await page.getByRole('button', { name: 'Log in' }).click();
|
||||
await expect(page.getByTestId('dashboard_view')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows validation error for password mismatch on reset', async ({ page, request }) => {
|
||||
// First register a new user
|
||||
const email = `john+${Math.round(Math.random() * 10000)}@doe.com`;
|
||||
const originalPassword = 'suchagreatpassword123';
|
||||
await registerNewUser(page, email, originalPassword);
|
||||
|
||||
// Log out
|
||||
await page.getByTestId('current_user_button').click();
|
||||
await page.getByText('Log Out').click();
|
||||
await page.waitForURL(PLAYWRIGHT_BASE_URL + '/login');
|
||||
|
||||
// Request password reset
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/forgot-password');
|
||||
await page.getByLabel('Email').fill(email);
|
||||
await page.getByRole('button', { name: 'Email Password Reset Link' }).click();
|
||||
await expect(page.getByText('We have emailed your password reset link.')).toBeVisible();
|
||||
|
||||
// Get password reset URL from email
|
||||
const resetUrl = await getPasswordResetUrl(request, email);
|
||||
|
||||
// Navigate to reset page
|
||||
await page.goto(resetUrl);
|
||||
|
||||
// Fill in mismatched passwords
|
||||
await page.getByLabel('Password', { exact: true }).fill('newpassword123');
|
||||
await page.getByLabel('Confirm Password').fill('differentpassword456');
|
||||
await page.getByRole('button', { name: 'Reset Password' }).click();
|
||||
|
||||
// Should show validation error
|
||||
await expect(page.getByText('The password field confirmation does not match.')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows validation error for short password on reset', async ({ page, request }) => {
|
||||
// First register a new user
|
||||
const email = `john+${Math.round(Math.random() * 10000)}@doe.com`;
|
||||
const originalPassword = 'suchagreatpassword123';
|
||||
await registerNewUser(page, email, originalPassword);
|
||||
|
||||
// Log out
|
||||
await page.getByTestId('current_user_button').click();
|
||||
await page.getByText('Log Out').click();
|
||||
await page.waitForURL(PLAYWRIGHT_BASE_URL + '/login');
|
||||
|
||||
// Request password reset
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/forgot-password');
|
||||
await page.getByLabel('Email').fill(email);
|
||||
await page.getByRole('button', { name: 'Email Password Reset Link' }).click();
|
||||
await expect(page.getByText('We have emailed your password reset link.')).toBeVisible();
|
||||
|
||||
// Get password reset URL from email
|
||||
const resetUrl = await getPasswordResetUrl(request, email);
|
||||
|
||||
// Navigate to reset page
|
||||
await page.goto(resetUrl);
|
||||
|
||||
// Fill in short password
|
||||
await page.getByLabel('Password', { exact: true }).fill('short');
|
||||
await page.getByLabel('Confirm Password').fill('short');
|
||||
await page.getByRole('button', { name: 'Reset Password' }).click();
|
||||
|
||||
// Should show validation error about minimum length
|
||||
await expect(page.getByText('must be at least')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows error for invalid login credentials', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/login');
|
||||
await page.getByLabel('Email').fill('nonexistent@example.com');
|
||||
await page.getByLabel('Password').fill('wrongpassword123');
|
||||
await page.getByRole('button', { name: 'Log in' }).click();
|
||||
|
||||
await expect(page.getByText('These credentials do not match our records.')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows error when registering with existing email', async ({ page }) => {
|
||||
const email = `john+${Math.round(Math.random() * 10000)}@doe.com`;
|
||||
const password = 'suchagreatpassword123';
|
||||
|
||||
// Register first user
|
||||
await registerNewUser(page, email, password);
|
||||
|
||||
// Log out
|
||||
await page.getByTestId('current_user_button').click();
|
||||
await page.getByText('Log Out').click();
|
||||
await page.waitForURL(PLAYWRIGHT_BASE_URL + '/login');
|
||||
|
||||
// Try to register with the same email
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/register');
|
||||
await page.getByLabel('Name').fill('Another User');
|
||||
await page.getByLabel('Email').fill(email);
|
||||
await page.getByLabel('Password', { exact: true }).fill(password);
|
||||
await page.getByLabel('Confirm Password').fill(password);
|
||||
await page.getByLabel('I agree to the Terms of').click();
|
||||
await page.getByRole('button', { name: 'Register' }).click();
|
||||
|
||||
// Should show error about email already taken
|
||||
await expect(page.getByText('The resource already exists.')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows validation error for weak password on registration', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/register');
|
||||
await page.getByLabel('Name').fill('Weak Password User');
|
||||
await page.getByLabel('Email').fill(`weak+${Math.round(Math.random() * 10000)}@test.com`);
|
||||
await page.getByLabel('Password', { exact: true }).fill('short');
|
||||
await page.getByLabel('Confirm Password').fill('short');
|
||||
await page.getByLabel('I agree to the Terms of').click();
|
||||
await page.getByRole('button', { name: 'Register' }).click();
|
||||
|
||||
await expect(page.getByText('must be at least')).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -1,326 +0,0 @@
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { test } from '../playwright/fixtures';
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import {
|
||||
createBillableProjectViaApi,
|
||||
createProjectViaApi,
|
||||
createBareTimeEntryViaApi,
|
||||
createTimeEntryViaApi,
|
||||
} from './utils/api';
|
||||
|
||||
async function goToCalendar(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/calendar');
|
||||
}
|
||||
|
||||
/**
|
||||
* These tests verify that changing the project on a time entry via the calendar
|
||||
* updates the billable status to match the new project's is_billable setting.
|
||||
*
|
||||
* Issue: https://github.com/solidtime-io/solidtime/issues/981
|
||||
*/
|
||||
|
||||
test('test that changing project in calendar edit modal from non-billable to billable updates billable status', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const billableProjectName = 'Billable Cal Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
|
||||
await createBillableProjectViaApi(ctx, { name: billableProjectName });
|
||||
await createBareTimeEntryViaApi(ctx, 'Test billable calendar', '1h');
|
||||
|
||||
await goToCalendar(page);
|
||||
|
||||
// Click on the time entry event in the calendar
|
||||
await page.locator('.fc-event').filter({ hasText: 'Test billable calendar' }).first().click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Verify initially non-billable
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Non-Billable' })
|
||||
).toBeVisible();
|
||||
|
||||
// Select the billable project
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'No Project' }).click();
|
||||
await page.getByRole('option', { name: billableProjectName }).click();
|
||||
|
||||
// Verify the billable dropdown updated to Billable
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Billable' })
|
||||
).toBeVisible();
|
||||
|
||||
// Save and verify
|
||||
const [updateResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('button', { name: 'Update Time Entry' }).click(),
|
||||
]);
|
||||
const responseBody = await updateResponse.json();
|
||||
expect(responseBody.data.billable).toBe(true);
|
||||
});
|
||||
|
||||
test('test that changing project in calendar edit modal from billable to non-billable updates billable status', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const billableProjectName = 'Billable Cal Rev Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
const nonBillableProjectName =
|
||||
'NonBillable Cal Rev Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
|
||||
await createBillableProjectViaApi(ctx, { name: billableProjectName });
|
||||
await createProjectViaApi(ctx, { name: nonBillableProjectName });
|
||||
await createBareTimeEntryViaApi(ctx, 'Test billable cal reverse', '1h');
|
||||
|
||||
await goToCalendar(page);
|
||||
|
||||
// Click on the time entry event in the calendar
|
||||
await page
|
||||
.locator('.fc-event')
|
||||
.filter({ hasText: 'Test billable cal reverse' })
|
||||
.first()
|
||||
.click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// First assign the billable project
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'No Project' }).click();
|
||||
await page.getByRole('option', { name: billableProjectName }).click();
|
||||
|
||||
// Verify billable status flipped to Billable
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Billable' })
|
||||
).toBeVisible();
|
||||
|
||||
// Now switch to the non-billable project
|
||||
await page.getByRole('dialog').getByRole('button', { name: billableProjectName }).click();
|
||||
await page.getByRole('option', { name: nonBillableProjectName }).click();
|
||||
|
||||
// Verify billable status reverted to Non-Billable
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Non-Billable' })
|
||||
).toBeVisible();
|
||||
|
||||
// Save and verify
|
||||
const [updateResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('button', { name: 'Update Time Entry' }).click(),
|
||||
]);
|
||||
const responseBody = await updateResponse.json();
|
||||
expect(responseBody.data.billable).toBe(false);
|
||||
});
|
||||
|
||||
test('test that opening calendar edit modal for a time entry with manually overridden billable status preserves that status', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const billableProjectName =
|
||||
'Billable Cal Persist Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
|
||||
await createBillableProjectViaApi(ctx, { name: billableProjectName });
|
||||
await createBareTimeEntryViaApi(ctx, 'Test cal persist override', '1h');
|
||||
|
||||
await goToCalendar(page);
|
||||
|
||||
// Click on the time entry event in the calendar
|
||||
await page
|
||||
.locator('.fc-event')
|
||||
.filter({ hasText: 'Test cal persist override' })
|
||||
.first()
|
||||
.click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Assign the billable project
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'No Project' }).click();
|
||||
await page.getByRole('option', { name: billableProjectName }).click();
|
||||
|
||||
// Verify it auto-set to Billable
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Billable' })
|
||||
).toBeVisible();
|
||||
|
||||
// Now manually override billable to Non-Billable via the dropdown
|
||||
await page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Billable' }).click();
|
||||
await page.getByRole('option', { name: 'Non Billable' }).click();
|
||||
|
||||
// Verify it shows Non-Billable now
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Non-Billable' })
|
||||
).toBeVisible();
|
||||
|
||||
// Save
|
||||
const [firstSaveResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('button', { name: 'Update Time Entry' }).click(),
|
||||
]);
|
||||
const firstBody = await firstSaveResponse.json();
|
||||
expect(firstBody.data.billable).toBe(false);
|
||||
|
||||
// Re-open the edit modal from the calendar — the project_id watcher should NOT override billable
|
||||
await page
|
||||
.locator('.fc-event')
|
||||
.filter({ hasText: 'Test cal persist override' })
|
||||
.first()
|
||||
.click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// The billable dropdown should still show Non-Billable
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Non-Billable' })
|
||||
).toBeVisible();
|
||||
|
||||
// Save without changes and verify the response still has billable=false
|
||||
const [updateResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('button', { name: 'Update Time Entry' }).click(),
|
||||
]);
|
||||
const responseBody = await updateResponse.json();
|
||||
expect(responseBody.data.billable).toBe(false);
|
||||
});
|
||||
|
||||
test('test that calendar page loads and displays time entries', async ({ page, ctx }) => {
|
||||
await createBareTimeEntryViaApi(ctx, 'Calendar display test', '1h');
|
||||
|
||||
await goToCalendar(page);
|
||||
|
||||
// Calendar container should be visible
|
||||
await expect(page.locator('.fc')).toBeVisible();
|
||||
|
||||
// The time entry should appear as a calendar event
|
||||
await expect(
|
||||
page.locator('.fc-event').filter({ hasText: 'Calendar display test' }).first()
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that calendar navigation buttons work', async ({ page }) => {
|
||||
await goToCalendar(page);
|
||||
await expect(page.locator('.fc')).toBeVisible();
|
||||
|
||||
// Click the "next" button to navigate forward
|
||||
await page.locator('button.fc-next-button').click();
|
||||
await expect(page.locator('.fc')).toBeVisible();
|
||||
|
||||
// Click the "prev" button to navigate back
|
||||
await page.locator('button.fc-prev-button').click();
|
||||
await expect(page.locator('.fc')).toBeVisible();
|
||||
|
||||
// Navigate forward first so "today" button becomes enabled, then click it
|
||||
await page.locator('button.fc-next-button').click();
|
||||
await page.locator('button.fc-today-button').click();
|
||||
await expect(page.locator('.fc')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that editing time entry description via calendar modal works', async ({ page, ctx }) => {
|
||||
const originalDescription = 'Edit me in calendar ' + Math.floor(1 + Math.random() * 10000);
|
||||
const updatedDescription = 'Updated in calendar ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createBareTimeEntryViaApi(ctx, originalDescription, '1h');
|
||||
|
||||
await goToCalendar(page);
|
||||
|
||||
// Click on the time entry event
|
||||
await page.locator('.fc-event').filter({ hasText: originalDescription }).first().click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Update the description (edit modal uses placeholder, not data-testid)
|
||||
const descriptionInput = page.getByRole('dialog').getByPlaceholder('What did you work on?');
|
||||
await descriptionInput.fill(updatedDescription);
|
||||
|
||||
// Save and verify
|
||||
const [editResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('button', { name: 'Update Time Entry' }).click(),
|
||||
]);
|
||||
const editBody = await editResponse.json();
|
||||
expect(editBody.data.description).toBe(updatedDescription);
|
||||
|
||||
// Verify the updated description is shown in the calendar UI
|
||||
await expect(
|
||||
page.locator('.fc-event').filter({ hasText: updatedDescription }).first()
|
||||
).toBeVisible();
|
||||
// Verify the old description is no longer shown
|
||||
await expect(
|
||||
page.locator('.fc-event').filter({ hasText: originalDescription })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that deleting time entry from calendar modal works', async ({ page, ctx }) => {
|
||||
const description = 'Delete me from calendar ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createBareTimeEntryViaApi(ctx, description, '1h');
|
||||
|
||||
await goToCalendar(page);
|
||||
|
||||
// Click on the time entry event
|
||||
await page.locator('.fc-event').filter({ hasText: description }).first().click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Click the delete button
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/') &&
|
||||
response.request().method() === 'DELETE' &&
|
||||
response.status() === 204
|
||||
),
|
||||
page.getByRole('dialog').getByRole('button', { name: 'Delete' }).click(),
|
||||
]);
|
||||
|
||||
// Verify the event is removed from the calendar
|
||||
await expect(page.locator('.fc-event').filter({ hasText: description })).not.toBeVisible();
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Calendar Isolation', () => {
|
||||
test('employee can only see their own time entries on the calendar', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
// Owner creates a time entry for today
|
||||
const ownerDescription = 'OwnerCalEntry ' + Math.floor(Math.random() * 10000);
|
||||
await createBareTimeEntryViaApi(ctx, ownerDescription, '1h');
|
||||
|
||||
// Create a time entry for the employee for today
|
||||
const employeeDescription = 'EmpCalEntry ' + Math.floor(Math.random() * 10000);
|
||||
await createTimeEntryViaApi(
|
||||
{ ...ctx, memberId: employee.memberId },
|
||||
{ description: employeeDescription, duration: '30min' }
|
||||
);
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/calendar');
|
||||
await expect(employee.page.locator('.fc')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Employee's event IS visible
|
||||
await expect(
|
||||
employee.page.locator('.fc-event').filter({ hasText: employeeDescription }).first()
|
||||
).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Owner's event is NOT visible
|
||||
await expect(
|
||||
employee.page.locator('.fc-event').filter({ hasText: ownerDescription })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -1,23 +1,18 @@
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, Page } from '@playwright/test';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { test } from '../playwright/fixtures';
|
||||
import {
|
||||
createClientViaApi,
|
||||
createProjectMemberViaApi,
|
||||
createProjectViaApi,
|
||||
createPublicProjectViaApi,
|
||||
} from './utils/api';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
|
||||
async function goToClientsOverview(page: Page) {
|
||||
async function goToProjectsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/clients');
|
||||
}
|
||||
|
||||
// Create new client via modal
|
||||
test('test that creating and deleting a new client via the modal works', async ({ page }) => {
|
||||
const newClientName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToClientsOverview(page);
|
||||
// Create new project via modal
|
||||
test('test that creating and deleting a new client via the modal works', async ({
|
||||
page,
|
||||
}) => {
|
||||
const newClientName =
|
||||
'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Client' }).click();
|
||||
await page.getByPlaceholder('Client Name').fill(newClientName);
|
||||
await Promise.all([
|
||||
@@ -33,9 +28,13 @@ test('test that creating and deleting a new client via the modal works', async (
|
||||
]);
|
||||
|
||||
await expect(page.getByTestId('client_table')).toContainText(newClientName);
|
||||
const moreButton = page.locator("[aria-label='Actions for Client " + newClientName + "']");
|
||||
await moreButton.click();
|
||||
const deleteButton = page.locator("[aria-label='Delete Client " + newClientName + "']");
|
||||
const moreButton = page.locator(
|
||||
"[aria-label='Actions for Client " + newClientName + "']"
|
||||
);
|
||||
moreButton.click();
|
||||
const deleteButton = page.locator(
|
||||
"[aria-label='Delete Client " + newClientName + "']"
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
deleteButton.click(),
|
||||
@@ -46,14 +45,18 @@ test('test that creating and deleting a new client via the modal works', async (
|
||||
response.status() === 204
|
||||
),
|
||||
]);
|
||||
await expect(page.getByTestId('client_table')).not.toContainText(newClientName);
|
||||
await expect(page.getByTestId('client_table')).not.toContainText(
|
||||
newClientName
|
||||
);
|
||||
});
|
||||
|
||||
test('test that archiving and unarchiving clients works', async ({ page, ctx }) => {
|
||||
test('test that archiving and unarchiving clients works', async ({ page }) => {
|
||||
const newClientName = 'New Client ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createClientViaApi(ctx, { name: newClientName });
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Client' }).click();
|
||||
await page.getByLabel('Client Name').fill(newClientName);
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Client' }).click();
|
||||
await expect(page.getByText(newClientName)).toBeVisible();
|
||||
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
@@ -77,226 +80,4 @@ test('test that archiving and unarchiving clients works', async ({ page, ctx })
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that editing a client name works', async ({ page, ctx }) => {
|
||||
const originalName = 'Original Client ' + Math.floor(1 + Math.random() * 10000);
|
||||
const updatedName = 'Updated Client ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createClientViaApi(ctx, { name: originalName });
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await expect(page.getByText(originalName)).toBeVisible();
|
||||
|
||||
// Open edit modal via actions menu
|
||||
const moreButton = page.locator("[aria-label='Actions for Client " + originalName + "']");
|
||||
await moreButton.click();
|
||||
await page.getByTestId('client_edit').click();
|
||||
|
||||
// Update the client name
|
||||
await page.getByPlaceholder('Client Name').fill(updatedName);
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Update Client' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/clients') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify updated name is shown and old name is gone
|
||||
await expect(page.getByTestId('client_table')).toContainText(updatedName);
|
||||
await expect(page.getByTestId('client_table')).not.toContainText(originalName);
|
||||
});
|
||||
|
||||
test('test that deleting a client via actions menu works', async ({ page, ctx }) => {
|
||||
const clientName = 'DeleteMe Client ' + Math.floor(1 + Math.random() * 10000);
|
||||
|
||||
await createClientViaApi(ctx, { name: clientName });
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await expect(page.getByTestId('client_table')).toContainText(clientName);
|
||||
|
||||
const moreButton = page.locator("[aria-label='Actions for Client " + clientName + "']");
|
||||
await moreButton.click();
|
||||
const deleteButton = page.locator("[aria-label='Delete Client " + clientName + "']");
|
||||
|
||||
await Promise.all([
|
||||
deleteButton.click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/clients') &&
|
||||
response.request().method() === 'DELETE' &&
|
||||
response.status() === 204
|
||||
),
|
||||
]);
|
||||
|
||||
await expect(page.getByTestId('client_table')).not.toContainText(clientName);
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Sorting Tests
|
||||
// =============================================
|
||||
|
||||
async function clearClientTableState(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
localStorage.removeItem('client-table-state');
|
||||
});
|
||||
}
|
||||
|
||||
test('test that sorting clients by name and status works', async ({ page, ctx }) => {
|
||||
await createClientViaApi(ctx, { name: 'AAA SortClient' });
|
||||
await createClientViaApi(ctx, { name: 'ZZZ SortClient' });
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// -- Name sorting (default is name asc) --
|
||||
let names = await getTableRowNames(table);
|
||||
expect(names.indexOf('AAA SortClient')).toBeLessThan(names.indexOf('ZZZ SortClient'));
|
||||
|
||||
const nameHeader = table.getByText('Name').first();
|
||||
await nameHeader.click(); // toggle to desc
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('ZZZ SortClient')).toBeLessThan(names.indexOf('AAA SortClient'));
|
||||
|
||||
// -- Status sorting --
|
||||
const statusHeader = table.getByText('Status').first();
|
||||
await statusHeader.click(); // asc
|
||||
await expect(statusHeader.locator('svg')).toBeVisible();
|
||||
await statusHeader.click(); // desc
|
||||
await expect(statusHeader.locator('svg')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that sorting clients by project count works', async ({ page, ctx }) => {
|
||||
const clientWithMany = await createClientViaApi(ctx, { name: 'ManyProjects Client' });
|
||||
const clientWithNone = await createClientViaApi(ctx, { name: 'NoProjects Client' });
|
||||
|
||||
// Create projects for the first client
|
||||
await createProjectViaApi(ctx, { name: 'Proj1', client_id: clientWithMany.id });
|
||||
await createProjectViaApi(ctx, { name: 'Proj2', client_id: clientWithMany.id });
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// Click Projects header - first click should sort desc (most projects first)
|
||||
const projectsHeader = table.getByText('Projects').first();
|
||||
await projectsHeader.click();
|
||||
await expect(projectsHeader.locator('svg')).toBeVisible();
|
||||
let names = await getTableRowNames(table);
|
||||
expect(names.indexOf('ManyProjects Client')).toBeLessThan(names.indexOf('NoProjects Client'));
|
||||
|
||||
// Second click toggles to asc (least projects first)
|
||||
await projectsHeader.click();
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('NoProjects Client')).toBeLessThan(names.indexOf('ManyProjects Client'));
|
||||
});
|
||||
|
||||
test('test that client sort state persists after page reload', async ({ page }) => {
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
const nameHeader = table.getByText('Name').first();
|
||||
await nameHeader.click(); // toggle to desc
|
||||
await expect(nameHeader.locator('svg')).toBeVisible();
|
||||
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId('client_table')).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId('client_table').getByText('Name').first().locator('svg')
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Clients Restrictions', () => {
|
||||
test('employee can view clients but cannot create', async ({ ctx, employee }) => {
|
||||
// Create a client with a public project so the employee can see the client
|
||||
const clientName = 'EmpViewClient ' + Math.floor(Math.random() * 10000);
|
||||
const client = await createClientViaApi(ctx, { name: clientName });
|
||||
await createPublicProjectViaApi(ctx, { name: 'EmpClientProj', client_id: client.id });
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/clients');
|
||||
await expect(employee.page.getByTestId('clients_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Employee can see the client
|
||||
await expect(employee.page.getByText(clientName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Employee cannot see Create Client button
|
||||
await expect(
|
||||
employee.page.getByRole('button', { name: 'Create Client' })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee cannot see edit/delete/archive actions on clients', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
const clientName = 'EmpActionsClient ' + Math.floor(Math.random() * 10000);
|
||||
const client = await createClientViaApi(ctx, { name: clientName });
|
||||
await createPublicProjectViaApi(ctx, { name: 'EmpClientActProj', client_id: client.id });
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/clients');
|
||||
await expect(employee.page.getByText(clientName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click the actions dropdown trigger to open the menu
|
||||
const actionsButton = employee.page.locator(
|
||||
`[aria-label='Actions for Client ${clientName}']`
|
||||
);
|
||||
await actionsButton.click();
|
||||
|
||||
// The dropdown menu items (Edit, Archive, Delete) should NOT be visible
|
||||
await expect(
|
||||
employee.page.locator(`[aria-label='Edit Client ${clientName}']`)
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.locator(`[aria-label='Archive Client ${clientName}']`)
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.locator(`[aria-label='Delete Client ${clientName}']`)
|
||||
).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee can see client when they are a member of its private project', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
const clientName = 'EmpPrivateClient ' + Math.floor(Math.random() * 10000);
|
||||
const client = await createClientViaApi(ctx, { name: clientName });
|
||||
|
||||
// Create a private project under this client
|
||||
const project = await createProjectViaApi(ctx, {
|
||||
name: 'PrivateProj',
|
||||
client_id: client.id,
|
||||
is_public: false,
|
||||
});
|
||||
|
||||
// Add the employee as a project member
|
||||
await createProjectMemberViaApi(ctx, project.id, {
|
||||
member_id: employee.memberId,
|
||||
});
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/clients');
|
||||
await expect(employee.page.getByTestId('clients_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Employee can see the client because they are a member of its private project
|
||||
await expect(employee.page.getByText(clientName)).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
});
|
||||
// TODO: Add Name Update Test
|
||||
|
||||
@@ -1,474 +0,0 @@
|
||||
import { expect, test } from '../playwright/fixtures';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import type { Page } from '@playwright/test';
|
||||
|
||||
const TIMER_BUTTON_SELECTOR = '[data-testid="dashboard_timer"] [data-testid="timer_button"]';
|
||||
|
||||
async function goToDashboard(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
}
|
||||
|
||||
async function openCommandPalette(page: Page) {
|
||||
await page.getByTestId('command_palette_button').click();
|
||||
await expect(page.locator('[role="dialog"]')).toBeVisible({ timeout: 5000 });
|
||||
}
|
||||
|
||||
async function closeCommandPalette(page: Page) {
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('[role="dialog"]')).not.toBeVisible();
|
||||
}
|
||||
|
||||
async function searchInCommandPalette(page: Page, query: string) {
|
||||
await page.locator('[role="dialog"] input').fill(query);
|
||||
// Wait for search debounce to settle (command palette uses a debounced search)
|
||||
await page.waitForTimeout(300);
|
||||
}
|
||||
|
||||
async function selectCommand(page: Page, name: string) {
|
||||
const option = page.getByRole('option', { name, exact: true });
|
||||
await option.scrollIntoViewIfNeeded();
|
||||
await option.click();
|
||||
}
|
||||
|
||||
async function assertTimerIsRunning(page: Page) {
|
||||
await expect(page.locator(TIMER_BUTTON_SELECTOR).and(page.locator(':visible'))).toHaveClass(
|
||||
/bg-red-400\/80/,
|
||||
{
|
||||
timeout: 10000,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
async function assertTimerIsStopped(page: Page) {
|
||||
await expect(page.locator(TIMER_BUTTON_SELECTOR).and(page.locator(':visible'))).toHaveClass(
|
||||
/bg-accent-300\/70/,
|
||||
{
|
||||
timeout: 10000,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
test.describe('Command Palette', () => {
|
||||
test.describe('Opening and Closing', () => {
|
||||
test('opens via search button and closes with Escape', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await expect(
|
||||
page.locator('[role="dialog"] input[placeholder*="command"]')
|
||||
).toBeVisible();
|
||||
|
||||
await closeCommandPalette(page);
|
||||
await expect(page.locator('[role="dialog"]')).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('opens with keyboard shortcut', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
// Click on body to ensure page has focus
|
||||
await page.locator('body').click();
|
||||
// Use ControlOrMeta which resolves to Ctrl on Linux/Windows and Meta on macOS
|
||||
await page.keyboard.press('ControlOrMeta+k');
|
||||
await expect(page.locator('[role="dialog"]')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test('clears search on close', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'dashboard');
|
||||
await closeCommandPalette(page);
|
||||
|
||||
await openCommandPalette(page);
|
||||
await expect(page.locator('[role="dialog"] input')).toHaveValue('');
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Command Display', () => {
|
||||
test('displays navigation and timer commands', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
|
||||
// Navigation commands
|
||||
await expect(page.getByRole('option', { name: 'Go to Dashboard' })).toBeVisible();
|
||||
await expect(page.getByRole('option', { name: 'Go to Time' })).toBeVisible();
|
||||
await expect(page.getByRole('option', { name: 'Go to Calendar' })).toBeVisible();
|
||||
|
||||
// Timer commands
|
||||
await expect(page.getByRole('option', { name: 'Start Timer' })).toBeVisible();
|
||||
await expect(page.getByRole('option', { name: 'Create Time Entry' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('displays create commands', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
|
||||
await expect(page.getByRole('option', { name: 'Create Project' })).toBeVisible();
|
||||
await expect(page.getByRole('option', { name: 'Create Client' })).toBeVisible();
|
||||
await expect(page.getByRole('option', { name: 'Create Tag' })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Navigation Commands', () => {
|
||||
// Tests use element visibility assertions for consistency with codebase patterns
|
||||
const navigationTests = [
|
||||
['Go to Dashboard', 'dashboard_view', '/time'],
|
||||
['Go to Time', 'time_view', '/dashboard'],
|
||||
['Go to Calendar', 'calendar_view', '/dashboard'],
|
||||
['Go to Projects', 'projects_view', '/dashboard'],
|
||||
['Go to Clients', 'clients_view', '/dashboard'],
|
||||
['Go to Members', 'members_view', '/dashboard'],
|
||||
['Go to Tags', 'tags_view', '/dashboard'],
|
||||
] as const;
|
||||
|
||||
for (const [commandName, expectedTestId, startUrl] of navigationTests) {
|
||||
test(`${commandName}`, async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + startUrl);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, commandName.replace('Go to ', ''));
|
||||
await selectCommand(page, commandName);
|
||||
await expect(page.getByTestId(expectedTestId)).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
}
|
||||
|
||||
test('Go to Profile', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Profile');
|
||||
await selectCommand(page, 'Go to Profile');
|
||||
// Profile page doesn't have a testId, so check for a unique element
|
||||
await expect(page.getByRole('heading', { name: 'Profile Information' })).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
});
|
||||
|
||||
test('Go to Reporting Overview', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Reporting Overview');
|
||||
await selectCommand(page, 'Go to Reporting Overview');
|
||||
await expect(page.getByTestId('reporting_view')).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
|
||||
test('Go to Settings', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Settings');
|
||||
await selectCommand(page, 'Go to Settings');
|
||||
// Settings page uses team settings which has an h3 heading
|
||||
await expect(
|
||||
page.getByRole('heading', { name: 'Organization Name', level: 3 })
|
||||
).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Search and Filtering', () => {
|
||||
test('filters commands when searching', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
|
||||
await searchInCommandPalette(page, 'dashboard');
|
||||
await expect(page.getByRole('option', { name: 'Go to Dashboard' })).toBeVisible();
|
||||
|
||||
await searchInCommandPalette(page, 'calendar');
|
||||
await expect(page.getByRole('option', { name: 'Go to Calendar' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('search is case insensitive', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
|
||||
await searchInCommandPalette(page, 'DASHBOARD');
|
||||
await expect(page.getByRole('option', { name: 'Go to Dashboard' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('partial word search works', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
|
||||
await searchInCommandPalette(page, 'proj');
|
||||
await expect(page.getByRole('option', { name: 'Go to Projects' })).toBeVisible();
|
||||
await expect(page.getByRole('option', { name: 'Create Project' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('keyboard navigation and selection works', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('Enter');
|
||||
|
||||
await expect(page.locator('[role="dialog"]')).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Theme Commands', () => {
|
||||
test('switches to dark theme', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Dark Theme');
|
||||
await selectCommand(page, 'Switch to Dark Theme');
|
||||
await expect(page.locator('html')).toHaveClass(/dark/);
|
||||
});
|
||||
|
||||
test('switches to light theme', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Light Theme');
|
||||
await selectCommand(page, 'Switch to Light Theme');
|
||||
await expect(page.locator('html')).toHaveClass(/light/);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Timer Commands', () => {
|
||||
test('starts and stops timer', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
|
||||
// Start timer
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Start Timer');
|
||||
await selectCommand(page, 'Start Timer');
|
||||
await assertTimerIsRunning(page);
|
||||
|
||||
// Stop timer
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Stop Timer');
|
||||
await selectCommand(page, 'Stop Timer');
|
||||
await assertTimerIsStopped(page);
|
||||
});
|
||||
|
||||
test('shows active timer commands when running', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
|
||||
// Start timer
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Start Timer');
|
||||
await selectCommand(page, 'Start Timer');
|
||||
await assertTimerIsRunning(page);
|
||||
|
||||
// Check active timer commands - search for them to ensure visibility
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Set Project');
|
||||
await expect(page.getByRole('option', { name: 'Set Project' })).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Create Commands', () => {
|
||||
test('opens create time entry modal', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Create Time Entry');
|
||||
await selectCommand(page, 'Create Time Entry');
|
||||
await expect(
|
||||
page.locator('[role="dialog"]').getByText('Create manual time entry')
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('opens create project modal', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Create Project');
|
||||
await selectCommand(page, 'Create Project');
|
||||
await expect(
|
||||
page.locator('[role="dialog"]').getByRole('heading', { name: 'Create Project' })
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('opens create client modal', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Create Client');
|
||||
await selectCommand(page, 'Create Client');
|
||||
await expect(
|
||||
page.locator('[role="dialog"]').getByRole('heading', { name: 'Create Client' })
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('opens create tag modal', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Create Tag');
|
||||
await selectCommand(page, 'Create Tag');
|
||||
await expect(page.locator('[role="dialog"]').getByText('Create Tags')).toBeVisible();
|
||||
});
|
||||
|
||||
test('opens invite member modal', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Invite Member');
|
||||
await selectCommand(page, 'Invite Member');
|
||||
// Modal has title with "Invite Member" text - use first() to get the title span
|
||||
await expect(
|
||||
page.locator('[role="dialog"]').getByText('Invite Member').first()
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Entity Search', () => {
|
||||
test('searches for projects and navigates on selection', async ({ page }) => {
|
||||
const projectName = 'CmdPalette' + Math.floor(Math.random() * 10000);
|
||||
|
||||
// Create project first
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByPlaceholder('The next big thing').fill(projectName);
|
||||
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
// Wait for project to be created and page to update
|
||||
await expect(page.getByText(projectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Search from the projects page where the query cache now has the new project
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, projectName);
|
||||
|
||||
// Wait for entity search to return results
|
||||
const projectOption = page.getByRole('option').filter({ hasText: projectName });
|
||||
await expect(projectOption).toBeVisible({
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
// Select the project from search results
|
||||
await projectOption.click();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Organization Switching', () => {
|
||||
test('shows switch commands only when multiple organizations exist', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await openCommandPalette(page);
|
||||
|
||||
// With only one org, no switch commands should appear
|
||||
await searchInCommandPalette(page, 'Switch to');
|
||||
// Check that no organization switch commands appear (only theme switch commands)
|
||||
const switchOptions = page.getByRole('option', { name: /^Switch to (?!.*Theme)/ });
|
||||
await expect(switchOptions).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('switches organization via command palette', async ({ page }) => {
|
||||
const newOrgName = 'TestOrg' + Math.floor(Math.random() * 10000);
|
||||
|
||||
// Create a new organization
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/teams/create');
|
||||
await page.getByLabel('Organization Name').fill(newOrgName);
|
||||
await page.getByRole('button', { name: 'Create' }).click();
|
||||
|
||||
// Wait for navigation to new org's dashboard
|
||||
await expect(page.getByTestId('dashboard_view')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Use visible switcher (desktop sidebar has one, mobile header has another)
|
||||
const orgSwitcher = page.locator('[data-testid="organization_switcher"]:visible');
|
||||
|
||||
// Verify we're in the new org by checking the switcher
|
||||
await expect(orgSwitcher).toContainText(newOrgName);
|
||||
|
||||
// Get the original org name from switcher dropdown
|
||||
await orgSwitcher.click();
|
||||
await expect(page.getByText('Switch Organizations')).toBeVisible();
|
||||
|
||||
// Find the other organization button (has ArrowRightIcon, not CheckCircleIcon)
|
||||
// The button contains an SVG and a div with the org name
|
||||
const otherOrgItem = page.locator('form button').filter({ hasText: /.+/ }).first();
|
||||
await expect(otherOrgItem).toBeVisible();
|
||||
const originalOrgName = (await otherOrgItem.innerText()).trim();
|
||||
await page.keyboard.press('Escape'); // Close dropdown
|
||||
|
||||
// Now use command palette to switch back to original org
|
||||
await openCommandPalette(page);
|
||||
await searchInCommandPalette(page, 'Switch to');
|
||||
|
||||
// Should see the switch command for the original org
|
||||
const switchCommand = page.getByRole('option', {
|
||||
name: new RegExp(`Switch to ${originalOrgName}`),
|
||||
});
|
||||
await expect(switchCommand).toBeVisible();
|
||||
await switchCommand.click();
|
||||
|
||||
// Wait for organization switch to complete
|
||||
await expect(orgSwitcher).toContainText(originalOrgName, {
|
||||
timeout: 10000,
|
||||
});
|
||||
});
|
||||
|
||||
test('organization switch commands appear in Organization group', async ({ page }) => {
|
||||
const newOrgName = 'GroupTestOrg' + Math.floor(Math.random() * 10000);
|
||||
|
||||
// Create a new organization to ensure we have multiple
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/teams/create');
|
||||
await page.getByLabel('Organization Name').fill(newOrgName);
|
||||
await page.getByRole('button', { name: 'Create' }).click();
|
||||
await expect(page.getByTestId('dashboard_view')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Open command palette and check for Organization group heading
|
||||
await openCommandPalette(page);
|
||||
|
||||
// The Organization group should be visible when there are switch commands
|
||||
await expect(page.getByText('Organization', { exact: true })).toBeVisible();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Command Palette Restrictions', () => {
|
||||
test('employee command palette does not show restricted navigation commands', async ({
|
||||
employee,
|
||||
}) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Open command palette
|
||||
await employee.page.getByTestId('command_palette_button').click();
|
||||
await expect(employee.page.locator('[role="dialog"]')).toBeVisible({ timeout: 5000 });
|
||||
|
||||
// Available navigation commands
|
||||
await expect(employee.page.getByRole('option', { name: 'Go to Dashboard' })).toBeVisible();
|
||||
await expect(employee.page.getByRole('option', { name: 'Go to Time' })).toBeVisible();
|
||||
await expect(employee.page.getByRole('option', { name: 'Go to Calendar' })).toBeVisible();
|
||||
|
||||
// Restricted commands should NOT be visible
|
||||
await expect(
|
||||
employee.page.getByRole('option', { name: 'Go to Members' })
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.getByRole('option', { name: 'Go to Settings' })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee command palette does not show create commands for restricted entities', async ({
|
||||
employee,
|
||||
}) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Open command palette
|
||||
await employee.page.getByTestId('command_palette_button').click();
|
||||
await expect(employee.page.locator('[role="dialog"]')).toBeVisible({ timeout: 5000 });
|
||||
|
||||
// Search for "Create" to filter
|
||||
await employee.page.locator('[role="dialog"] input').fill('Create');
|
||||
await employee.page.waitForTimeout(300);
|
||||
|
||||
// Should NOT see create commands for restricted entities
|
||||
await expect(
|
||||
employee.page.getByRole('option', { name: 'Create Project' })
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.getByRole('option', { name: 'Create Client' })
|
||||
).not.toBeVisible();
|
||||
await expect(employee.page.getByRole('option', { name: 'Create Tag' })).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.getByRole('option', { name: 'Invite Member' })
|
||||
).not.toBeVisible();
|
||||
|
||||
// Should still see Create Time Entry (employees can create time entries)
|
||||
await expect(
|
||||
employee.page.getByRole('option', { name: 'Create Time Entry' })
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -1,198 +0,0 @@
|
||||
import { expect, test } from '../playwright/fixtures';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import type { Page } from '@playwright/test';
|
||||
import {
|
||||
assertThatTimerHasStarted,
|
||||
assertThatTimerIsStopped,
|
||||
newTimeEntryResponse,
|
||||
startOrStopTimerWithButton,
|
||||
stoppedTimeEntryResponse,
|
||||
} from './utils/currentTimeEntry';
|
||||
import {
|
||||
createBareTimeEntryViaApi,
|
||||
createPublicProjectViaApi,
|
||||
createTimeEntryViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
|
||||
async function goToDashboard(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
}
|
||||
|
||||
test('test that dashboard loads with all expected sections', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await expect(page.getByTestId('dashboard_view')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Timer section (scoped to dashboard_timer to avoid matching sidebar timer)
|
||||
await expect(page.getByTestId('time_entry_description')).toBeVisible();
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('dashboard_timer')
|
||||
.getByTestId('timer_button')
|
||||
.and(page.locator(':visible'))
|
||||
).toBeVisible();
|
||||
|
||||
// Dashboard cards
|
||||
await expect(page.getByText('Recent Time Entries', { exact: true })).toBeVisible();
|
||||
await expect(page.getByText('Last 7 Days', { exact: true })).toBeVisible();
|
||||
await expect(page.getByText('Activity Graph', { exact: true })).toBeVisible();
|
||||
await expect(page.getByText('Team Activity', { exact: true })).toBeVisible();
|
||||
|
||||
// Weekly overview section
|
||||
await expect(page.getByText('This Week', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that dashboard shows time entry data after creating entries', async ({ page, ctx }) => {
|
||||
await createBareTimeEntryViaApi(ctx, 'Dashboard test entry', '1h');
|
||||
|
||||
await goToDashboard(page);
|
||||
await expect(page.getByTestId('dashboard_view')).toBeVisible();
|
||||
|
||||
// The "Last 7 Days" or "This Week" section should reflect tracked time
|
||||
await expect(page.getByText('This Week', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that timer on dashboard can start and stop', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await Promise.all([newTimeEntryResponse(page), startOrStopTimerWithButton(page)]);
|
||||
await assertThatTimerHasStarted(page);
|
||||
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
await Promise.all([stoppedTimeEntryResponse(page), startOrStopTimerWithButton(page)]);
|
||||
await assertThatTimerIsStopped(page);
|
||||
});
|
||||
|
||||
test('test that weekly overview section displays stat cards', async ({ page, ctx }) => {
|
||||
await createBareTimeEntryViaApi(ctx, 'Stats test entry', '2h');
|
||||
|
||||
await goToDashboard(page);
|
||||
|
||||
// Verify stat card labels are visible
|
||||
await expect(page.getByText('Spent Time')).toBeVisible();
|
||||
await expect(page.getByText('Billable Time')).toBeVisible();
|
||||
await expect(page.getByText('Billable Amount')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that stopping timer refreshes dashboard data', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
|
||||
// Start timer
|
||||
await Promise.all([newTimeEntryResponse(page), startOrStopTimerWithButton(page)]);
|
||||
await assertThatTimerHasStarted(page);
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
// Stop timer and verify dashboard queries are refetched
|
||||
await Promise.all([
|
||||
stoppedTimeEntryResponse(page),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/charts/') &&
|
||||
response.request().method() === 'GET' &&
|
||||
response.status() === 200
|
||||
),
|
||||
startOrStopTimerWithButton(page),
|
||||
]);
|
||||
await assertThatTimerIsStopped(page);
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Dashboard Restrictions', () => {
|
||||
test('employee dashboard loads and timer is functional', async ({ employee }) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Timer should be available
|
||||
await expect(
|
||||
employee.page
|
||||
.getByTestId('dashboard_timer')
|
||||
.getByTestId('timer_button')
|
||||
.and(employee.page.locator(':visible'))
|
||||
).toBeVisible();
|
||||
await expect(employee.page.getByTestId('time_entry_description')).toBeEditable();
|
||||
});
|
||||
|
||||
test('employee cannot see Team Activity card', async ({ employee }) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Other dashboard cards should be visible
|
||||
await expect(employee.page.getByText('Recent Time Entries', { exact: true })).toBeVisible();
|
||||
|
||||
// Team Activity should NOT be visible for employees
|
||||
await expect(employee.page.getByText('Team Activity', { exact: true })).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee cannot see Cost column in This Week table by default', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
const project = await createPublicProjectViaApi(ctx, {
|
||||
name: 'EmpDashBillProj',
|
||||
is_billable: true,
|
||||
billable_rate: 10000,
|
||||
});
|
||||
await createTimeEntryViaApi(
|
||||
{ ...ctx, memberId: employee.memberId },
|
||||
{
|
||||
description: 'Emp dashboard cost entry',
|
||||
duration: '1h',
|
||||
projectId: project.id,
|
||||
billable: true,
|
||||
}
|
||||
);
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// This Week table should be visible
|
||||
await expect(employee.page.getByText('This Week', { exact: true })).toBeVisible();
|
||||
|
||||
// Duration column should be visible, but Cost column should NOT
|
||||
await expect(employee.page.getByText('Duration', { exact: true })).toBeVisible();
|
||||
await expect(employee.page.getByText('Cost', { exact: true })).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee can see Cost column in This Week table when employees_can_see_billable_rates is enabled', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { employees_can_see_billable_rates: true });
|
||||
|
||||
const project = await createPublicProjectViaApi(ctx, {
|
||||
name: 'EmpDashBillVisProj',
|
||||
is_billable: true,
|
||||
billable_rate: 10000,
|
||||
});
|
||||
await createTimeEntryViaApi(
|
||||
{ ...ctx, memberId: employee.memberId },
|
||||
{
|
||||
description: 'Emp dashboard cost visible entry',
|
||||
duration: '1h',
|
||||
projectId: project.id,
|
||||
billable: true,
|
||||
}
|
||||
);
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Both Duration and Cost columns should be visible
|
||||
await expect(employee.page.getByText('Duration', { exact: true })).toBeVisible();
|
||||
await expect(employee.page.getByText('Cost', { exact: true })).toBeVisible();
|
||||
|
||||
// 1h at 100.00/h = 100.00 EUR cost should be visible
|
||||
await expect(employee.page.getByText('100,00 EUR').first()).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -1,154 +0,0 @@
|
||||
import { expect, test } from '../playwright/fixtures';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import type { Page } from '@playwright/test';
|
||||
import path from 'path';
|
||||
|
||||
async function goToImportExport(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/import');
|
||||
}
|
||||
|
||||
test('test that import page loads with type dropdown and file upload', async ({ page }) => {
|
||||
await goToImportExport(page);
|
||||
await expect(page.getByTestId('import_view')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Import section
|
||||
await expect(page.getByRole('heading', { name: 'Import Data' })).toBeVisible();
|
||||
await expect(page.locator('#importType')).toBeVisible();
|
||||
|
||||
// Export section
|
||||
await expect(page.getByRole('heading', { name: 'Export Data' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Export Organization Data' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that selecting an import type shows instructions', async ({ page }) => {
|
||||
await goToImportExport(page);
|
||||
|
||||
// Select a Toggl import type
|
||||
await page.getByLabel('Import Type').selectOption({ index: 1 });
|
||||
|
||||
// Instructions should appear
|
||||
await expect(page.getByText('Instructions:')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that importing without selecting type shows error', async ({ page }) => {
|
||||
await goToImportExport(page);
|
||||
|
||||
// Click Import Data without selecting a type
|
||||
await page.getByRole('button', { name: 'Import Data' }).click();
|
||||
|
||||
// Should show an error notification
|
||||
await expect(page.getByText('Please select the import type')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that importing without selecting file shows error', async ({ page }) => {
|
||||
await goToImportExport(page);
|
||||
|
||||
// Select an import type first
|
||||
await page.getByLabel('Import Type').selectOption({ index: 1 });
|
||||
|
||||
// Click Import Data without selecting a file
|
||||
await page.getByRole('button', { name: 'Import Data' }).click();
|
||||
|
||||
// Should show an error notification
|
||||
await expect(
|
||||
page.getByText('Please select the CSV or ZIP file that you want to import')
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that export button triggers export and shows success modal', async ({ page }) => {
|
||||
await goToImportExport(page);
|
||||
await expect(page.getByRole('button', { name: 'Export Organization Data' })).toBeVisible();
|
||||
|
||||
// Override window.open to prevent the page from navigating away to the
|
||||
// download URL (the app uses window.open(url, '_self') which would navigate
|
||||
// away before we can verify the success modal)
|
||||
await page.evaluate(() => {
|
||||
window.open = () => null;
|
||||
});
|
||||
|
||||
// Click Export Organization Data and wait for the API response
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/export') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 200,
|
||||
{ timeout: 60000 }
|
||||
),
|
||||
page.getByRole('button', { name: 'Export Organization Data' }).click(),
|
||||
]);
|
||||
|
||||
// Success modal should appear after export completes
|
||||
await expect(page.getByText('The export was successful!')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that import type dropdown has multiple options', async ({ page }) => {
|
||||
await goToImportExport(page);
|
||||
|
||||
// The dropdown should load with options from the API
|
||||
await page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/importers') &&
|
||||
response.request().method() === 'GET' &&
|
||||
response.status() === 200
|
||||
);
|
||||
|
||||
// Verify the select has options besides the default placeholder
|
||||
const options = page.getByLabel('Import Type').locator('option');
|
||||
const count = await options.count();
|
||||
// Should have at least the placeholder + some import types
|
||||
expect(count).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
test('test that importing a generic time entries CSV works', async ({ page }) => {
|
||||
await goToImportExport(page);
|
||||
await expect(page.getByTestId('import_view')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Select "Generic Time Entries" import type
|
||||
await page.getByLabel('Import Type').selectOption({ label: 'Generic Time Entries' });
|
||||
await expect(page.getByText('Instructions:')).toBeVisible();
|
||||
|
||||
// Upload the test CSV file
|
||||
const csvPath = path.resolve('resources/testfiles/generic_time_entries_import_test_1.csv');
|
||||
await page.locator('#file-upload').setInputFiles(csvPath);
|
||||
|
||||
// Click Import and wait for the API response
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/import') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 200,
|
||||
{ timeout: 30000 }
|
||||
),
|
||||
page.getByRole('button', { name: 'Import Data' }).click(),
|
||||
]);
|
||||
|
||||
// Verify success modal with import results
|
||||
await expect(page.getByRole('heading', { name: 'Import Result' })).toBeVisible();
|
||||
await expect(page.getByText('The import was successful!')).toBeVisible();
|
||||
|
||||
// The CSV has 2 time entries, 1 client, 2 projects, 1 task
|
||||
await expect(page.getByText('Time entries created:').locator('..')).toContainText('2');
|
||||
await expect(page.getByText('Projects created:').locator('..')).toContainText('2');
|
||||
await expect(page.getByText('Clients created:').locator('..')).toContainText('1');
|
||||
await expect(page.getByText('Tasks created:').locator('..')).toContainText('1');
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Import Restrictions', () => {
|
||||
test('employee does not see Import / Export link in the sidebar', async ({ employee }) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// The Import / Export link should NOT be visible in the sidebar for employees
|
||||
await expect(
|
||||
employee.page.getByRole('link', { name: 'Import / Export' })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -3,69 +3,65 @@
|
||||
// TODO: Remove Invitation
|
||||
import { expect, test } from '../playwright/fixtures';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { inviteAndAcceptMember } from './utils/members';
|
||||
import {
|
||||
createPlaceholderMemberViaImportApi,
|
||||
getMembersViaApi,
|
||||
updateMemberBillableRateViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
|
||||
// Tests that invite + accept members need more time
|
||||
test.describe.configure({ timeout: 45000 });
|
||||
|
||||
async function goToMembersPage(page: Page) {
|
||||
async function goToMembersPage(page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
|
||||
}
|
||||
|
||||
async function openInviteMemberModal(page: Page) {
|
||||
async function openInviteMemberModal(page) {
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Invite Member' }).click(),
|
||||
expect(page.getByPlaceholder('Member Email')).toBeVisible(),
|
||||
]);
|
||||
}
|
||||
|
||||
test('test that new manager can be invited and accepted', async ({ page, browser }) => {
|
||||
const memberId = Math.round(Math.random() * 100000);
|
||||
const memberEmail = `manager+${memberId}@invite.test`;
|
||||
|
||||
await inviteAndAcceptMember(page, browser, 'Invited Mgr', memberEmail, 'Manager');
|
||||
|
||||
// Verify the member appears in the members table with the correct role
|
||||
test('test that new manager can be invited', async ({ page }) => {
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: 'Invited Mgr' });
|
||||
await expect(memberRow).toBeVisible();
|
||||
await expect(memberRow.getByText('Manager', { exact: true })).toBeVisible();
|
||||
await openInviteMemberModal(page);
|
||||
const editorId = Math.round(Math.random() * 10000);
|
||||
await page.getByLabel('Email').fill(`new+${editorId}@editor.test`);
|
||||
await page.getByRole('button', { name: 'Manager' }).click();
|
||||
await Promise.all([
|
||||
page
|
||||
.getByRole('button', { name: 'Invite Member', exact: true })
|
||||
.click(),
|
||||
expect(page.getByRole('main')).toContainText(
|
||||
`new+${editorId}@editor.test`
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that new employee can be invited and accepted', async ({ page, browser }) => {
|
||||
const memberId = Math.round(Math.random() * 100000);
|
||||
const memberEmail = `employee+${memberId}@invite.test`;
|
||||
|
||||
await inviteAndAcceptMember(page, browser, 'Invited Emp', memberEmail, 'Employee');
|
||||
|
||||
// Verify the member appears in the members table with the correct role
|
||||
test('test that new employee can be invited', async ({ page }) => {
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: 'Invited Emp' });
|
||||
await expect(memberRow).toBeVisible();
|
||||
await expect(memberRow.getByText('Employee', { exact: true })).toBeVisible();
|
||||
await openInviteMemberModal(page);
|
||||
const editorId = Math.round(Math.random() * 10000);
|
||||
await page.getByLabel('Email').fill(`new+${editorId}@editor.test`);
|
||||
await page.getByRole('button', { name: 'Employee' }).click();
|
||||
await Promise.all([
|
||||
page
|
||||
.getByRole('button', { name: 'Invite Member', exact: true })
|
||||
.click(),
|
||||
await expect(page.getByRole('main')).toContainText(
|
||||
`new+${editorId}@editor.test`
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that new admin can be invited and accepted', async ({ page, browser }) => {
|
||||
const memberId = Math.round(Math.random() * 100000);
|
||||
const memberEmail = `admin+${memberId}@invite.test`;
|
||||
|
||||
await inviteAndAcceptMember(page, browser, 'Invited Adm', memberEmail, 'Administrator');
|
||||
|
||||
// Verify the member appears in the members table with the correct role
|
||||
test('test that new admin can be invited', async ({ page }) => {
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: 'Invited Adm' });
|
||||
await expect(memberRow).toBeVisible();
|
||||
await expect(memberRow.getByText('Admin', { exact: true })).toBeVisible();
|
||||
await openInviteMemberModal(page);
|
||||
const adminId = Math.round(Math.random() * 10000);
|
||||
await page.getByLabel('Email').fill(`new+${adminId}@admin.test`);
|
||||
await page.getByRole('button', { name: 'Administrator' }).click();
|
||||
await Promise.all([
|
||||
page
|
||||
.getByRole('button', { name: 'Invite Member', exact: true })
|
||||
.click(),
|
||||
expect(page.getByRole('main')).toContainText(
|
||||
`new+${adminId}@admin.test`
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that error shows if no role is selected', async ({ page }) => {
|
||||
await goToMembersPage(page);
|
||||
await openInviteMemberModal(page);
|
||||
@@ -73,7 +69,9 @@ test('test that error shows if no role is selected', async ({ page }) => {
|
||||
|
||||
await page.getByLabel('Email').fill(`new+${noRoleId}@norole.test`);
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Invite Member', exact: true }).click(),
|
||||
page
|
||||
.getByRole('button', { name: 'Invite Member', exact: true })
|
||||
.click(),
|
||||
expect(page.getByText('Please select a role')).toBeVisible(),
|
||||
]);
|
||||
});
|
||||
@@ -85,9 +83,11 @@ test('test that organization billable rate can be updated with all existing time
|
||||
const newBillableRate = Math.round(Math.random() * 10000);
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').click();
|
||||
await page.getByRole('combobox').last().click();
|
||||
await page.getByRole('option', { name: 'Custom Rate' }).click();
|
||||
await page.getByPlaceholder('Billable Rate').fill(newBillableRate.toString());
|
||||
await page.getByText('Organization Default Rate').click();
|
||||
await page.getByText('Custom Rate').click();
|
||||
await page
|
||||
.getByPlaceholder('Billable Rate')
|
||||
.fill(newBillableRate.toString());
|
||||
await page.getByRole('button', { name: 'Update Member' }).click();
|
||||
|
||||
await Promise.all([
|
||||
@@ -103,687 +103,8 @@ test('test that organization billable rate can be updated with all existing time
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.billable_rate === newBillableRate * 100
|
||||
(await response.json()).data.billable_rate ===
|
||||
newBillableRate * 100
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that switching member billable rate from custom back to default rate works', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Set a known org billable rate
|
||||
await updateOrganizationSettingViaApi(ctx, { billable_rate: 12000 });
|
||||
|
||||
// Create a placeholder member with a custom billable rate
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'CustomToDefault Member');
|
||||
const members = await getMembersViaApi(ctx);
|
||||
const member = members.find((m) => m.name === 'CustomToDefault Member');
|
||||
expect(member).toBeDefined();
|
||||
await updateMemberBillableRateViaApi(ctx, member!.id, 25000);
|
||||
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: 'CustomToDefault Member' });
|
||||
await expect(memberRow).toBeVisible();
|
||||
|
||||
// Open edit modal
|
||||
await memberRow.getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').click();
|
||||
await expect(page.getByRole('heading', { name: 'Update Member' })).toBeVisible();
|
||||
|
||||
// Verify it starts on Custom Rate
|
||||
const billableCombobox = page.getByRole('dialog').getByRole('combobox').last();
|
||||
await expect(billableCombobox).toContainText('Custom Rate');
|
||||
|
||||
// Switch to Default Rate
|
||||
await billableCombobox.click();
|
||||
await page.getByRole('option', { name: 'Default Rate' }).click();
|
||||
await expect(billableCombobox).toContainText('Default Rate');
|
||||
|
||||
// Verify the billable rate input is disabled
|
||||
await expect(page.getByPlaceholder('Billable Rate')).toBeDisabled();
|
||||
|
||||
// Submit — billable_rate changes from 25000 to null, so confirmation dialog appears
|
||||
await page.getByRole('button', { name: 'Update Member' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Update Member Billable Rate' })).toBeVisible();
|
||||
await expect(page.getByText('the default rate of the organization')).toBeVisible();
|
||||
|
||||
// Confirm the update
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Yes, update existing time' }).click(),
|
||||
page.waitForRequest(
|
||||
(request) =>
|
||||
request.url().includes('/members/') &&
|
||||
request.method() === 'PUT' &&
|
||||
request.postDataJSON().billable_rate === null
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify both dialogs are closed
|
||||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that default rate shows disabled input with organization billable rate', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Set a known org billable rate (150.00)
|
||||
await updateOrganizationSettingViaApi(ctx, { billable_rate: 15000 });
|
||||
|
||||
await goToMembersPage(page);
|
||||
|
||||
// Open edit modal for the owner (who uses default rate by default)
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').click();
|
||||
await expect(page.getByRole('heading', { name: 'Update Member' })).toBeVisible();
|
||||
|
||||
// Verify it's on Default Rate
|
||||
const billableCombobox = page.getByRole('dialog').getByRole('combobox').last();
|
||||
await expect(billableCombobox).toContainText('Default Rate');
|
||||
|
||||
// Verify the input is disabled and shows the org rate (formatted with currency)
|
||||
const billableInput = page.getByPlaceholder('Billable Rate');
|
||||
await expect(billableInput).toBeDisabled();
|
||||
await expect(billableInput).toHaveAttribute('aria-valuenow', '150');
|
||||
|
||||
// Close the dialog
|
||||
await page.getByRole('button', { name: 'Cancel' }).click();
|
||||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that cancelling the billable rate confirmation dialog does not update the member', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Create a placeholder member with a custom billable rate
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'CancelConfirm Member');
|
||||
const members = await getMembersViaApi(ctx);
|
||||
const member = members.find((m) => m.name === 'CancelConfirm Member');
|
||||
expect(member).toBeDefined();
|
||||
await updateMemberBillableRateViaApi(ctx, member!.id, 10000);
|
||||
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: 'CancelConfirm Member' });
|
||||
await expect(memberRow).toBeVisible();
|
||||
|
||||
// Open edit modal
|
||||
await memberRow.getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').click();
|
||||
await expect(page.getByRole('heading', { name: 'Update Member' })).toBeVisible();
|
||||
|
||||
// Change the billable rate
|
||||
await page.getByPlaceholder('Billable Rate').fill('200');
|
||||
|
||||
// Click Update Member — confirmation dialog should appear
|
||||
await page.getByRole('button', { name: 'Update Member' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'Update Member Billable Rate' })).toBeVisible();
|
||||
|
||||
// Set up listener to verify no PUT request is sent after cancel
|
||||
let putRequestSent = false;
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('/members/') && request.method() === 'PUT') {
|
||||
putRequestSent = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Click Cancel on the confirmation dialog
|
||||
await page.getByRole('button', { name: 'Cancel' }).click();
|
||||
|
||||
// Verify confirmation dialog is closed
|
||||
await expect(
|
||||
page.getByRole('heading', { name: 'Update Member Billable Rate' })
|
||||
).not.toBeVisible();
|
||||
|
||||
// Verify no API call was made
|
||||
expect(putRequestSent).toBe(false);
|
||||
});
|
||||
|
||||
test('test that changing role of placeholder member is rejected', async ({ page, ctx }) => {
|
||||
const placeholderName = 'RoleChange ' + Math.floor(Math.random() * 10000);
|
||||
|
||||
// Create a placeholder member via import
|
||||
await createPlaceholderMemberViaImportApi(ctx, placeholderName);
|
||||
|
||||
// Go to members page and verify placeholder exists with role "Placeholder"
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: placeholderName });
|
||||
await expect(memberRow).toBeVisible();
|
||||
await expect(memberRow.getByText('Placeholder', { exact: true })).toBeVisible();
|
||||
|
||||
// Open the edit modal for the placeholder member
|
||||
await memberRow.getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Update Member' })).toBeVisible();
|
||||
|
||||
// Change role to Employee
|
||||
const roleSelect = page.getByRole('dialog').getByRole('combobox').first();
|
||||
await roleSelect.click();
|
||||
await expect(page.getByRole('option', { name: 'Employee' })).toBeVisible();
|
||||
await page.getByRole('option', { name: 'Employee' }).click();
|
||||
await expect(roleSelect).toContainText('Employee');
|
||||
|
||||
// Submit the change - the API should reject it with 400
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Update Member' }).click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/members/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 400
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify error notification is shown
|
||||
await expect(page.getByText('Failed to update member')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that changing member role updates the role in the member table', async ({
|
||||
page,
|
||||
browser,
|
||||
}) => {
|
||||
const memberId = Math.floor(Math.random() * 100000);
|
||||
const memberEmail = `member+${memberId}@rolechange.test`;
|
||||
|
||||
// Invite and accept a new Employee member
|
||||
await inviteAndAcceptMember(page, browser, 'Jane Smith', memberEmail, 'Employee');
|
||||
|
||||
// Verify the new member appears with the Employee role
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: 'Jane Smith' });
|
||||
await expect(memberRow).toBeVisible();
|
||||
await expect(memberRow.getByText('Employee', { exact: true })).toBeVisible();
|
||||
|
||||
// Open the edit modal
|
||||
await memberRow.getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Update Member' })).toBeVisible();
|
||||
|
||||
// Change role to Manager
|
||||
const roleSelect = page.getByRole('dialog').getByRole('combobox').first();
|
||||
await roleSelect.click();
|
||||
await expect(page.getByRole('option', { name: 'Manager' })).toBeVisible();
|
||||
await page.getByRole('option', { name: 'Manager' }).click();
|
||||
await expect(roleSelect).toContainText('Manager');
|
||||
|
||||
// Submit the change and verify the API call succeeds
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Update Member' }).click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/members/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify dialog closed
|
||||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||
|
||||
// Verify the role updated in the table
|
||||
await expect(memberRow.getByText('Manager', { exact: true })).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that merging a placeholder member works', async ({ page, ctx }) => {
|
||||
const placeholderName = 'Merge Target ' + Math.floor(Math.random() * 10000);
|
||||
|
||||
// Create a placeholder member via import
|
||||
await createPlaceholderMemberViaImportApi(ctx, placeholderName);
|
||||
|
||||
// Go to members page
|
||||
await goToMembersPage(page);
|
||||
await expect(page.getByText(placeholderName)).toBeVisible();
|
||||
|
||||
// Find the placeholder member row and open actions menu
|
||||
const placeholderRow = page.getByRole('row').filter({ hasText: placeholderName });
|
||||
await placeholderRow.getByRole('button').click();
|
||||
|
||||
// Click Merge
|
||||
await page.getByTestId('member_merge').click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Merge Member' })).toBeVisible();
|
||||
|
||||
// Select the current user (the owner) as merge target via MemberCombobox
|
||||
// The MemberCombobox renders a Button as trigger; clicking it opens the popover with the combobox input
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'Select a member...' }).click();
|
||||
|
||||
// Wait for dropdown options to load
|
||||
const firstOption = page.getByRole('option').first();
|
||||
await expect(firstOption).toBeVisible({ timeout: 10000 });
|
||||
await firstOption.click();
|
||||
|
||||
// Submit merge
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Merge Member' }).click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/member/') &&
|
||||
response.url().includes('/merge-into') &&
|
||||
response.ok()
|
||||
),
|
||||
]);
|
||||
|
||||
// Wait for merge dialog to close after successful merge
|
||||
await expect(page.getByRole('dialog').filter({ hasText: 'Merge Member' })).not.toBeVisible();
|
||||
|
||||
// Verify placeholder member is no longer in the members table
|
||||
await expect(page.getByRole('main').getByText(placeholderName)).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that deleting a placeholder member works', async ({ page, ctx }) => {
|
||||
const placeholderName = 'Delete Target ' + Math.floor(Math.random() * 10000);
|
||||
|
||||
// Create a placeholder member via import
|
||||
await createPlaceholderMemberViaImportApi(ctx, placeholderName);
|
||||
|
||||
// Go to members page
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: placeholderName });
|
||||
await expect(memberRow).toBeVisible();
|
||||
|
||||
// Open actions menu and click Delete
|
||||
await memberRow.getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Delete').click();
|
||||
|
||||
// Verify delete modal is shown
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Delete Member' })).toBeVisible();
|
||||
|
||||
// Try to delete without checking the confirmation checkbox
|
||||
await page.getByRole('button', { name: 'Delete Member' }).click();
|
||||
|
||||
// Should show validation error
|
||||
await expect(
|
||||
page.getByText('You must confirm that you understand the consequences of this action')
|
||||
).toBeVisible();
|
||||
|
||||
// Check the confirmation checkbox
|
||||
await page.getByRole('checkbox').click();
|
||||
|
||||
// Click Delete Member button and wait for API response
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Delete Member' }).click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/members/') &&
|
||||
response.request().method() === 'DELETE' &&
|
||||
response.ok()
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify modal is closed
|
||||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||
|
||||
// Verify member is removed from the table
|
||||
await expect(page.getByRole('main').getByText(placeholderName)).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that member delete modal can be cancelled', async ({ page, ctx }) => {
|
||||
const placeholderName = 'Delete Cancel ' + Math.floor(Math.random() * 10000);
|
||||
|
||||
// Create a placeholder member via import
|
||||
await createPlaceholderMemberViaImportApi(ctx, placeholderName);
|
||||
|
||||
// Go to members page
|
||||
await goToMembersPage(page);
|
||||
const memberRow = page.getByRole('row').filter({ hasText: placeholderName });
|
||||
await expect(memberRow).toBeVisible();
|
||||
|
||||
// Open actions menu and click Delete
|
||||
await memberRow.getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Delete').click();
|
||||
|
||||
// Verify delete modal is shown
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Set up listener to verify no DELETE request is sent
|
||||
let deleteRequestSent = false;
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('/members/') && request.method() === 'DELETE') {
|
||||
deleteRequestSent = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Click Cancel
|
||||
await page.getByRole('button', { name: 'Cancel' }).click();
|
||||
|
||||
// Verify modal is closed
|
||||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||
|
||||
// Verify member is still in the table
|
||||
await expect(memberRow).toBeVisible();
|
||||
|
||||
// Verify no DELETE request was sent
|
||||
expect(deleteRequestSent).toBe(false);
|
||||
});
|
||||
|
||||
test('test that organization owner cannot be deleted', async ({ page }) => {
|
||||
await goToMembersPage(page);
|
||||
|
||||
// Find the owner row (John Doe with Owner role)
|
||||
const ownerRow = page.getByRole('row').filter({ hasText: 'Owner' });
|
||||
await expect(ownerRow).toBeVisible();
|
||||
|
||||
// Open the actions menu for the owner
|
||||
await ownerRow.getByRole('button').click();
|
||||
|
||||
// Click Delete
|
||||
await page.getByRole('menuitem').getByText('Delete').click();
|
||||
|
||||
// Verify delete modal is shown
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Check the confirmation checkbox
|
||||
await page.getByRole('checkbox').click();
|
||||
|
||||
// Try to delete - should fail with 400 error
|
||||
const responsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/members/') && response.request().method() === 'DELETE'
|
||||
);
|
||||
await page.getByRole('button', { name: 'Delete Member' }).click();
|
||||
const response = await responsePromise;
|
||||
|
||||
// Verify the API returned an error status
|
||||
expect(response.status()).toBe(400);
|
||||
|
||||
// Close the modal by pressing Escape
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
// Refresh and verify the owner is still there
|
||||
await goToMembersPage(page);
|
||||
await expect(page.getByRole('row').filter({ hasText: 'Owner' })).toBeVisible();
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Invitations Tab Tests
|
||||
// =============================================
|
||||
|
||||
test('test that invitation shows in invitations tab and can be revoked', async ({ page }) => {
|
||||
const inviteEmail = `invite+${Math.floor(Math.random() * 100000)}@pending.test`;
|
||||
|
||||
await goToMembersPage(page);
|
||||
await openInviteMemberModal(page);
|
||||
|
||||
await page.getByPlaceholder('Member Email').fill(inviteEmail);
|
||||
await page.getByRole('button', { name: 'Employee' }).click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/invitations') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 204
|
||||
),
|
||||
page.getByRole('button', { name: 'Invite Member', exact: true }).click(),
|
||||
]);
|
||||
|
||||
// Wait for modal to close
|
||||
await expect(page.getByPlaceholder('Member Email')).not.toBeVisible();
|
||||
|
||||
// Switch to Invitations tab and verify the invitation is visible
|
||||
await page.getByText('Invitations', { exact: true }).click();
|
||||
await expect(page.getByText(inviteEmail)).toBeVisible();
|
||||
|
||||
// Find and click the actions menu for this invitation
|
||||
const invitationRow = page.locator('tr, [role="row"]').filter({ hasText: inviteEmail });
|
||||
await invitationRow.getByRole('button').click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/invitations/') &&
|
||||
response.request().method() === 'DELETE' &&
|
||||
response.status() === 204
|
||||
),
|
||||
page.getByRole('menuitem').getByText('Delete').click(),
|
||||
]);
|
||||
|
||||
// Verify invitation is removed
|
||||
await expect(page.getByText(inviteEmail)).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that invitation can be resent', async ({ page }) => {
|
||||
const inviteEmail = `resend+${Math.floor(Math.random() * 100000)}@invite.test`;
|
||||
|
||||
await goToMembersPage(page);
|
||||
await openInviteMemberModal(page);
|
||||
|
||||
await page.getByPlaceholder('Member Email').fill(inviteEmail);
|
||||
await page.getByRole('button', { name: 'Employee' }).click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/invitations') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 204
|
||||
),
|
||||
page.getByRole('button', { name: 'Invite Member', exact: true }).click(),
|
||||
]);
|
||||
|
||||
// Wait for modal to close
|
||||
await expect(page.getByPlaceholder('Member Email')).not.toBeVisible();
|
||||
|
||||
// Switch to Invitations tab
|
||||
await page.getByText('Invitations', { exact: true }).click();
|
||||
await expect(page.getByText(inviteEmail)).toBeVisible();
|
||||
|
||||
// Find and click the actions menu, then resend
|
||||
const invitationRow = page.locator('tr, [role="row"]').filter({ hasText: inviteEmail });
|
||||
await invitationRow.getByRole('button').click();
|
||||
// Wait for dropdown menu to appear
|
||||
await expect(page.getByRole('menuitem').getByText('Resend Invitation')).toBeVisible();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/resend') && response.request().method() === 'POST'
|
||||
),
|
||||
page.getByRole('menuitem').getByText('Resend Invitation').click(),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that admin user cannot transfer ownership', async ({ page, browser }) => {
|
||||
const memberId = Math.floor(Math.random() * 100000);
|
||||
const memberEmail = `admin+${memberId}@perms.test`;
|
||||
|
||||
// Invite and accept an admin member
|
||||
await inviteAndAcceptMember(
|
||||
page,
|
||||
browser,
|
||||
'Admin User ' + memberId,
|
||||
memberEmail,
|
||||
'Administrator'
|
||||
);
|
||||
|
||||
// Go to members page and verify the admin exists
|
||||
await goToMembersPage(page);
|
||||
const adminRow = page.getByRole('row').filter({ hasText: 'Admin User' });
|
||||
await expect(adminRow).toBeVisible();
|
||||
|
||||
// The owner should still be the owner
|
||||
const ownerRow = page.getByRole('row').filter({ hasText: 'Owner' });
|
||||
await expect(ownerRow).toBeVisible();
|
||||
|
||||
// Open actions menu for the admin - should NOT have "Transfer Ownership" option
|
||||
await adminRow.getByRole('button').click();
|
||||
await expect(page.getByRole('menuitem').getByText('Edit')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that accepted invitation disappears from invitations tab', async ({ page, browser }) => {
|
||||
const memberId = Math.round(Math.random() * 100000);
|
||||
const memberEmail = `accepted+${memberId}@invite.test`;
|
||||
|
||||
// Invite and accept the member
|
||||
await inviteAndAcceptMember(page, browser, 'Accepted Member', memberEmail, 'Employee');
|
||||
|
||||
// Go to members page and switch to Invitations tab
|
||||
await goToMembersPage(page);
|
||||
await page.getByRole('tab', { name: 'Invitations' }).click();
|
||||
|
||||
// The accepted invitation should not be visible
|
||||
await expect(page.getByText(memberEmail)).not.toBeVisible();
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Sorting Tests
|
||||
// =============================================
|
||||
|
||||
// Helper to clear localStorage before tests that check sorting
|
||||
async function clearMemberTableState(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
localStorage.removeItem('member-table-state');
|
||||
});
|
||||
}
|
||||
|
||||
test('test that sorting members by name, role, and status works', async ({ page, ctx }) => {
|
||||
// Create two placeholder members with names that sort predictably around "John Doe"
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'AAA SortFirst');
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'ZZZ SortLast');
|
||||
|
||||
await goToMembersPage(page);
|
||||
await clearMemberTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// -- Name sorting (default is already name asc after clearing state) --
|
||||
const nameHeader = table.getByText('Name').first();
|
||||
let names = await getTableRowNames(table);
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
|
||||
|
||||
await nameHeader.click(); // toggle to desc
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('ZZZ SortLast')).toBeLessThan(names.indexOf('AAA SortFirst'));
|
||||
|
||||
// -- Role sorting --
|
||||
const roleHeader = table.getByText('Role').first();
|
||||
await roleHeader.click(); // asc: Owner(0) < Placeholder(4)
|
||||
names = await getTableRowNames(table);
|
||||
const ownerIdx = names.indexOf('John Doe');
|
||||
const placeholderIdx = names.indexOf('AAA SortFirst');
|
||||
expect(ownerIdx).toBeLessThan(placeholderIdx);
|
||||
|
||||
await roleHeader.click(); // desc: Placeholder first
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe'));
|
||||
|
||||
// -- Status sorting --
|
||||
const statusHeader = table.getByText('Status').first();
|
||||
await statusHeader.click(); // asc: Active(0) < Inactive(1)
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('John Doe')).toBeLessThan(names.indexOf('AAA SortFirst'));
|
||||
|
||||
await statusHeader.click(); // desc: Inactive first
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe'));
|
||||
|
||||
// -- Email: just verify sort indicator appears --
|
||||
const emailHeader = table.getByText('Email').first();
|
||||
await emailHeader.click();
|
||||
await expect(emailHeader.locator('svg')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that member sort state persists after page reload', async ({ page }) => {
|
||||
await goToMembersPage(page);
|
||||
await clearMemberTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// Click Role header twice to set descending sort
|
||||
const roleHeader = table.getByText('Role').first();
|
||||
await roleHeader.click();
|
||||
await expect(roleHeader.locator('svg')).toBeVisible();
|
||||
await roleHeader.click();
|
||||
await expect(roleHeader.locator('svg')).toBeVisible();
|
||||
|
||||
// Reload the page
|
||||
await page.reload();
|
||||
|
||||
// Verify the sort indicator is still visible on Role column
|
||||
await expect(page.getByTestId('member_table')).toBeVisible();
|
||||
await expect(
|
||||
page.getByTestId('member_table').getByText('Role').first().locator('svg')
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that sorting members by billable rate works', async ({ page, ctx }) => {
|
||||
// Create two placeholder members and set different billable rates
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'HighRate Member');
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'LowRate Member');
|
||||
|
||||
const members = await getMembersViaApi(ctx);
|
||||
const highRateMember = members.find((m) => m.name === 'HighRate Member');
|
||||
const lowRateMember = members.find((m) => m.name === 'LowRate Member');
|
||||
expect(highRateMember).toBeDefined();
|
||||
expect(lowRateMember).toBeDefined();
|
||||
|
||||
await updateMemberBillableRateViaApi(ctx, highRateMember!.id, 20000);
|
||||
await updateMemberBillableRateViaApi(ctx, lowRateMember!.id, 5000);
|
||||
|
||||
await goToMembersPage(page);
|
||||
await clearMemberTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// First click = desc (highest first), null rates last
|
||||
const billableHeader = table.getByText('Billable Rate').first();
|
||||
await billableHeader.click();
|
||||
await expect(billableHeader.locator('svg')).toBeVisible();
|
||||
let names = await getTableRowNames(table);
|
||||
expect(names.indexOf('HighRate Member')).toBeLessThan(names.indexOf('LowRate Member'));
|
||||
|
||||
// Second click = asc (lowest first), null rates still last
|
||||
await billableHeader.click();
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('LowRate Member')).toBeLessThan(names.indexOf('HighRate Member'));
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Sidebar Navigation', () => {
|
||||
test('employee sidebar shows correct navigation links', async ({ employee }) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employee.page.getByTestId('dashboard_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Visible links
|
||||
await expect(employee.page.getByRole('link', { name: 'Dashboard' })).toBeVisible();
|
||||
await expect(employee.page.getByRole('link', { name: 'Time' })).toBeVisible();
|
||||
await expect(employee.page.getByRole('link', { name: 'Calendar' })).toBeVisible();
|
||||
await expect(employee.page.getByRole('link', { name: 'Projects' })).toBeVisible();
|
||||
await expect(employee.page.getByRole('link', { name: 'Clients' })).toBeVisible();
|
||||
await expect(employee.page.getByRole('link', { name: 'Tags' })).toBeVisible();
|
||||
|
||||
// Hidden links
|
||||
await expect(employee.page.getByRole('link', { name: 'Members' })).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.getByRole('link', { name: 'Settings', exact: true })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee cannot see members list or invite members', async ({ employee }) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/members');
|
||||
|
||||
// Page loads but the members API returns 403 (no members:view permission)
|
||||
await expect(employee.page.getByRole('heading', { name: 'Members' })).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Member table is empty — no rows rendered (only headers)
|
||||
await expect(employee.page.getByTestId('member_table').locator('[role="row"]')).toHaveCount(
|
||||
0
|
||||
);
|
||||
|
||||
// Employee should NOT see the Invite Member button
|
||||
await expect(
|
||||
employee.page.getByRole('button', { name: 'Invite member' })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,10 +9,7 @@ async function goToOrganizationSettings(page) {
|
||||
|
||||
async function createTimeEntry(page, duration: string) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
|
||||
|
||||
// Open the dropdown menu and click "Manual time entry"
|
||||
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||
await page.getByRole('menuitem', { name: 'Manual time entry' }).click();
|
||||
await page.getByRole('button', { name: 'Manual time entry' }).click();
|
||||
|
||||
// Fill in the time entry details
|
||||
await page.getByTestId('time_entry_description').fill('Test time entry');
|
||||
@@ -38,9 +35,9 @@ test('test that organization name can be updated', async ({ page }) => {
|
||||
await page.getByLabel('Organization Name').fill('NEW ORG NAME');
|
||||
await page.getByLabel('Organization Name').press('Enter');
|
||||
await page.getByLabel('Organization Name').press('Meta+r');
|
||||
await expect(page.locator('[data-testid="organization_switcher"]:visible')).toContainText(
|
||||
'NEW ORG NAME'
|
||||
);
|
||||
await expect(
|
||||
page.locator('[data-testid="organization_switcher"]:visible')
|
||||
).toContainText('NEW ORG NAME');
|
||||
});
|
||||
|
||||
test('test that organization billable rate can be updated with all existing time entries', async ({
|
||||
@@ -49,7 +46,9 @@ test('test that organization billable rate can be updated with all existing time
|
||||
await goToOrganizationSettings(page);
|
||||
const newBillableRate = Math.round(Math.random() * 10000);
|
||||
await page.getByLabel('Organization Billable Rate').click();
|
||||
await page.getByLabel('Organization Billable Rate').fill(newBillableRate.toString());
|
||||
await page
|
||||
.getByLabel('Organization Billable Rate')
|
||||
.fill(newBillableRate.toString());
|
||||
await page
|
||||
.locator('form')
|
||||
.filter({ hasText: 'Organization Billable' })
|
||||
@@ -57,7 +56,9 @@ test('test that organization billable rate can be updated with all existing time
|
||||
.click();
|
||||
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Yes, update existing time entries' }).click(),
|
||||
page
|
||||
.getByRole('button', { name: 'Yes, update existing time entries' })
|
||||
.click(),
|
||||
page.waitForRequest(
|
||||
async (request) =>
|
||||
request.url().includes('/organizations/') &&
|
||||
@@ -69,12 +70,15 @@ test('test that organization billable rate can be updated with all existing time
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.billable_rate === newBillableRate * 100
|
||||
(await response.json()).data.billable_rate ===
|
||||
newBillableRate * 100
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that organization format settings can be updated', async ({ page }) => {
|
||||
test('test that organization format settings can be updated', async ({
|
||||
page,
|
||||
}) => {
|
||||
await goToOrganizationSettings(page);
|
||||
|
||||
// Test number format
|
||||
@@ -109,7 +113,8 @@ test('test that organization format settings can be updated', async ({ page }) =
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.currency_format === 'iso-code-after-with-space'
|
||||
(await response.json()).data.currency_format ===
|
||||
'iso-code-after-with-space'
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -127,7 +132,8 @@ test('test that organization format settings can be updated', async ({ page }) =
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.date_format === 'slash-separated-dd-mm-yyyy'
|
||||
(await response.json()).data.date_format ===
|
||||
'slash-separated-dd-mm-yyyy'
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -163,14 +169,19 @@ test('test that organization format settings can be updated', async ({ page }) =
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.interval_format === 'hours-minutes-colon-separated'
|
||||
(await response.json()).data.interval_format ===
|
||||
'hours-minutes-colon-separated'
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that format settings are reflected in the dashboard', async ({ page }) => {
|
||||
test('test that format settings are reflected in the dashboard', async ({
|
||||
page,
|
||||
}) => {
|
||||
// check that 0h 00min is displayed
|
||||
await expect(page.getByText('0h 00min', { exact: true }).nth(0)).toBeVisible();
|
||||
await expect(
|
||||
page.getByText('0h 00min', { exact: true }).nth(0)
|
||||
).toBeVisible();
|
||||
|
||||
// First set the format settings
|
||||
await goToOrganizationSettings(page);
|
||||
@@ -202,8 +213,10 @@ test('test that format settings are reflected in the dashboard', async ({ page }
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.interval_format === 'hours-minutes-colon-separated' &&
|
||||
(await response.json()).data.currency_format === 'symbol-after' &&
|
||||
(await response.json()).data.interval_format ===
|
||||
'hours-minutes-colon-separated' &&
|
||||
(await response.json()).data.currency_format ===
|
||||
'symbol-after' &&
|
||||
(await response.json()).data.number_format === 'comma-point'
|
||||
),
|
||||
]);
|
||||
@@ -219,215 +232,17 @@ test('test that format settings are reflected in the dashboard', async ({ page }
|
||||
// check that 00:00 is displayed
|
||||
await expect(page.getByText('0:00', { exact: true }).nth(0)).toBeVisible();
|
||||
// check that 0h 00min is not displayed
|
||||
await expect(page.getByText('0h 00min', { exact: true }).nth(0)).not.toBeVisible();
|
||||
await expect(
|
||||
page.getByText('0h 00min', { exact: true }).nth(0)
|
||||
).not.toBeVisible();
|
||||
|
||||
// check that the current date is displayed in the dd/mm/yyyy format on the time page
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
|
||||
// Wait for time entries to load so organization data is available for date formatting
|
||||
await page.waitForResponse(
|
||||
(response) => response.url().includes('/time-entries') && response.status() === 200
|
||||
);
|
||||
await expect(
|
||||
page.getByText(new Date().toLocaleDateString('en-GB'), { exact: true }).nth(0)
|
||||
).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
|
||||
test('test that organization time entry settings can be toggled', async ({ page }) => {
|
||||
await goToOrganizationSettings(page);
|
||||
|
||||
const preventOverlappingCheckbox = page.getByLabel(
|
||||
'Prevent overlapping time entries (new entries only)'
|
||||
);
|
||||
const manageTasksCheckbox = page.getByLabel('Allow Employees to manage tasks');
|
||||
|
||||
// Get current states and toggle both
|
||||
const wasOverlappingChecked = await preventOverlappingCheckbox.isChecked();
|
||||
const wasManageTasksChecked = await manageTasksCheckbox.isChecked();
|
||||
|
||||
if (wasOverlappingChecked) {
|
||||
await preventOverlappingCheckbox.uncheck();
|
||||
} else {
|
||||
await preventOverlappingCheckbox.check();
|
||||
}
|
||||
|
||||
if (wasManageTasksChecked) {
|
||||
await manageTasksCheckbox.uncheck();
|
||||
} else {
|
||||
await manageTasksCheckbox.check();
|
||||
}
|
||||
|
||||
// Save
|
||||
const settingsForm = page.locator('form').filter({ hasText: 'Prevent overlapping' });
|
||||
await Promise.all([
|
||||
settingsForm.getByRole('button', { name: 'Save' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.prevent_overlapping_time_entries ===
|
||||
!wasOverlappingChecked
|
||||
),
|
||||
]);
|
||||
|
||||
// Reload and verify both settings persisted
|
||||
await page.reload();
|
||||
await expect(preventOverlappingCheckbox).toBeChecked({ checked: !wasOverlappingChecked });
|
||||
await expect(manageTasksCheckbox).toBeChecked({ checked: !wasManageTasksChecked });
|
||||
|
||||
// Toggle both back to restore original state
|
||||
if (!wasOverlappingChecked) {
|
||||
await preventOverlappingCheckbox.uncheck();
|
||||
} else {
|
||||
await preventOverlappingCheckbox.check();
|
||||
}
|
||||
|
||||
if (!wasManageTasksChecked) {
|
||||
await manageTasksCheckbox.uncheck();
|
||||
} else {
|
||||
await manageTasksCheckbox.check();
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
settingsForm.getByRole('button', { name: 'Save' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.prevent_overlapping_time_entries ===
|
||||
wasOverlappingChecked
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that 12-hour clock format can be set', async ({ page }) => {
|
||||
await goToOrganizationSettings(page);
|
||||
|
||||
await page.getByLabel('Time Format').click();
|
||||
await page.getByRole('option', { name: '12-hour clock' }).click();
|
||||
await Promise.all([
|
||||
page
|
||||
.locator('form')
|
||||
.filter({ hasText: 'Time Format' })
|
||||
.getByRole('button', { name: 'Save' })
|
||||
.click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.time_format === '12-hours'
|
||||
),
|
||||
]);
|
||||
|
||||
// Reload and verify it persisted
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Time Format')).toContainText('12-hour clock');
|
||||
|
||||
// Reset back to 24-hour
|
||||
await page.getByLabel('Time Format').click();
|
||||
await page.getByRole('option', { name: '24-hour clock' }).click();
|
||||
await Promise.all([
|
||||
page
|
||||
.locator('form')
|
||||
.filter({ hasText: 'Time Format' })
|
||||
.getByRole('button', { name: 'Save' })
|
||||
.click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.time_format === '24-hours'
|
||||
),
|
||||
]);
|
||||
.getByText(new Date().toLocaleDateString('en-GB'), { exact: true })
|
||||
.nth(0)
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that format settings persist after page reload', async ({ page }) => {
|
||||
await goToOrganizationSettings(page);
|
||||
|
||||
// Set a specific date format
|
||||
await page.getByLabel('Date Format').click();
|
||||
await page.getByRole('option', { name: 'DD/MM/YYYY' }).click();
|
||||
await Promise.all([
|
||||
page
|
||||
.locator('form')
|
||||
.filter({ hasText: 'Date Format' })
|
||||
.getByRole('button', { name: 'Save' })
|
||||
.click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/organizations/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
]);
|
||||
|
||||
// Reload and verify it persisted
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Date Format')).toContainText('DD/MM/YYYY');
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Admin Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Admin Organization Settings Access', () => {
|
||||
test('admin can see and edit organization settings', async ({ ctx, admin }) => {
|
||||
await admin.page.goto(PLAYWRIGHT_BASE_URL + '/teams/' + ctx.orgId);
|
||||
|
||||
// Organization Name section is visible
|
||||
await expect(
|
||||
admin.page.getByRole('heading', { name: 'Organization Name', level: 3 })
|
||||
).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Editable settings sections should be visible
|
||||
await expect(
|
||||
admin.page.getByRole('heading', { name: 'Billable Rate', level: 3 })
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
admin.page.getByRole('heading', { name: 'Format Settings', level: 3 })
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
admin.page.getByRole('heading', { name: 'Organization Settings', level: 3 })
|
||||
).toBeVisible();
|
||||
|
||||
// Save buttons should be visible (admin can update)
|
||||
await expect(admin.page.getByRole('button', { name: 'Save' }).first()).toBeVisible();
|
||||
|
||||
// Delete organization should NOT be visible (owner only)
|
||||
await expect(
|
||||
admin.page.getByRole('heading', { name: 'Delete Organization' })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Organization Settings Restrictions', () => {
|
||||
test('employee can see org name but not editable settings', async ({ ctx, employee }) => {
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/teams/' + ctx.orgId);
|
||||
|
||||
// Organization Name section is visible (but inputs are disabled)
|
||||
await expect(
|
||||
employee.page.getByRole('heading', { name: 'Organization Name', level: 3 })
|
||||
).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Editable settings sections should NOT be visible
|
||||
await expect(
|
||||
employee.page.getByRole('heading', { name: 'Billable Rate', level: 3 })
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.getByRole('heading', { name: 'Format Settings', level: 3 })
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.getByRole('heading', { name: 'Organization Settings', level: 3 })
|
||||
).not.toBeVisible();
|
||||
|
||||
// Save button should not be visible (employee cannot update)
|
||||
await expect(employee.page.getByRole('button', { name: 'Save' })).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
// TODO: Test 12-hour clock format
|
||||
|
||||
@@ -1,37 +1,34 @@
|
||||
import { test, expect } from '../playwright/fixtures';
|
||||
import { PLAYWRIGHT_BASE_URL, TEST_USER_PASSWORD } from '../playwright/config';
|
||||
import type { Page } from '@playwright/test';
|
||||
import {test, expect} from '../playwright/fixtures';
|
||||
import {PLAYWRIGHT_BASE_URL} from '../playwright/config';
|
||||
|
||||
async function goToProfilePage(page: Page) {
|
||||
test('test that user name can be updated', async ({page}) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
}
|
||||
|
||||
test('test that user name can be updated', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
await page.getByLabel('Name', { exact: true }).fill('NEW NAME');
|
||||
await page.getByLabel('Name', {exact: true} ).fill('NEW NAME');
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Save' }).first().click(),
|
||||
page.getByRole('button', {name: 'Save'}).first().click(),
|
||||
page.waitForResponse('**/user/profile-information'),
|
||||
]);
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Name', { exact: true })).toHaveValue('NEW NAME');
|
||||
await expect(page.getByLabel('Name', {exact: true})).toHaveValue('NEW NAME');
|
||||
});
|
||||
|
||||
test.skip('test that user email can be updated', async ({ page }) => {
|
||||
test.skip('test that user email can be updated', async ({page}) => {
|
||||
// this does not work because of email verification currently
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
const emailId = Math.round(Math.random() * 10000);
|
||||
await page.getByLabel('Email').fill(`newemail+${emailId}@test.com`);
|
||||
await page.getByRole('button', { name: 'Save' }).first().click();
|
||||
await page.getByRole('button', {name: 'Save'}).first().click();
|
||||
await page.reload();
|
||||
await expect(page.getByLabel('Email')).toHaveValue(`newemail+${emailId}@test.com`);
|
||||
await expect(page.getByLabel('Email')).toHaveValue(
|
||||
`newemail+${emailId}@test.com`
|
||||
);
|
||||
});
|
||||
|
||||
async function createNewApiToken(page) {
|
||||
await page.getByLabel('API Key Name').fill('NEW API KEY');
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Create API Key' }).click(),
|
||||
page.waitForResponse('**/users/me/api-tokens'),
|
||||
page.getByRole('button', {name: 'Create API Key'}).click(),
|
||||
page.waitForResponse('**/users/me/api-tokens')
|
||||
]);
|
||||
|
||||
await expect(page.locator('body')).toContainText('API Token created successfully');
|
||||
@@ -39,310 +36,34 @@ async function createNewApiToken(page) {
|
||||
await expect(page.locator('body')).toContainText('NEW API KEY');
|
||||
}
|
||||
|
||||
test('test that user can create an API key', async ({ page }) => {
|
||||
test('test that user can create an API key', async ({page}) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
await createNewApiToken(page);
|
||||
});
|
||||
|
||||
test('test that creating an API key with empty name shows validation error', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
|
||||
// Wait for the API Key Name input to be visible before interacting
|
||||
const nameInput = page.getByLabel('API Key Name');
|
||||
await expect(nameInput).toBeVisible();
|
||||
|
||||
// Ensure the API Key Name input is empty
|
||||
await nameInput.fill('');
|
||||
|
||||
// Click the create button and wait for the 422 response
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse('**/users/me/api-tokens'),
|
||||
page.getByRole('button', { name: 'Create API Key' }).click(),
|
||||
]);
|
||||
|
||||
expect(response.status()).toBe(422);
|
||||
|
||||
// Verify that an error notification is shown with validation message about the name field
|
||||
await expect(page.getByText('name field is required')).toBeVisible({ timeout: 5000 });
|
||||
});
|
||||
|
||||
test('test that user can delete an API key', async ({ page }) => {
|
||||
test('test that user can delete an API key', async ({page}) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
await createNewApiToken(page);
|
||||
page.getByLabel('Delete API Token NEW API KEY').click();
|
||||
await expect(page.getByRole('dialog')).toContainText(
|
||||
'Are you sure you would like to delete this API token?'
|
||||
);
|
||||
await expect(page.getByRole('dialog')).toContainText('Are you sure you would like to delete this API token?');
|
||||
await Promise.all([
|
||||
page.getByRole('dialog').getByRole('button', { name: 'Delete' }).click(),
|
||||
page.waitForResponse('**/users/me/api-tokens'),
|
||||
page.getByRole('dialog').getByRole('button', {name: 'Delete'}).click(),
|
||||
page.waitForResponse('**/users/me/api-tokens')
|
||||
]);
|
||||
await expect(page.locator('body')).not.toContainText('NEW API KEY');
|
||||
});
|
||||
|
||||
test('test that user can revoke an API key', async ({ page }) => {
|
||||
|
||||
test('test that user can revoke an API key', async ({page}) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/user/profile');
|
||||
await createNewApiToken(page);
|
||||
page.getByLabel('Revoke API Token NEW API KEY').click();
|
||||
await expect(page.getByRole('dialog')).toContainText(
|
||||
'Are you sure you would like to revoke this API token?'
|
||||
);
|
||||
await expect(page.getByRole('dialog')).toContainText('Are you sure you would like to revoke this API token?');
|
||||
await Promise.all([
|
||||
page.getByRole('dialog').getByRole('button', { name: 'Revoke' }).click(),
|
||||
page.waitForResponse('**/users/me/api-tokens'),
|
||||
page.getByRole('dialog').getByRole('button', {name: 'Revoke'}).click(),
|
||||
page.waitForResponse('**/users/me/api-tokens')
|
||||
]);
|
||||
await expect(page.getByRole('button', { name: 'Revoke' })).toBeHidden();
|
||||
await expect(page.getByRole('button', {name: 'Revoke'})).toBeHidden();
|
||||
await expect(page.locator('body')).toContainText('NEW API KEY');
|
||||
await expect(page.locator('body')).toContainText('Revoked');
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Update Password Form Tests
|
||||
// =============================================
|
||||
|
||||
test('test that password mismatch shows error', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
// Fill in with mismatched passwords
|
||||
await page.getByLabel('Current Password').fill(TEST_USER_PASSWORD);
|
||||
await page.getByLabel('New Password').fill('newSecurePassword456');
|
||||
await page.getByLabel('Confirm Password').fill('differentPassword789');
|
||||
|
||||
// Find the form containing the Confirm Password field and click its Save button
|
||||
const passwordForm = page.getByLabel('Confirm Password').locator('xpath=ancestor::form');
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/user/password') && response.request().method() === 'PUT'
|
||||
),
|
||||
passwordForm.getByRole('button', { name: 'Save' }).click(),
|
||||
]);
|
||||
|
||||
// Verify error message about password confirmation
|
||||
await expect(page.getByText('confirmation does not match')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that short password shows validation error', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
// Fill in with a too short password
|
||||
await page.getByLabel('Current Password').fill(TEST_USER_PASSWORD);
|
||||
await page.getByLabel('New Password').fill('short');
|
||||
await page.getByLabel('Confirm Password').fill('short');
|
||||
|
||||
// Find the form containing the Confirm Password field and click its Save button
|
||||
const passwordForm = page.getByLabel('Confirm Password').locator('xpath=ancestor::form');
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/user/password') && response.request().method() === 'PUT'
|
||||
),
|
||||
passwordForm.getByRole('button', { name: 'Save' }).click(),
|
||||
]);
|
||||
|
||||
// Verify error message about password length
|
||||
await expect(page.getByText('must be at least')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that incorrect current password shows validation error', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
// Fill in with wrong current password
|
||||
await page.getByLabel('Current Password').fill('wrongCurrentPassword123');
|
||||
await page.getByLabel('New Password').fill('newSecurePassword456');
|
||||
await page.getByLabel('Confirm Password').fill('newSecurePassword456');
|
||||
|
||||
// Find the form containing the Confirm Password field and click its Save button
|
||||
const passwordForm = page.getByLabel('Confirm Password').locator('xpath=ancestor::form');
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/user/password') && response.request().method() === 'PUT'
|
||||
),
|
||||
passwordForm.getByRole('button', { name: 'Save' }).click(),
|
||||
]);
|
||||
|
||||
// Verify error message about incorrect password
|
||||
await expect(page.getByText('does not match')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that password can be updated successfully', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
const newPassword = 'newSecurePassword456';
|
||||
|
||||
// Change password to new password
|
||||
await page.getByLabel('Current Password').fill(TEST_USER_PASSWORD);
|
||||
await page.getByLabel('New Password').fill(newPassword);
|
||||
await page.getByLabel('Confirm Password').fill(newPassword);
|
||||
|
||||
const passwordForm = page.getByLabel('Confirm Password').locator('xpath=ancestor::form');
|
||||
const responsePromise = page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/user/password') && response.request().method() === 'PUT'
|
||||
);
|
||||
await passwordForm.getByRole('button', { name: 'Save' }).click();
|
||||
const response = await responsePromise;
|
||||
|
||||
// Verify successful response (303 is Inertia redirect on success, means password was updated)
|
||||
expect(response.status()).toBe(303);
|
||||
|
||||
// Verify no error messages are displayed
|
||||
await expect(page.getByText('does not match')).not.toBeVisible();
|
||||
await expect(page.getByText('must be at least')).not.toBeVisible();
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Theme Selection Tests
|
||||
// =============================================
|
||||
|
||||
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"]');
|
||||
|
||||
// Change theme to dark
|
||||
await themeSelect.click();
|
||||
await page.getByRole('option', { name: 'Dark' }).click();
|
||||
|
||||
// Verify the html element has 'dark' class
|
||||
await expect(page.locator('html')).toHaveClass(/dark/);
|
||||
|
||||
// Change theme to light
|
||||
await themeSelect.click();
|
||||
await page.getByRole('option', { name: 'Light' }).click();
|
||||
|
||||
// Verify the html element has 'light' class and no 'dark' class
|
||||
await expect(page.locator('html')).toHaveClass(/light/);
|
||||
await expect(page.locator('html')).not.toHaveClass(/dark/);
|
||||
|
||||
// Verify localStorage persists the setting
|
||||
const storedTheme = await page.evaluate(() => localStorage.getItem('theme'));
|
||||
expect(storedTheme).toContain('light');
|
||||
|
||||
// Reload and verify the theme persists
|
||||
await page.reload();
|
||||
await expect(page.locator('html')).toHaveClass(/light/);
|
||||
|
||||
// Reset to system
|
||||
await page.locator('button[role="combobox"]').click();
|
||||
await page.getByRole('option', { name: 'System' }).click();
|
||||
await expect(page.getByText('System default:')).toBeVisible();
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Two Factor Authentication Tests
|
||||
// =============================================
|
||||
|
||||
test('test that password confirmation modal can be cancelled without sending API request', async ({
|
||||
page,
|
||||
}) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
// Find the Enable button in the 2FA section
|
||||
const enableButton = page
|
||||
.getByText('You have not enabled two factor authentication.')
|
||||
.locator('..')
|
||||
.getByRole('button', { name: 'Enable' });
|
||||
await enableButton.click();
|
||||
|
||||
// Verify password confirmation modal appears
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Set up listener to verify no POST request is sent to confirm-password
|
||||
let confirmPasswordRequestSent = false;
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('/user/confirm-password') && request.method() === 'POST') {
|
||||
confirmPasswordRequestSent = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Click Cancel
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'Cancel' }).click();
|
||||
|
||||
// Verify modal is closed
|
||||
await expect(page.getByRole('dialog')).not.toBeVisible();
|
||||
|
||||
// Verify no confirm-password request was sent
|
||||
expect(confirmPasswordRequestSent).toBe(false);
|
||||
});
|
||||
|
||||
test('test that password confirmation modal shows error for incorrect password', async ({
|
||||
page,
|
||||
}) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
// Find the Enable button in the 2FA section
|
||||
const enableButton = page
|
||||
.getByText('You have not enabled two factor authentication.')
|
||||
.locator('..')
|
||||
.getByRole('button', { name: 'Enable' });
|
||||
await enableButton.click();
|
||||
|
||||
// Verify password confirmation modal appears
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Enter incorrect password and confirm
|
||||
await page.getByPlaceholder('Password').fill('wrongpassword123');
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'Confirm' }).click();
|
||||
|
||||
// Should show error message (wait longer for API response)
|
||||
await expect(page.getByRole('dialog').getByText('incorrect')).toBeVisible({ timeout: 10000 });
|
||||
});
|
||||
|
||||
test('test that 2FA can be enabled with correct password', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
// Verify 2FA is not enabled
|
||||
await expect(page.getByText('You have not enabled two factor authentication.')).toBeVisible();
|
||||
|
||||
// Find the Enable button in the 2FA section
|
||||
const enableButton = page
|
||||
.getByText('You have not enabled two factor authentication.')
|
||||
.locator('..')
|
||||
.getByRole('button', { name: 'Enable' });
|
||||
await enableButton.click();
|
||||
|
||||
// Verify password confirmation modal appears
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// Enter correct password and confirm
|
||||
await page.getByPlaceholder('Password').fill(TEST_USER_PASSWORD);
|
||||
await Promise.all([
|
||||
page.getByRole('dialog').getByRole('button', { name: 'Confirm' }).click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/user/two-factor-authentication') &&
|
||||
response.request().method() === 'POST'
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify QR code is shown
|
||||
await expect(page.getByRole('heading', { name: 'Finish enabling two factor' })).toBeVisible();
|
||||
await expect(page.getByText('Setup Key:')).toBeVisible();
|
||||
await expect(page.getByLabel('Code')).toBeVisible();
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Logout Other Browser Sessions Tests
|
||||
// =============================================
|
||||
|
||||
test('test that logout other browser sessions works with correct password', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
|
||||
await page.getByRole('button', { name: 'Log Out Other Browser Sessions' }).click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
await page.getByPlaceholder('Password').fill(TEST_USER_PASSWORD);
|
||||
await Promise.all([
|
||||
page
|
||||
.getByRole('dialog')
|
||||
.getByRole('button', { name: 'Log Out Other Browser Sessions' })
|
||||
.click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/user/other-browser-sessions') &&
|
||||
response.request().method() === 'DELETE'
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1,27 +1,34 @@
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, Page } from '@playwright/test';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { test } from '../playwright/fixtures';
|
||||
import { formatCentsWithOrganizationDefaults } from './utils/money';
|
||||
import { createProjectViaApi, createProjectMemberViaApi, type TestContext } from './utils/api';
|
||||
import type { CurrencyFormat } from '../resources/js/packages/ui/src/utils/money';
|
||||
import { NumberFormat } from '@/packages/ui/src/utils/number';
|
||||
|
||||
async function createProjectWithMemberViaApi(ctx: TestContext, page: Page, projectName: string) {
|
||||
const project = await createProjectViaApi(ctx, { name: projectName });
|
||||
await createProjectMemberViaApi(ctx, project.id, { member_id: ctx.memberId });
|
||||
|
||||
// Navigate to the project detail page
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/projects/' + project.id);
|
||||
await expect(page.getByTestId('project_member_table').getByRole('row').first()).toBeVisible();
|
||||
return project;
|
||||
async function goToProjectsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
}
|
||||
|
||||
test('test that updating project member billable rate works for existing time entries', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
const newProjectName =
|
||||
'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
const newBillableRate = Math.round(Math.random() * 10000);
|
||||
await createProjectWithMemberViaApi(ctx, page, newProjectName);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
await page.getByText(newProjectName).click();
|
||||
await page.getByRole('button', { name: 'Add Member' }).click();
|
||||
|
||||
await expect(page.getByText('Add Project Member').first()).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Select a member' }).click();
|
||||
await page.keyboard.press('Enter');
|
||||
await page.getByRole('button', { name: 'Add Project Member' }).click();
|
||||
|
||||
await page
|
||||
.getByTestId('project_member_table')
|
||||
@@ -29,7 +36,9 @@ test('test that updating project member billable rate works for existing time en
|
||||
.first()
|
||||
.getByRole('button')
|
||||
.click();
|
||||
await page.getByRole('menuitem', { name: 'Edit Project Member' }).click();
|
||||
await page
|
||||
.getByRole('menuitem', { name: 'Edit Project Member' })
|
||||
.click();
|
||||
await page.getByLabel('Billable Rate').fill(newBillableRate.toString());
|
||||
await page.getByRole('button', { name: 'Update Project Member' }).click();
|
||||
|
||||
@@ -46,7 +55,8 @@ test('test that updating project member billable rate works for existing time en
|
||||
response.url().includes('/project-members/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.billable_rate === newBillableRate * 100
|
||||
(await response.json()).data.billable_rate ===
|
||||
newBillableRate * 100
|
||||
),
|
||||
]);
|
||||
await expect(
|
||||
@@ -56,197 +66,3 @@ test('test that updating project member billable rate works for existing time en
|
||||
.getByText(formatCentsWithOrganizationDefaults(newBillableRate * 100))
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that project member edit modal can be cancelled without sending API request', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const projectName = 'Cancel Test ' + Math.floor(1 + Math.random() * 10000);
|
||||
|
||||
await createProjectWithMemberViaApi(ctx, page, projectName);
|
||||
|
||||
// Open the edit modal
|
||||
await page
|
||||
.getByTestId('project_member_table')
|
||||
.getByRole('row')
|
||||
.first()
|
||||
.getByRole('button')
|
||||
.click();
|
||||
await page.getByRole('menuitem', { name: 'Edit Project Member' }).click();
|
||||
|
||||
// Verify the modal is open and shows the member name
|
||||
await expect(page.getByRole('heading', { name: 'Edit Project Member' })).toBeVisible();
|
||||
await expect(page.getByRole('dialog').getByText('John Doe')).toBeVisible();
|
||||
|
||||
// Enter a new billable rate
|
||||
await page.getByLabel('Billable Rate').fill('999');
|
||||
|
||||
// Set up listener to verify no PUT request is sent
|
||||
let putRequestSent = false;
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('/project-members/') && request.method() === 'PUT') {
|
||||
putRequestSent = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Click Cancel
|
||||
await page.getByRole('button', { name: 'Cancel' }).click();
|
||||
|
||||
// Verify the modal is closed
|
||||
await expect(page.getByRole('heading', { name: 'Edit Project Member' })).not.toBeVisible();
|
||||
|
||||
// Verify no PUT request was sent
|
||||
expect(putRequestSent).toBe(false);
|
||||
});
|
||||
|
||||
test('test that project member update without billable rate change skips confirmation and completes', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const projectName = 'No Change ' + Math.floor(1 + Math.random() * 10000);
|
||||
|
||||
await createProjectWithMemberViaApi(ctx, page, projectName);
|
||||
|
||||
// Open the edit modal
|
||||
await page
|
||||
.getByTestId('project_member_table')
|
||||
.getByRole('row')
|
||||
.first()
|
||||
.getByRole('button')
|
||||
.click();
|
||||
await page.getByRole('menuitem', { name: 'Edit Project Member' }).click();
|
||||
|
||||
// Click Update without changing anything - no confirmation modal since rate didn't change
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/project-members/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('button', { name: 'Update Project Member' }).click(),
|
||||
]);
|
||||
|
||||
// Verify the edit modal is closed (confirmation modal was skipped)
|
||||
await expect(page.getByRole('heading', { name: 'Edit Project Member' })).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that billable rate confirmation modal can be cancelled without sending API request', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const projectName = 'Rate Cancel ' + Math.floor(1 + Math.random() * 10000);
|
||||
const newBillableRate = Math.round(Math.random() * 10000);
|
||||
|
||||
await createProjectWithMemberViaApi(ctx, page, projectName);
|
||||
|
||||
// Open the edit modal
|
||||
await page
|
||||
.getByTestId('project_member_table')
|
||||
.getByRole('row')
|
||||
.first()
|
||||
.getByRole('button')
|
||||
.click();
|
||||
await page.getByRole('menuitem', { name: 'Edit Project Member' }).click();
|
||||
|
||||
// Change the billable rate
|
||||
await page.getByLabel('Billable Rate').fill(newBillableRate.toString());
|
||||
|
||||
// Set up listener to verify no PUT request is sent
|
||||
let putRequestSent = false;
|
||||
page.on('request', (request) => {
|
||||
if (request.url().includes('/project-members/') && request.method() === 'PUT') {
|
||||
putRequestSent = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Click Update - this should show the confirmation modal
|
||||
await page.getByRole('button', { name: 'Update Project Member' }).click();
|
||||
|
||||
// Verify the confirmation modal is shown
|
||||
await expect(page.getByText('update all existing time entries')).toBeVisible();
|
||||
|
||||
// Click Cancel to close the confirmation modal without updating
|
||||
await page.getByRole('button', { name: 'Cancel' }).click();
|
||||
|
||||
// Verify the confirmation modal is closed but edit modal is still open
|
||||
await expect(page.getByText('update all existing time entries')).not.toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Edit Project Member' })).toBeVisible();
|
||||
|
||||
// Close the edit modal
|
||||
await page.getByRole('dialog').getByRole('button', { name: 'Cancel' }).click();
|
||||
|
||||
// Verify the edit modal is closed
|
||||
await expect(page.getByRole('heading', { name: 'Edit Project Member' })).not.toBeVisible();
|
||||
|
||||
// Verify no PUT request was sent
|
||||
expect(putRequestSent).toBe(false);
|
||||
});
|
||||
|
||||
test('test that clearing billable rate reverts to project default', async ({ page, ctx }) => {
|
||||
const projectName = 'Revert Default ' + Math.floor(1 + Math.random() * 10000);
|
||||
const customRate = Math.round(100 + Math.random() * 10000);
|
||||
|
||||
await createProjectWithMemberViaApi(ctx, page, projectName);
|
||||
|
||||
// Verify the billable rate shows "--" (project default) initially
|
||||
await expect(
|
||||
page.getByTestId('project_member_table').getByRole('row').first().getByText('--')
|
||||
).toBeVisible();
|
||||
|
||||
// Set a custom billable rate
|
||||
await page
|
||||
.getByTestId('project_member_table')
|
||||
.getByRole('row')
|
||||
.first()
|
||||
.getByRole('button')
|
||||
.click();
|
||||
await page.getByRole('menuitem', { name: 'Edit Project Member' }).click();
|
||||
await page.getByLabel('Billable Rate').fill(customRate.toString());
|
||||
await page.getByRole('button', { name: 'Update Project Member' }).click();
|
||||
|
||||
// Confirm the billable rate update
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Yes, update existing time' }).click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/project-members/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify the custom rate is shown in the table (not "--")
|
||||
await expect(
|
||||
page.getByTestId('project_member_table').getByRole('row').first().getByText('--')
|
||||
).not.toBeVisible();
|
||||
|
||||
// Now clear the billable rate to revert to project default
|
||||
await page
|
||||
.getByTestId('project_member_table')
|
||||
.getByRole('row')
|
||||
.first()
|
||||
.getByRole('button')
|
||||
.click();
|
||||
await page.getByRole('menuitem', { name: 'Edit Project Member' }).click();
|
||||
|
||||
// Set billable rate to 0 to revert to project default
|
||||
await page.getByLabel('Billable Rate').fill('0');
|
||||
await page.getByRole('button', { name: 'Update Project Member' }).click();
|
||||
|
||||
// Confirm the billable rate update
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Yes, update existing time' }).click(),
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/project-members/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify the billable rate shows "--" again (project default)
|
||||
await expect(
|
||||
page.getByTestId('project_member_table').getByRole('row').first().getByText('--')
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -1,32 +1,19 @@
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { expect, Page } from '@playwright/test';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { test } from '../playwright/fixtures';
|
||||
import { formatCentsWithOrganizationDefaults } from './utils/money';
|
||||
import {
|
||||
createProjectViaApi,
|
||||
createPublicProjectViaApi,
|
||||
createTaskViaApi,
|
||||
createClientViaApi,
|
||||
createTimeEntryViaApi,
|
||||
archiveProjectViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
import type { CurrencyFormat } from '../resources/js/packages/ui/src/utils/money';
|
||||
|
||||
async function goToProjectsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
}
|
||||
|
||||
// Helper to clear localStorage before tests that check persistence
|
||||
async function clearProjectTableState(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
localStorage.removeItem('project-table-state');
|
||||
});
|
||||
}
|
||||
|
||||
// Create new project via modal
|
||||
test('test that creating and deleting a new project via the modal works', async ({ page }) => {
|
||||
const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
test('test that creating and deleting a new project via the modal works', async ({
|
||||
page,
|
||||
}) => {
|
||||
const newProjectName =
|
||||
'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
@@ -44,10 +31,16 @@ test('test that creating and deleting a new project via the modal works', async
|
||||
),
|
||||
]);
|
||||
|
||||
await expect(page.getByTestId('project_table')).toContainText(newProjectName);
|
||||
const moreButton = page.locator("[aria-label='Actions for Project " + newProjectName + "']");
|
||||
await moreButton.click();
|
||||
const deleteButton = page.locator("[aria-label='Delete Project " + newProjectName + "']");
|
||||
await expect(page.getByTestId('project_table')).toContainText(
|
||||
newProjectName
|
||||
);
|
||||
const moreButton = page.locator(
|
||||
"[aria-label='Actions for Project " + newProjectName + "']"
|
||||
);
|
||||
moreButton.click();
|
||||
const deleteButton = page.locator(
|
||||
"[aria-label='Delete Project " + newProjectName + "']"
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
deleteButton.click(),
|
||||
@@ -58,88 +51,68 @@ test('test that creating and deleting a new project via the modal works', async
|
||||
response.status() === 204
|
||||
),
|
||||
]);
|
||||
await expect(page.getByTestId('project_table')).not.toContainText(newProjectName);
|
||||
await expect(page.getByTestId('project_table')).not.toContainText(
|
||||
newProjectName
|
||||
);
|
||||
});
|
||||
|
||||
// Helper to select a status filter using the new dropdown UI
|
||||
async function selectStatusFilter(page: Page, status: 'Active' | 'Archived') {
|
||||
// Click the Filter button to open the dropdown
|
||||
await page.getByRole('button', { name: 'Filter projects' }).click();
|
||||
// Click on Status submenu
|
||||
await page.getByRole('menuitem', { name: 'Status' }).click();
|
||||
// Select the status option
|
||||
await page.getByRole('menuitem', { name: status }).click();
|
||||
}
|
||||
|
||||
// Helper to remove status filter by clicking the X on the badge
|
||||
async function removeStatusFilter(page: Page) {
|
||||
const statusBadge = page.getByTestId('status-filter-badge');
|
||||
// Click the remove button (second button in the badge, contains XMarkIcon)
|
||||
await statusBadge.locator('button').last().click();
|
||||
}
|
||||
|
||||
test('test that archiving and unarchiving projects works', async ({ page, ctx }) => {
|
||||
const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
test('test that archiving and unarchiving projects works', async ({ page }) => {
|
||||
const newProjectName =
|
||||
'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
// Archive the project
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Archive').first().click();
|
||||
await Promise.all([
|
||||
page.getByRole('menuitem').getByText('Archive').first().click(),
|
||||
expect(page.getByText(newProjectName)).not.toBeVisible(),
|
||||
]);
|
||||
await Promise.all([
|
||||
page.getByRole('tab', { name: 'Archived' }).click(),
|
||||
expect(page.getByText(newProjectName)).toBeVisible(),
|
||||
]);
|
||||
|
||||
// Project should still be visible since default is "all" (no filter)
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
// Apply Active filter - archived project should disappear
|
||||
await selectStatusFilter(page, 'Active');
|
||||
await expect(page.getByText(newProjectName)).not.toBeVisible();
|
||||
|
||||
// Remove Active filter and apply Archived filter
|
||||
await removeStatusFilter(page);
|
||||
await selectStatusFilter(page, 'Archived');
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
// Unarchive the project
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Unarchive').first().click();
|
||||
|
||||
// Project should disappear from Archived view
|
||||
await expect(page.getByText(newProjectName)).not.toBeVisible();
|
||||
|
||||
// Remove Archived filter and apply Active filter to see the project
|
||||
await removeStatusFilter(page);
|
||||
await selectStatusFilter(page, 'Active');
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
await Promise.all([
|
||||
page.getByRole('menuitem').getByText('Unarchive').first().click(),
|
||||
expect(page.getByText(newProjectName)).not.toBeVisible(),
|
||||
]);
|
||||
await Promise.all([
|
||||
page.getByRole('tab', { name: 'Active' }).click(),
|
||||
expect(page.getByText(newProjectName)).toBeVisible(),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that updating billable rate works with existing time entries', async ({ page, ctx }) => {
|
||||
const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
test('test that updating billable rate works with existing time entries', async ({
|
||||
page,
|
||||
}) => {
|
||||
const newProjectName =
|
||||
'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
const newBillableRate = Math.round(Math.random() * 10000);
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').first().click();
|
||||
|
||||
// Set billable default to Billable
|
||||
await page.getByRole('dialog').locator('#billable').click();
|
||||
await page.getByRole('option', { name: 'Billable', exact: true }).click();
|
||||
|
||||
// Set billable rate to Custom Rate
|
||||
await page.getByRole('dialog').locator('#billableRateType').click();
|
||||
await page.getByRole('option', { name: 'Custom Rate' }).click();
|
||||
|
||||
await page.getByPlaceholder('Billable Rate').fill(newBillableRate.toString());
|
||||
await page.getByText('Non-Billable').click();
|
||||
await page.getByText('Custom Rate').click();
|
||||
await page
|
||||
.getByPlaceholder('Billable Rate')
|
||||
.fill(newBillableRate.toString());
|
||||
await page.getByRole('button', { name: 'Update Project' }).click();
|
||||
|
||||
await Promise.all([
|
||||
page.locator('button').filter({ hasText: 'Yes, update existing time' }).click(),
|
||||
page
|
||||
.locator('button').filter({ hasText: 'Yes, update existing time' })
|
||||
.click(),
|
||||
page.waitForRequest(
|
||||
async (request) =>
|
||||
request.url().includes('/projects/') &&
|
||||
@@ -151,7 +124,8 @@ test('test that updating billable rate works with existing time entries', async
|
||||
response.url().includes('/projects/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.billable_rate === newBillableRate * 100
|
||||
(await response.json()).data.billable_rate ===
|
||||
newBillableRate * 100
|
||||
),
|
||||
]);
|
||||
await expect(
|
||||
@@ -162,733 +136,22 @@ test('test that updating billable rate works with existing time entries', async
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that creating a project with default billable rate works', async ({ page }) => {
|
||||
const newProjectName = 'Default Rate Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
// Create new project with new Client
|
||||
|
||||
// Set billable default to Billable (leaves rate type as Default Rate)
|
||||
await page.getByRole('dialog').locator('#billable').click();
|
||||
await page.getByRole('option', { name: 'Billable', exact: true }).click();
|
||||
// Create new project with existing Client
|
||||
|
||||
// Verify rate type is "Default Rate" and the rate input is disabled
|
||||
await expect(page.getByRole('dialog').locator('#billableRateType')).toContainText(
|
||||
'Default Rate'
|
||||
);
|
||||
await expect(page.getByPlaceholder('Billable Rate')).toBeDisabled();
|
||||
// Delete project via More Options
|
||||
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Create Project' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 201 &&
|
||||
(await response.json()).data.is_billable === true &&
|
||||
(await response.json()).data.billable_rate === null
|
||||
),
|
||||
]);
|
||||
// Test that project task count is displayed correctly
|
||||
|
||||
await expect(page.getByTestId('project_table')).toContainText(newProjectName);
|
||||
});
|
||||
// Test that active / archive / all filter works (once implemented)
|
||||
|
||||
test('test that creating a non-billable project works', async ({ page }) => {
|
||||
const newProjectName = 'Non-Billable Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
// Edit Project Modal Test
|
||||
|
||||
// Billable default should already be "Non-billable" by default
|
||||
await expect(page.getByRole('dialog').locator('#billable')).toContainText('Non-billable');
|
||||
// Add Project with billable rate
|
||||
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Create Project' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 201 &&
|
||||
(await response.json()).data.is_billable === false &&
|
||||
(await response.json()).data.billable_rate === null
|
||||
),
|
||||
]);
|
||||
// Edit Project with billable rate
|
||||
|
||||
await expect(page.getByTestId('project_table')).toContainText(newProjectName);
|
||||
});
|
||||
// Edit Project Member Billable Rate
|
||||
|
||||
test('test that switching from custom rate to default rate clears billable rate', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const newProjectName = 'Rate Switch Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
// Create a project with an existing custom billable rate
|
||||
await createProjectViaApi(ctx, {
|
||||
name: newProjectName,
|
||||
is_billable: true,
|
||||
billable_rate: 15000,
|
||||
});
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').first().click();
|
||||
|
||||
// Verify it loaded as Billable with Custom Rate
|
||||
await expect(page.getByRole('dialog').locator('#billable')).toContainText('Billable');
|
||||
await expect(page.getByRole('dialog').locator('#billableRateType')).toContainText(
|
||||
'Custom Rate'
|
||||
);
|
||||
|
||||
// Switch to Default Rate
|
||||
await page.getByRole('dialog').locator('#billableRateType').click();
|
||||
await page.getByRole('option', { name: 'Default Rate' }).click();
|
||||
|
||||
// Rate input should now be disabled
|
||||
await expect(page.getByPlaceholder('Billable Rate')).toBeDisabled();
|
||||
|
||||
// Submit — billable_rate changes from 15000 to null, so confirmation dialog appears
|
||||
await page.getByRole('button', { name: 'Update Project' }).click();
|
||||
await Promise.all([
|
||||
page.locator('button').filter({ hasText: 'Yes, update existing time' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.is_billable === true &&
|
||||
(await response.json()).data.billable_rate === null
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that switching from billable to non-billable preserves rate settings', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const newProjectName = 'Billable Reset Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
// Create a project with a custom billable rate
|
||||
await createProjectViaApi(ctx, {
|
||||
name: newProjectName,
|
||||
is_billable: true,
|
||||
billable_rate: 20000,
|
||||
});
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').first().click();
|
||||
|
||||
// Verify it loaded correctly as Billable with Custom Rate
|
||||
await expect(page.getByRole('dialog').locator('#billable')).toContainText('Billable');
|
||||
await expect(page.getByRole('dialog').locator('#billableRateType')).toContainText(
|
||||
'Custom Rate'
|
||||
);
|
||||
|
||||
// Switch to Non-billable
|
||||
await page.getByRole('dialog').locator('#billable').click();
|
||||
await page.getByRole('option', { name: 'Non-billable' }).click();
|
||||
|
||||
// Rate type should still be Custom Rate (not reset)
|
||||
await expect(page.getByRole('dialog').locator('#billableRateType')).toContainText(
|
||||
'Custom Rate'
|
||||
);
|
||||
|
||||
// Submit and verify project is non-billable but keeps its custom rate
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Update Project' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
(await response.json()).data.is_billable === false &&
|
||||
(await response.json()).data.billable_rate === 20000
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that editing an existing billable project with default rate loads correctly', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const newProjectName = 'Default Rate Edit Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
// Create a project that is billable but has no custom rate (= default rate)
|
||||
await createProjectViaApi(ctx, {
|
||||
name: newProjectName,
|
||||
is_billable: true,
|
||||
billable_rate: null,
|
||||
});
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').first().click();
|
||||
|
||||
// Verify it loaded as Billable with Default Rate
|
||||
await expect(page.getByRole('dialog').locator('#billable')).toContainText('Billable');
|
||||
await expect(page.getByRole('dialog').locator('#billableRateType')).toContainText(
|
||||
'Default Rate'
|
||||
);
|
||||
await expect(page.getByPlaceholder('Billable Rate')).toBeDisabled();
|
||||
});
|
||||
|
||||
// Sorting tests
|
||||
test('test that sorting projects by all columns works', async ({ page, ctx }) => {
|
||||
// Seed projects with distinct values for each sortable column
|
||||
const clientAlpha = await createClientViaApi(ctx, { name: 'Alpha Client' });
|
||||
const clientBeta = await createClientViaApi(ctx, { name: 'Beta Client' });
|
||||
|
||||
// Project A: client Alpha, low billable rate, has estimated time, active
|
||||
const projectA = await createProjectViaApi(ctx, {
|
||||
name: 'AAA Project',
|
||||
client_id: clientAlpha.id,
|
||||
is_billable: true,
|
||||
billable_rate: 5000,
|
||||
estimated_time: 36000, // 10h
|
||||
});
|
||||
// Add 1h of time entries (10% progress)
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
duration: '1h',
|
||||
projectId: projectA.id,
|
||||
});
|
||||
|
||||
// Project B: client Beta, high billable rate, has estimated time, archived
|
||||
const projectB = await createProjectViaApi(ctx, {
|
||||
name: 'BBB Project',
|
||||
client_id: clientBeta.id,
|
||||
is_billable: true,
|
||||
billable_rate: 15000,
|
||||
estimated_time: 7200, // 2h
|
||||
});
|
||||
// Add 1h of time entries (50% progress)
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
duration: '1h',
|
||||
projectId: projectB.id,
|
||||
});
|
||||
await archiveProjectViaApi(ctx, {
|
||||
...projectB,
|
||||
client_id: clientBeta.id,
|
||||
billable_rate: 15000,
|
||||
estimated_time: 7200,
|
||||
});
|
||||
|
||||
// Project C: no client, medium billable rate, no estimated time, active
|
||||
const projectC = await createProjectViaApi(ctx, {
|
||||
name: 'CCC Project',
|
||||
is_billable: true,
|
||||
billable_rate: 10000,
|
||||
});
|
||||
// Add 3h of time entries
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
duration: '3h',
|
||||
projectId: projectC.id,
|
||||
});
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
await expect(page.getByTestId('project_table')).toBeVisible();
|
||||
await expect(page.getByText('AAA Project')).toBeVisible();
|
||||
await expect(page.getByText('BBB Project')).toBeVisible();
|
||||
await expect(page.getByText('CCC Project')).toBeVisible();
|
||||
|
||||
// Helper to get the visual order of our seeded projects by reading
|
||||
// all row text in a single evaluate call (avoids locator timing issues)
|
||||
const seededNames = ['AAA Project', 'BBB Project', 'CCC Project'];
|
||||
const getOrder = async (): Promise<string[]> => {
|
||||
const allRowTexts = await page.evaluate(() => {
|
||||
const table = document.querySelector('[data-testid="project_table"]');
|
||||
if (!table) return [];
|
||||
const rows = table.querySelectorAll('[role="row"]');
|
||||
return Array.from(rows).map((row) => row.textContent ?? '');
|
||||
});
|
||||
const order: string[] = [];
|
||||
for (const text of allRowTexts) {
|
||||
const match = seededNames.find((name) => text.includes(name));
|
||||
if (match) order.push(match);
|
||||
}
|
||||
return order;
|
||||
};
|
||||
|
||||
// Helper: click a column header and wait for sort to apply.
|
||||
// expectedFirstAmongSeeded = which of our 3 seeded projects should appear first
|
||||
const clickSortHeader = async (headerText: string, expectedFirstAmongSeeded: string) => {
|
||||
const header = page
|
||||
.locator('[data-testid="project_table"] .select-none', {
|
||||
hasText: headerText,
|
||||
})
|
||||
.first();
|
||||
await header.click();
|
||||
// Wait until the expected project appears before the others among our seeded set
|
||||
await page.waitForFunction(
|
||||
({ expected, names }) => {
|
||||
const table = document.querySelector('[data-testid="project_table"]');
|
||||
if (!table) return false;
|
||||
const rows = table.querySelectorAll('[role="row"]');
|
||||
let firstSeededIdx = -1;
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const text = rows[i].textContent ?? '';
|
||||
if (names.some((n: string) => text.includes(n))) {
|
||||
firstSeededIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (firstSeededIdx === -1) return false;
|
||||
return (rows[firstSeededIdx].textContent ?? '').includes(expected);
|
||||
},
|
||||
{ expected: expectedFirstAmongSeeded, names: seededNames },
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
};
|
||||
|
||||
// --- Sort by Name ---
|
||||
// Default is name asc (A-Z)
|
||||
let order = await getOrder();
|
||||
expect(order).toEqual(['AAA Project', 'BBB Project', 'CCC Project']);
|
||||
|
||||
// Click to toggle to Z-A
|
||||
await clickSortHeader('Name', 'CCC Project');
|
||||
order = await getOrder();
|
||||
expect(order).toEqual(['CCC Project', 'BBB Project', 'AAA Project']);
|
||||
|
||||
// --- Sort by Client (text: first click = A-Z, no-client last) ---
|
||||
await clickSortHeader('Client', 'AAA Project');
|
||||
order = await getOrder();
|
||||
expect(order).toEqual(['AAA Project', 'BBB Project', 'CCC Project']); // Alpha, Beta, No client
|
||||
|
||||
// Reverse: Z-A, no-client still last
|
||||
await clickSortHeader('Client', 'BBB Project');
|
||||
order = await getOrder();
|
||||
expect(order).toEqual(['BBB Project', 'AAA Project', 'CCC Project']); // Beta, Alpha, No client
|
||||
|
||||
// --- Sort by Total Time (numeric: first click = highest first) ---
|
||||
await clickSortHeader('Total Time', 'CCC Project');
|
||||
order = await getOrder();
|
||||
expect(order[0]).toBe('CCC Project'); // C=3h first, A and B tied at 1h
|
||||
|
||||
// Reverse: lowest first
|
||||
await clickSortHeader('Total Time', 'AAA Project');
|
||||
order = await getOrder();
|
||||
expect(order[2]).toBe('CCC Project'); // C=3h last
|
||||
|
||||
// --- Sort by Billable Rate (numeric: first click = highest first) ---
|
||||
await clickSortHeader('Billable Rate', 'BBB Project');
|
||||
order = await getOrder();
|
||||
expect(order).toEqual(['BBB Project', 'CCC Project', 'AAA Project']); // 15000, 10000, 5000
|
||||
|
||||
// Reverse: lowest first
|
||||
await clickSortHeader('Billable Rate', 'AAA Project');
|
||||
order = await getOrder();
|
||||
expect(order).toEqual(['AAA Project', 'CCC Project', 'BBB Project']); // 5000, 10000, 15000
|
||||
|
||||
// --- Sort by Progress (numeric: first click = highest first, no-estimate last) ---
|
||||
await clickSortHeader('Progress', 'BBB Project');
|
||||
order = await getOrder();
|
||||
expect(order).toEqual(['BBB Project', 'AAA Project', 'CCC Project']); // 50%, 10%, no estimate
|
||||
|
||||
// Reverse: lowest first, no-estimate still last
|
||||
await clickSortHeader('Progress', 'AAA Project');
|
||||
order = await getOrder();
|
||||
expect(order).toEqual(['AAA Project', 'BBB Project', 'CCC Project']); // 10%, 50%, no estimate
|
||||
|
||||
// --- Sort by Status (first click = active first, archived last) ---
|
||||
await expect(async () => {
|
||||
await clickSortHeader('Status', 'AAA Project');
|
||||
order = await getOrder();
|
||||
expect(order.indexOf('BBB Project')).toBeGreaterThan(order.indexOf('AAA Project'));
|
||||
expect(order.indexOf('BBB Project')).toBeGreaterThan(order.indexOf('CCC Project'));
|
||||
}).toPass({ timeout: 5000 });
|
||||
|
||||
// Reverse: archived first
|
||||
await expect(async () => {
|
||||
await clickSortHeader('Status', 'BBB Project');
|
||||
order = await getOrder();
|
||||
expect(order.indexOf('BBB Project')).toBeLessThan(order.indexOf('AAA Project'));
|
||||
expect(order.indexOf('BBB Project')).toBeLessThan(order.indexOf('CCC Project'));
|
||||
}).toPass({ timeout: 5000 });
|
||||
});
|
||||
|
||||
// Filter tests
|
||||
test('test that filtering projects by status works', async ({ page, ctx }) => {
|
||||
const newProjectName = 'Filter Test Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Archive the project
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Archive').first().click();
|
||||
|
||||
// Project should still be visible (default is "all" - no filter)
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
// Apply Active filter - archived project should disappear
|
||||
await selectStatusFilter(page, 'Active');
|
||||
await expect(page.getByText(newProjectName)).not.toBeVisible();
|
||||
|
||||
// Remove Active filter - project should reappear (back to "all")
|
||||
await removeStatusFilter(page);
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
// Apply Archived filter - project should still be visible
|
||||
await selectStatusFilter(page, 'Archived');
|
||||
await expect(page.getByText(newProjectName)).toBeVisible();
|
||||
|
||||
// Remove Archived filter and apply Active filter - project should not be visible
|
||||
await removeStatusFilter(page);
|
||||
await selectStatusFilter(page, 'Active');
|
||||
await expect(page.getByText(newProjectName)).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that filter state persists after page reload', async ({ page }) => {
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
|
||||
// Apply Active status filter
|
||||
await selectStatusFilter(page, 'Active');
|
||||
|
||||
// Verify the filter badge is visible
|
||||
await expect(page.getByTestId('status-filter-badge')).toBeVisible();
|
||||
|
||||
// Reload the page
|
||||
await page.reload();
|
||||
|
||||
// Verify the filter badge is still visible after reload
|
||||
await expect(page.getByTestId('status-filter-badge')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that sort state persists after page reload', async ({ page }) => {
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
|
||||
// Click on Name header twice to sort descending
|
||||
const nameHeader = page.getByText('Name').first();
|
||||
await nameHeader.click();
|
||||
await expect(nameHeader.locator('svg')).toBeVisible();
|
||||
await nameHeader.click();
|
||||
|
||||
// Reload the page
|
||||
await page.reload();
|
||||
|
||||
// Verify descending sort indicator is visible on Name column
|
||||
await expect(page.getByTestId('project_table')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that custom billable rate is displayed correctly on project detail page', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const newProjectName = 'Billable Rate Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
const newBillableRate = Math.round(10 + Math.random() * 1000);
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Edit the project to set a custom billable rate
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').first().click();
|
||||
|
||||
// Set billable default to Billable
|
||||
await page.getByRole('dialog').locator('#billable').click();
|
||||
await page.getByRole('option', { name: 'Billable', exact: true }).click();
|
||||
|
||||
// Set billable rate to Custom Rate
|
||||
await page.getByRole('dialog').locator('#billableRateType').click();
|
||||
await page.getByRole('option', { name: 'Custom Rate' }).click();
|
||||
|
||||
await page.getByPlaceholder('Billable Rate').fill(newBillableRate.toString());
|
||||
await page.getByRole('button', { name: 'Update Project' }).click();
|
||||
|
||||
await Promise.all([
|
||||
page.locator('button').filter({ hasText: 'Yes, update existing time' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
]);
|
||||
|
||||
// Navigate to the project detail page by clicking the project name
|
||||
await page.getByText(newProjectName).first().click();
|
||||
await page.waitForURL(/\/projects\/[a-f0-9-]+/);
|
||||
|
||||
// Verify the badge displays the correctly formatted billable rate
|
||||
const expectedFormattedRate = formatCentsWithOrganizationDefaults(newBillableRate * 100);
|
||||
await expect(page.locator('nav[aria-label="Breadcrumb"]').locator('..')).toContainText(
|
||||
expectedFormattedRate
|
||||
);
|
||||
});
|
||||
|
||||
// Tests for estimated time input (Issue #460)
|
||||
test('test that creating a project with estimated time in human-readable format works', async ({
|
||||
page,
|
||||
}) => {
|
||||
const newProjectName = 'Estimated Time Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
|
||||
// Fill in estimated time using human-readable format
|
||||
const estimatedTimeInput = page.getByPlaceholder('e.g. 2h 30m or 1.5');
|
||||
await estimatedTimeInput.fill('2h 30m');
|
||||
await estimatedTimeInput.press('Tab');
|
||||
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Create Project' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 201 &&
|
||||
// 2h 30m = 9000 seconds
|
||||
(await response.json()).data.estimated_time === 9000
|
||||
),
|
||||
]);
|
||||
|
||||
await expect(page.getByTestId('project_table')).toContainText(newProjectName);
|
||||
});
|
||||
|
||||
test('test that creating a project with estimated time using decimal notation works', async ({
|
||||
page,
|
||||
}) => {
|
||||
const newProjectName = 'Decimal Estimated Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
|
||||
// Fill in estimated time using decimal notation (1.5 hours = 1h 30m)
|
||||
const estimatedTimeInput = page.getByPlaceholder('e.g. 2h 30m or 1.5');
|
||||
await estimatedTimeInput.fill('1.5');
|
||||
await estimatedTimeInput.press('Tab');
|
||||
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Create Project' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 201 &&
|
||||
// 1.5 hours = 5400 seconds
|
||||
(await response.json()).data.estimated_time === 5400
|
||||
),
|
||||
]);
|
||||
|
||||
await expect(page.getByTestId('project_table')).toContainText(newProjectName);
|
||||
});
|
||||
|
||||
test('test that creating a project with estimated time using comma decimal notation works', async ({
|
||||
page,
|
||||
}) => {
|
||||
const newProjectName = 'Comma Decimal Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
await page.getByLabel('Project Name').fill(newProjectName);
|
||||
|
||||
// Fill in estimated time using comma decimal notation (2,5 hours = 2h 30m)
|
||||
const estimatedTimeInput = page.getByPlaceholder('e.g. 2h 30m or 1.5');
|
||||
await estimatedTimeInput.fill('2,5');
|
||||
await estimatedTimeInput.press('Tab');
|
||||
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Create Project' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 201 &&
|
||||
// 2.5 hours = 9000 seconds
|
||||
(await response.json()).data.estimated_time === 9000
|
||||
),
|
||||
]);
|
||||
|
||||
await expect(page.getByTestId('project_table')).toContainText(newProjectName);
|
||||
});
|
||||
|
||||
test('test that updating estimated time on existing project works', async ({ page, ctx }) => {
|
||||
const newProjectName = 'Update Estimated Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Edit the project to add estimated time
|
||||
await page.getByRole('row').first().getByRole('button').click();
|
||||
await page.getByRole('menuitem').getByText('Edit').first().click();
|
||||
|
||||
// Fill in estimated time
|
||||
const estimatedTimeInput = page.getByPlaceholder('e.g. 2h 30m or 1.5');
|
||||
await estimatedTimeInput.fill('4h 15m');
|
||||
await estimatedTimeInput.press('Tab');
|
||||
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Update Project' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/projects/') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200 &&
|
||||
// 4h 15m = 15300 seconds
|
||||
(await response.json()).data.estimated_time === 15300
|
||||
),
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that estimated time input displays formatted value after blur', async ({ page }) => {
|
||||
await goToProjectsOverview(page);
|
||||
await page.getByRole('button', { name: 'Create Project' }).click();
|
||||
|
||||
const estimatedTimeInput = page.getByPlaceholder('e.g. 2h 30m or 1.5');
|
||||
|
||||
// Enter time in various formats and check the displayed value
|
||||
await estimatedTimeInput.fill('90');
|
||||
await estimatedTimeInput.press('Tab');
|
||||
// 90 hours should be displayed as "90h 00min" (default format)
|
||||
await expect(estimatedTimeInput).toHaveValue(/90h/);
|
||||
|
||||
await estimatedTimeInput.fill('1:30');
|
||||
await estimatedTimeInput.press('Tab');
|
||||
// 1:30 should be displayed as "1h 30min"
|
||||
await expect(estimatedTimeInput).toHaveValue(/1h.*30/);
|
||||
});
|
||||
|
||||
test('test that editing a task name on the project detail page works', async ({ page, ctx }) => {
|
||||
const projectName = 'Task Edit Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
const originalTaskName = 'Original Task ' + Math.floor(1 + Math.random() * 10000);
|
||||
const updatedTaskName = 'Updated Task ' + Math.floor(1 + Math.random() * 10000);
|
||||
const project = await createProjectViaApi(ctx, { name: projectName });
|
||||
await createTaskViaApi(ctx, { name: originalTaskName, project_id: project.id });
|
||||
|
||||
// Navigate to the project detail page
|
||||
await goToProjectsOverview(page);
|
||||
await expect(page.getByText(projectName)).toBeVisible({ timeout: 10000 });
|
||||
await page.getByText(projectName).first().click();
|
||||
await page.waitForURL(/\/projects\/[a-f0-9-]+/);
|
||||
|
||||
// Verify task is visible
|
||||
await expect(page.getByTestId('task_table')).toContainText(originalTaskName);
|
||||
|
||||
// Open edit modal via actions menu
|
||||
const moreButton = page.locator("[aria-label='Actions for Task " + originalTaskName + "']");
|
||||
await moreButton.click();
|
||||
await page.getByTestId('task_edit').click();
|
||||
|
||||
// Update the task name
|
||||
await page.locator('#taskName').fill(updatedTaskName);
|
||||
await Promise.all([
|
||||
page.getByRole('button', { name: 'Update Task' }).click(),
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/tasks') &&
|
||||
response.request().method() === 'PUT' &&
|
||||
response.status() === 200
|
||||
),
|
||||
]);
|
||||
|
||||
// Verify updated name is shown and old name is gone
|
||||
await expect(page.getByTestId('task_table')).toContainText(updatedTaskName);
|
||||
await expect(page.getByTestId('task_table')).not.toContainText(originalTaskName);
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
test.describe('Employee Projects Restrictions', () => {
|
||||
test('employee can view public projects but cannot create', async ({ ctx, employee }) => {
|
||||
const projectName = 'EmpViewProj ' + Math.floor(Math.random() * 10000);
|
||||
await createPublicProjectViaApi(ctx, { name: projectName });
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
await expect(employee.page.getByTestId('projects_view')).toBeVisible({
|
||||
timeout: 10000,
|
||||
});
|
||||
|
||||
// Employee can see the public project
|
||||
await expect(employee.page.getByText(projectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Employee cannot see Create Project button
|
||||
await expect(
|
||||
employee.page.getByRole('button', { name: 'Create Project' })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee cannot see edit/delete/archive actions on projects', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
const projectName = 'EmpActionsProj ' + Math.floor(Math.random() * 10000);
|
||||
await createPublicProjectViaApi(ctx, { name: projectName });
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
await expect(employee.page.getByText(projectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Click the actions dropdown trigger to open the menu
|
||||
const actionsButton = employee.page.locator(
|
||||
`[aria-label='Actions for Project ${projectName}']`
|
||||
);
|
||||
await actionsButton.click();
|
||||
|
||||
// The dropdown menu items (Edit, Archive, Delete) should NOT be visible
|
||||
await expect(
|
||||
employee.page.locator(`[aria-label='Edit Project ${projectName}']`)
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.locator(`[aria-label='Archive Project ${projectName}']`)
|
||||
).not.toBeVisible();
|
||||
await expect(
|
||||
employee.page.locator(`[aria-label='Delete Project ${projectName}']`)
|
||||
).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('Employee Billable Rate Visibility', () => {
|
||||
test('employee cannot see billable rate column by default', async ({ ctx, employee }) => {
|
||||
const projectName = 'EmpBillableProj ' + Math.floor(Math.random() * 10000);
|
||||
await createPublicProjectViaApi(ctx, {
|
||||
name: projectName,
|
||||
is_billable: true,
|
||||
billable_rate: 15000,
|
||||
});
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
await expect(employee.page.getByText(projectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Billable Rate column should not be visible to employee by default
|
||||
await expect(employee.page.getByText('Billable Rate')).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('employee can see billable rate column when employees_can_see_billable_rates is enabled', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { employees_can_see_billable_rates: true });
|
||||
|
||||
const projectName = 'EmpBillableVisProj ' + Math.floor(Math.random() * 10000);
|
||||
await createPublicProjectViaApi(ctx, {
|
||||
name: projectName,
|
||||
is_billable: true,
|
||||
billable_rate: 20000,
|
||||
});
|
||||
|
||||
await employee.page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
await expect(employee.page.getByText(projectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
// Billable Rate column header should be visible
|
||||
await expect(employee.page.getByText('Billable Rate')).toBeVisible();
|
||||
|
||||
// The project row should show the formatted billable rate
|
||||
const projectRow = employee.page.getByRole('row').filter({ hasText: projectName });
|
||||
await expect(projectRow).toContainText('200');
|
||||
});
|
||||
});
|
||||
// Edit Task Name
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user