mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-10-08 05:43:18 +01:00
Compare commits
64 Commits
feature/fi
...
feature/mo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a8acd2780 | ||
|
|
0cfd5fd22b | ||
|
|
45c7377802 | ||
|
|
8e57275cef | ||
|
|
efc6b55628 | ||
|
|
c12789376d | ||
|
|
4795812b60 | ||
|
|
0e00979ab8 | ||
|
|
f1426fcb5e | ||
|
|
23f512d4a4 | ||
|
|
637475e669 | ||
|
|
3ec2abb309 | ||
|
|
3e36b1cc01 | ||
|
|
7831bc697e | ||
|
|
602a8daa1f | ||
|
|
38b448a729 | ||
|
|
e6f071f87f | ||
|
|
693a1fa7e0 | ||
|
|
77f14b696e | ||
|
|
593372bae5 | ||
|
|
db9ca51fc4 | ||
|
|
28aba7b27a | ||
|
|
453d5ed066 | ||
|
|
ed3ba0135b | ||
|
|
fb7d945c50 | ||
|
|
9958e1c09c | ||
|
|
f00d48f1c3 | ||
|
|
7edbfd5d76 | ||
|
|
1edb940557 | ||
|
|
c9330e6cb8 | ||
|
|
0e9f652d84 | ||
|
|
d29f5706ce | ||
|
|
b2849ec04a | ||
|
|
bd69cf478c | ||
|
|
5197135d00 | ||
|
|
b09b8649b8 | ||
|
|
99fafdb8d6 | ||
|
|
b02e49c7e0 | ||
|
|
8609635d74 | ||
|
|
5a07f798b3 | ||
|
|
3af69830ee | ||
|
|
a050153bcd | ||
|
|
9d9731c7ce | ||
|
|
dfe3206614 | ||
|
|
97fd882878 | ||
|
|
111e12df12 | ||
|
|
de13c07855 | ||
|
|
29a2e994cd | ||
|
|
f6d886b218 | ||
|
|
80d98b30a1 | ||
|
|
32f2f1431b | ||
|
|
8f6d584ee9 | ||
|
|
1905cbf40c | ||
|
|
c8f668238e | ||
|
|
bf11bacdee | ||
|
|
f3c6a0b8ae | ||
|
|
619c602571 | ||
|
|
600daf44d9 | ||
|
|
a1d6c92806 | ||
|
|
ce1bd6a435 | ||
|
|
79d85227c2 | ||
|
|
885abf3333 | ||
|
|
c0c8fee6be | ||
|
|
cbcd1e51f6 |
@@ -5,7 +5,8 @@ APP_KEY=base64:UNQNf1SXeASNkWux01Rj8EnHYx8FO0kAxWNDwktclkk=
|
||||
APP_DEBUG=true
|
||||
APP_URL=https://solidtime.test
|
||||
APP_FORCE_HTTPS=false
|
||||
APP_ENABLE_REGISTRATION=true
|
||||
# Supported values: on, off, invite-only (true/false are supported for backwards compatibility)
|
||||
APP_ENABLE_REGISTRATION=on
|
||||
SUPER_ADMINS=admin@example.com
|
||||
PAGINATION_PER_PAGE_DEFAULT=500
|
||||
|
||||
|
||||
27
.github/VOUCHED.td
vendored
Normal file
27
.github/VOUCHED.td
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
# Vouched contributors for solidtime.
|
||||
#
|
||||
# One handle per line, without the leading @, sorted alphabetically.
|
||||
# Prefix a handle with - to denounce them, optionally followed by a reason.
|
||||
# Format reference: https://github.com/mitchellh/vouch
|
||||
#
|
||||
# Maintainers do not need to edit this file by hand. Comment "vouch @user",
|
||||
# "unvouch @user" or "denounce @user <reason>" on any issue, pull request or
|
||||
# discussion and the vouch workflows will update this file.
|
||||
#
|
||||
# Collaborators with write access and bots are always allowed and do not need
|
||||
# an entry here.
|
||||
#
|
||||
# Seeded 2026-07-25 from the authors of every merged pull request.
|
||||
|
||||
agross
|
||||
akolenda
|
||||
bufferhead-code
|
||||
candideu
|
||||
kasparrosin
|
||||
korridor
|
||||
nikbucher tasks table sorting
|
||||
onatcer
|
||||
shrootbuck
|
||||
smilebeda
|
||||
thespyder
|
||||
utlark
|
||||
4
.github/workflows/build-onpremise.yml
vendored
4
.github/workflows/build-onpremise.yml
vendored
@@ -141,7 +141,7 @@ jobs:
|
||||
${{ env.DOCKER_REPO }}
|
||||
|
||||
- name: "Login to solidtime OnPremise Registry"
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v4.5.2
|
||||
with:
|
||||
registry: registry.on-premise.solidtime.io
|
||||
username: ${{ secrets.ONPREMISE_USERNAME }}
|
||||
@@ -195,7 +195,7 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: "Login to solidtime OnPremise Registry"
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v4.5.2
|
||||
with:
|
||||
registry: registry.on-premise.solidtime.io
|
||||
username: ${{ secrets.ONPREMISE_USERNAME }}
|
||||
|
||||
2
.github/workflows/build-private.yml
vendored
2
.github/workflows/build-private.yml
vendored
@@ -177,7 +177,7 @@ jobs:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
|
||||
- name: "Login to GitHub Container Registry"
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v4.5.2
|
||||
with:
|
||||
registry: rg.fr-par.scw.cloud/solidtime
|
||||
username: nologin
|
||||
|
||||
8
.github/workflows/build-public.yml
vendored
8
.github/workflows/build-public.yml
vendored
@@ -117,13 +117,13 @@ jobs:
|
||||
${{ env.GHCR_REPO }}
|
||||
|
||||
- name: "Login to Docker Hub Container Registry"
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v4.5.2
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: "Login to GitHub Container Registry"
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v4.5.2
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
@@ -177,13 +177,13 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: "Login to Docker Hub"
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v4.5.2
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: "Login to GHCR"
|
||||
uses: docker/login-action@v4
|
||||
uses: docker/login-action@v4.5.2
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
|
||||
75
.github/workflows/vouch-check-pr.yml
vendored
Normal file
75
.github/workflows/vouch-check-pr.yml
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
name: Vouch (check PR)
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, reopened, synchronize]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
if: >-
|
||||
github.event_name == 'pull_request_target' ||
|
||||
(github.event_name == 'issue_comment' &&
|
||||
github.event.issue.pull_request &&
|
||||
contains(github.event.comment.body, '/recheck'))
|
||||
|
||||
steps:
|
||||
# Pull requests of 50 changed lines or fewer skip the vouch requirement.
|
||||
- name: "Measure diff size"
|
||||
id: size
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REPO: ${{ github.repository }}
|
||||
PR: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
|
||||
# Changes to these files do not count towards the 50-line limit.
|
||||
# One extended regex per line, matched against the whole repo-relative
|
||||
# path, so use a leading .* to match a file in any directory.
|
||||
IGNORED: |
|
||||
package-lock\.json
|
||||
composer\.lock
|
||||
tests/.*
|
||||
e2e/.*
|
||||
.*\.(test|spec)\.(ts|js|vue)
|
||||
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# An empty list yields "^()$", which matches no filename. grep exits
|
||||
# 1 on an empty list, so swallow that rather than fail the step.
|
||||
join() { { grep -vE '^[[:space:]]*$' || true; } | paste -sd'|' -; }
|
||||
ignored="^($(join <<<"$IGNORED"))$"
|
||||
|
||||
total=$(gh api --paginate "repos/$REPO/pulls/$PR/files" \
|
||||
--jq '.[] | [.filename, .additions + .deletions] | @tsv' |
|
||||
awk -F'\t' -v ignored="$ignored" '
|
||||
$1 ~ ignored { next }
|
||||
{ n += $2 }
|
||||
END { print n+0 }')
|
||||
echo "total=$total" >> "$GITHUB_OUTPUT"
|
||||
echo "Countable diff size: $total line(s)"
|
||||
|
||||
- name: "Small patch (denounced users still blocked)"
|
||||
if: fromJSON(steps.size.outputs.total) <= 50
|
||||
uses: mitchellh/vouch/action/check-pr@v1.5.0
|
||||
with:
|
||||
pr-number: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
auto-close: true
|
||||
require-vouch: false
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: "Full vouch required"
|
||||
if: fromJSON(steps.size.outputs.total) > 50
|
||||
uses: mitchellh/vouch/action/check-pr@v1.5.0
|
||||
with:
|
||||
pr-number: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
auto-close: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
33
.github/workflows/vouch-manage-by-discussion.yml
vendored
Normal file
33
.github/workflows/vouch-manage-by-discussion.yml
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
name: Vouch (manage by discussion)
|
||||
|
||||
# Same commands as vouch-manage-by-issue.yml, but for discussion comments.
|
||||
|
||||
on:
|
||||
discussion_comment:
|
||||
types: [created]
|
||||
|
||||
concurrency:
|
||||
group: vouch-manage
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
discussions: write
|
||||
|
||||
jobs:
|
||||
manage:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
- name: "Checkout code"
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: "Apply vouch command"
|
||||
uses: mitchellh/vouch/action/manage-by-discussion@v1.5.0
|
||||
with:
|
||||
discussion-number: ${{ github.event.discussion.number }}
|
||||
comment-node-id: ${{ github.event.comment.node_id }}
|
||||
roles: admin,maintain,write
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
35
.github/workflows/vouch-manage-by-issue.yml
vendored
Normal file
35
.github/workflows/vouch-manage-by-issue.yml
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
name: Vouch (manage by issue)
|
||||
|
||||
# Maintainers comment "vouch @user", "unvouch @user" or "denounce @user <reason>"
|
||||
# on any issue or pull request, and this workflow updates .github/VOUCHED.td.
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
concurrency:
|
||||
group: vouch-manage
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
manage:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
|
||||
steps:
|
||||
- name: "Checkout code"
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: "Apply vouch command"
|
||||
uses: mitchellh/vouch/action/manage-by-issue@v1.5.0
|
||||
with:
|
||||
issue-id: ${{ github.event.issue.number }}
|
||||
comment-id: ${{ github.event.comment.id }}
|
||||
roles: admin,maintain,write
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -12,6 +12,22 @@ In order to keep the issues of the repository clean we decided to only use them
|
||||
|
||||
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.
|
||||
|
||||
### Vouched contributors
|
||||
|
||||
Pull requests from authors who are not vouched are closed automatically. This lets us keep up with the volume of AI slop pull requests without a maintainer having to triage every one of them by hand.
|
||||
|
||||
Your pull request is not affected if any of the following applies:
|
||||
|
||||
- You have write access to this repository.
|
||||
- Someone with write access has vouched for you. The list lives in [.github/VOUCHED.td](.github/VOUCHED.td).
|
||||
- Your pull request changes 50 lines or fewer. Test files and lockfiles do not count towards that number, so a small fix that comes with tests still qualifies.
|
||||
|
||||
To get vouched, open an issue or discussion before you start and explain how you intend to implement the change. We will discuss the approach with you, and only once we have agreed on the implementation does a maintainer comment `vouch @your-handle`, which puts you on the list from then on.
|
||||
|
||||
Being vouched only stops your pull requests from being closed automatically. [Only work on approved issues](#only-work-on-approved-issues) still applies to every pull request you send.
|
||||
|
||||
Contributors who abuse this are denounced, and their pull requests are closed regardless of size.
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -39,6 +39,8 @@ Please open an issue or start a discussion and wait for approval before submitti
|
||||
|
||||
**If you submit an AI slop pull request (especially without following the proper procedure), you will be banned from future contributions to solidtime.**
|
||||
|
||||
To keep that manageable, pull requests from authors who are not vouched are closed automatically, unless they change 50 lines or fewer. To get vouched, open an issue or discussion first and explain how you intend to implement the change. Once we have agreed on the approach, we vouch for you. See [Vouched contributors](./CONTRIBUTING.md#vouched-contributors).
|
||||
|
||||
Please read the [CONTRIBUTING.md](./CONTRIBUTING.md) before sumbitting a Pull Request.
|
||||
|
||||
We do accept contributions in the [documentation repository](https://github.com/solidtime-io/docs) f.e. to add new self-hosting guides.
|
||||
|
||||
@@ -4,9 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Actions\Fortify;
|
||||
|
||||
use App\Enums\RegistrationMode;
|
||||
use App\Enums\Weekday;
|
||||
use App\Events\NewsletterRegistered;
|
||||
use App\Models\User;
|
||||
use App\Service\InvitationService;
|
||||
use App\Service\IpLookup\IpLookupServiceContract;
|
||||
use App\Service\TimezoneService;
|
||||
use App\Service\UserService;
|
||||
@@ -31,13 +33,14 @@ class CreateNewUser implements CreatesNewUsers
|
||||
*/
|
||||
public function create(array $input): User
|
||||
{
|
||||
if (! config('app.enable_registration')) {
|
||||
$registrationMode = RegistrationMode::fromConfig(config('app.enable_registration'));
|
||||
if ($registrationMode === RegistrationMode::Off) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => [__('Registration is disabled.')],
|
||||
]);
|
||||
}
|
||||
|
||||
Validator::make($input, [
|
||||
$validated = Validator::make($input, [
|
||||
'name' => [
|
||||
'required',
|
||||
'string',
|
||||
@@ -60,6 +63,20 @@ class CreateNewUser implements CreatesNewUsers
|
||||
],
|
||||
])->validate();
|
||||
|
||||
if ($registrationMode === RegistrationMode::InviteOnly) {
|
||||
$invitationService = app(InvitationService::class);
|
||||
$email = (string) $validated['email'];
|
||||
if (! $invitationService->hasAcceptedInvitationForEmail($email)) {
|
||||
$message = $invitationService->hasPendingInvitationForEmail($email)
|
||||
? __('Please accept the organization invitation sent to your email address before registering.')
|
||||
: __('Registration is only available to invited users.');
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => [$message],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$timezone = null;
|
||||
if (array_key_exists('timezone', $input) && is_string($input['timezone'])) {
|
||||
if (app(TimezoneService::class)->isValid($input['timezone'])) {
|
||||
|
||||
@@ -51,7 +51,8 @@ class TimeEntrySendStillRunningMailsCommand extends Command
|
||||
])
|
||||
->whereHas('user', function (Builder $query): void {
|
||||
/** @var Builder<User> $query */
|
||||
$query->where('is_placeholder', '=', false);
|
||||
$query->where('is_placeholder', '=', false)
|
||||
->where('send_time_entry_still_running_email', '=', true);
|
||||
})
|
||||
->orderBy('created_at', 'asc')
|
||||
->chunk(500, function (Collection $timeEntries) use ($dryRun, &$sentMails): void {
|
||||
|
||||
29
app/Enums/RegistrationMode.php
Normal file
29
app/Enums/RegistrationMode.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
enum RegistrationMode: string
|
||||
{
|
||||
case On = 'on';
|
||||
case InviteOnly = 'invite-only';
|
||||
case Off = 'off';
|
||||
|
||||
public static function fromConfig(mixed $value): self
|
||||
{
|
||||
if ($value === true) {
|
||||
return self::On;
|
||||
}
|
||||
|
||||
if ($value === false || $value === null) {
|
||||
return self::Off;
|
||||
}
|
||||
|
||||
return match (strtolower(trim((string) $value))) {
|
||||
'1', 'on', 'true' => self::On,
|
||||
'invite-only' => self::InviteOnly,
|
||||
default => self::Off,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ enum TimeEntryAggregationType: string
|
||||
case Billable = 'billable';
|
||||
case Description = 'description';
|
||||
case Tag = 'tag';
|
||||
case Type = 'type';
|
||||
|
||||
public static function fromInterval(TimeEntryAggregationTypeInterval $timeEntryAggregationTypeInterval): TimeEntryAggregationType
|
||||
{
|
||||
|
||||
15
app/Enums/TimeEntryType.php
Normal file
15
app/Enums/TimeEntryType.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Datomatic\LaravelEnumHelper\LaravelEnumHelper;
|
||||
|
||||
enum TimeEntryType: string
|
||||
{
|
||||
use LaravelEnumHelper;
|
||||
|
||||
case Work = 'work';
|
||||
case Break = 'break';
|
||||
}
|
||||
@@ -60,7 +60,6 @@ abstract class ApiException extends Exception
|
||||
*/
|
||||
public function report(): bool
|
||||
{
|
||||
// TODO: temporary activated
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers extends ApiException
|
||||
{
|
||||
public const string KEY = 'can_not_delete_user_who_is_owner_of_organization_with_multiple_members';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class CanNotRemoveOwnerFromOrganization extends ApiException
|
||||
{
|
||||
public const string KEY = 'can_not_remove_owner_from_organization';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class ChangingRoleOfPlaceholderIsNotAllowed extends ApiException
|
||||
{
|
||||
public const string KEY = 'changing_role_of_placeholder_is_not_allowed';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class ChangingRoleToPlaceholderIsNotAllowed extends ApiException
|
||||
{
|
||||
public const string KEY = 'changing_role_to_placeholder_is_not_allowed';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,16 @@ class EntityStillInUseApiException extends ApiException
|
||||
|
||||
public const string KEY = 'entity_still_in_use';
|
||||
|
||||
/**
|
||||
* Report the exception.
|
||||
*
|
||||
* @return bool true means the exception handler will not report it again
|
||||
*/
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the translated message for the exception.
|
||||
*/
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class FeatureIsNotAvailableInFreePlanApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'feature_is_not_available_in_free_plan';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class InactiveUserCanNotBeUsedApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'inactive_user_can_not_be_used';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class InvitationForTheEmailAlreadyExistsApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'invitation_for_the_email_already_exists';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class OnlyOwnerCanChangeOwnership extends ApiException
|
||||
{
|
||||
public const string KEY = 'only_owner_can_change_ownership';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class OnlyPlaceholdersCanBeMergedIntoAnotherMember extends ApiException
|
||||
{
|
||||
public const string KEY = 'only_placeholders_can_be_merged_into_another_member';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class OrganizationHasNoSubscriptionButMultipleMembersException extends ApiException
|
||||
{
|
||||
public const string KEY = 'organization_has_no_subscription_but_multiple_members';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class OrganizationNeedsAtLeastOneOwner extends ApiException
|
||||
{
|
||||
public const string KEY = 'organization_needs_at_least_one_owner';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class OverlappingTimeEntryApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'overlapping_time_entry';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException extends ApiException
|
||||
{
|
||||
public const string KEY = 'this_placeholder_can_not_be_invited_use_the_merge_tool_instead_api_exception';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class TimeEntryCanNotBeRestartedApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'time_entry_can_not_be_restarted';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,14 @@ namespace App\Exceptions\Api;
|
||||
class TimeEntryStillRunningApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'time_entry_still_running';
|
||||
|
||||
/**
|
||||
* Report the exception.
|
||||
*
|
||||
* @return bool true means the exception handler will not report it again
|
||||
*/
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class UserIsAlreadyMemberOfOrganizationApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'user_is_already_member_of_organization';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class UserIsAlreadyMemberOfProjectApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'user_is_already_member_of_project';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class UserNotPlaceholderApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'user_not_placeholder';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,4 +7,9 @@ namespace App\Exceptions\Api;
|
||||
class UserResendEmailVerificationNoPendingEmailApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'user_resend_email_verification_no_pending_email';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,11 @@ namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use League\OAuth2\Server\Exception\OAuthServerException;
|
||||
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
@@ -30,6 +34,33 @@ class Handler extends ExceptionHandler
|
||||
$this->reportable(function (Throwable $e): void {
|
||||
//
|
||||
});
|
||||
|
||||
$this->dontReportWhen(fn (Throwable $e): bool => $e instanceof OAuthServerException
|
||||
&& $e->getErrorType() === 'access_denied'
|
||||
&& $e->getHttpStatusCode() === 401);
|
||||
|
||||
// A request on an untrusted host (see App\Http\Middleware\TrustHosts)
|
||||
// otherwise renders as a bare "Bad request." 400. Show a message that
|
||||
// says how to fix it instead. The framework has already converted the
|
||||
// SuspiciousOperationException into a BadRequestHttpException by the time
|
||||
// renderables run, so we match that and inspect the original.
|
||||
$this->renderable(function (BadRequestHttpException $e, Request $request): ?Response {
|
||||
$previous = $e->getPrevious();
|
||||
|
||||
if (! $previous instanceof SuspiciousOperationException
|
||||
|| ! str_starts_with($previous->getMessage(), 'Untrusted Host')) {
|
||||
return null; // any other bad request keeps the default response
|
||||
}
|
||||
|
||||
$message = 'This hostname is not configured for this instance. '
|
||||
.'Set APP_URL, or add the host to TRUSTED_HOSTS.';
|
||||
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json(['message' => $message], 400);
|
||||
}
|
||||
|
||||
return response()->view('errors.untrusted-host', ['message' => $message], 400);
|
||||
});
|
||||
}
|
||||
|
||||
public function render($request, Throwable $e): Response|RedirectResponse
|
||||
|
||||
@@ -28,7 +28,9 @@ class ExportController extends Controller
|
||||
|
||||
$filepath = $exportService->export($organization);
|
||||
$downloadUrl = Storage::disk(config('filesystems.private'))
|
||||
->temporaryUrl($filepath, Carbon::now()->addMinutes(10));
|
||||
->temporaryUrl($filepath, Carbon::now()->addMinutes(10), [
|
||||
'ResponseContentDisposition' => 'attachment; filename="'.basename($filepath).'"',
|
||||
]);
|
||||
|
||||
return new JsonResponse([
|
||||
'success' => true,
|
||||
|
||||
@@ -78,6 +78,9 @@ class OrganizationController extends Controller
|
||||
if ($request->getPreventOverlappingTimeEntries() !== null) {
|
||||
$organization->prevent_overlapping_time_entries = $request->getPreventOverlappingTimeEntries();
|
||||
}
|
||||
if ($request->getBreaksEnabled() !== null) {
|
||||
$organization->breaks_enabled = $request->getBreaksEnabled();
|
||||
}
|
||||
$hasBillableRate = $request->has('billable_rate');
|
||||
if ($hasBillableRate) {
|
||||
$oldBillableRate = $organization->billable_rate;
|
||||
|
||||
@@ -57,6 +57,7 @@ class ReportController extends Controller
|
||||
$filter->addEnd($properties->end);
|
||||
$filter->addActive($properties->active);
|
||||
$filter->addBillable($properties->billable);
|
||||
$filter->addType($properties->timeEntryType);
|
||||
$filter->addMemberIdsFilter($properties->memberIds?->toArray());
|
||||
$filter->addProjectIdsFilter($properties->projectIds?->toArray());
|
||||
$filter->addTagIdsFilter($properties->tagIds?->toArray(), $properties->tagMatchType);
|
||||
|
||||
@@ -112,6 +112,7 @@ class ReportController extends Controller
|
||||
$properties->timezone = $timezone;
|
||||
$properties->roundingType = $request->getPropertyRoundingType();
|
||||
$properties->roundingMinutes = $request->getPropertyRoundingMinutes();
|
||||
$properties->timeEntryType = $request->getPropertyTimeEntryType();
|
||||
$report->properties = $properties;
|
||||
if ($isPublic) {
|
||||
$report->share_secret = $reportService->generateSecret();
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\Role;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Exceptions\Api\FeatureIsNotAvailableInFreePlanApiException;
|
||||
use App\Exceptions\Api\OverlappingTimeEntryApiException;
|
||||
use App\Exceptions\Api\PdfRendererIsNotConfiguredException;
|
||||
@@ -209,6 +210,7 @@ class TimeEntryController extends Controller
|
||||
$filter->addTaskIdsFilter($request->input('task_ids'));
|
||||
$filter->addClientIdsFilter($request->input('client_ids'));
|
||||
$filter->addBillableFilter($request->input('billable'));
|
||||
$filter->addTypeFilter($request->input('type'));
|
||||
|
||||
return $filter->get();
|
||||
}
|
||||
@@ -334,7 +336,9 @@ class TimeEntryController extends Controller
|
||||
|
||||
return response()->json([
|
||||
'download_url' => Storage::disk(config('filesystems.private'))
|
||||
->temporaryUrl($path, now()->addMinutes(5)),
|
||||
->temporaryUrl($path, now()->addMinutes(5), [
|
||||
'ResponseContentDisposition' => 'attachment; filename="'.$filename.'"',
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -533,7 +537,7 @@ class TimeEntryController extends Controller
|
||||
->putFileAs($folderPath, new File($tempFolder->path($filenameTemp)), $filename);
|
||||
} else {
|
||||
Excel::store(
|
||||
new TimeEntriesReportExport($aggregatedData, $format, $currency, $group, $subGroup, $showBillableRate),
|
||||
new TimeEntriesReportExport($aggregatedData, $format, $currency, $group, $subGroup, $showBillableRate, $localizationService),
|
||||
$path,
|
||||
config('filesystems.private'),
|
||||
$format->getExportPackageType(),
|
||||
@@ -545,7 +549,9 @@ class TimeEntryController extends Controller
|
||||
|
||||
return response()->json([
|
||||
'download_url' => Storage::disk(config('filesystems.private'))
|
||||
->temporaryUrl($path, now()->addMinutes(5)),
|
||||
->temporaryUrl($path, now()->addMinutes(5), [
|
||||
'ResponseContentDisposition' => 'attachment; filename="'.$filename.'"',
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -568,6 +574,7 @@ class TimeEntryController extends Controller
|
||||
$filter->addTaskIdsFilter($request->input('task_ids'));
|
||||
$filter->addClientIdsFilter($request->input('client_ids'));
|
||||
$filter->addBillableFilter($request->input('billable'));
|
||||
$filter->addTypeFilter($request->input('type'));
|
||||
|
||||
return $filter->get();
|
||||
}
|
||||
@@ -759,6 +766,19 @@ class TimeEntryController extends Controller
|
||||
continue;
|
||||
|
||||
}
|
||||
// Changing time entries to Break entries is only allowed when breaks are enabled in the org settings
|
||||
$resultingType = isset($changes['type']) ? TimeEntryType::from($changes['type']) : $timeEntry->type;
|
||||
if ($resultingType === TimeEntryType::Break && $timeEntry->type !== TimeEntryType::Break && ! $organization->breaks_enabled) {
|
||||
$error->push($id);
|
||||
|
||||
continue;
|
||||
}
|
||||
// Break entries can not be billable, have tags or belong to a project/task (see TimeEntry::booted)
|
||||
if ($resultingType === TimeEntryType::Break && ($project !== null || $task !== null || $request->boolean('changes.billable') || count($changes['tags'] ?? []) > 0)) {
|
||||
$error->push($id);
|
||||
|
||||
continue;
|
||||
}
|
||||
$oldProject = $timeEntry->project;
|
||||
$oldTask = $timeEntry->task;
|
||||
|
||||
|
||||
@@ -124,6 +124,10 @@ class UserController extends Controller
|
||||
$user->week_start = $request->getWeekStart();
|
||||
}
|
||||
|
||||
if ($request->getSendTimeEntryStillRunningEmail() !== null) {
|
||||
$user->send_time_entry_still_running_email = $request->getSendTimeEntryStillRunningEmail();
|
||||
}
|
||||
|
||||
$user->save();
|
||||
|
||||
if ($emailToVerify !== null) {
|
||||
|
||||
@@ -36,6 +36,7 @@ class OrganizationInvitationController extends Controller
|
||||
}
|
||||
|
||||
return redirect(route('register'))
|
||||
->with('registration_email', $email)
|
||||
->with('bannerText', __('Please create an account to finish joining the :organization organization.', [
|
||||
'organization' => $organization->name,
|
||||
]))
|
||||
|
||||
@@ -15,6 +15,7 @@ use App\Http\Middleware\PreventRequestsDuringMaintenance;
|
||||
use App\Http\Middleware\RedirectIfAuthenticated;
|
||||
use App\Http\Middleware\ShareInertiaData;
|
||||
use App\Http\Middleware\TrimStrings;
|
||||
use App\Http\Middleware\TrustHosts;
|
||||
use App\Http\Middleware\TrustProxies;
|
||||
use App\Http\Middleware\ValidateSignature;
|
||||
use App\Http\Middleware\VerifyCsrfToken;
|
||||
@@ -47,6 +48,7 @@ class Kernel extends HttpKernel
|
||||
*/
|
||||
protected $middleware = [
|
||||
ForceHttps::class,
|
||||
TrustHosts::class,
|
||||
TrustProxies::class,
|
||||
HandleCors::class,
|
||||
PreventRequestsDuringMaintenance::class,
|
||||
|
||||
56
app/Http/Middleware/TrustHosts.php
Normal file
56
app/Http/Middleware/TrustHosts.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustHosts as BaseTrustHosts;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
/**
|
||||
* Rejects requests whose Host is not trusted, preventing Host-header poisoning of
|
||||
* generated URLs (password reset, SSO callback, invitations). Trusted = the
|
||||
* APP_URL host and its subdomains, plus TRUSTED_HOSTS (for multi-host access such
|
||||
* as a Tailscale name). Health-check endpoints are exempt (probed by IP).
|
||||
*/
|
||||
class TrustHosts extends BaseTrustHosts
|
||||
{
|
||||
/**
|
||||
* @return array<int, string|null>
|
||||
*/
|
||||
public function hosts(): array
|
||||
{
|
||||
/** @var array<int, string> $configured */
|
||||
$configured = config('app.trusted_hosts', []);
|
||||
|
||||
$extra = array_map(function (string $host): string {
|
||||
$host = trim($host);
|
||||
|
||||
// "*.example.com" matches any subdomain, not the apex.
|
||||
if (str_starts_with($host, '*.')) {
|
||||
return '^.+\.'.preg_quote(substr($host, 2), '#').'$';
|
||||
}
|
||||
|
||||
return '^'.preg_quote($host, '#').'$';
|
||||
}, $configured);
|
||||
|
||||
return array_merge([$this->allSubdomainsOfApplicationUrl()], $extra);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Closure(Request): Response $next
|
||||
*/
|
||||
public function handle(Request $request, $next)
|
||||
{
|
||||
// Exempt health checks (probed by IP). Also reset the trusted hosts,
|
||||
// since Octane leaks the static state across requests.
|
||||
if ($request->is('health-check/*')) {
|
||||
Request::setTrustedHosts([]);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
return parent::handle($request, $next);
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,9 @@ class OrganizationUpdateRequest extends BaseFormRequest
|
||||
'prevent_overlapping_time_entries' => [
|
||||
'boolean',
|
||||
],
|
||||
'breaks_enabled' => [
|
||||
'boolean',
|
||||
],
|
||||
'number_format' => [
|
||||
Rule::enum(NumberFormat::class),
|
||||
],
|
||||
@@ -125,4 +128,9 @@ class OrganizationUpdateRequest extends BaseFormRequest
|
||||
{
|
||||
return $this->has('prevent_overlapping_time_entries') ? $this->boolean('prevent_overlapping_time_entries') : null;
|
||||
}
|
||||
|
||||
public function getBreaksEnabled(): ?bool
|
||||
{
|
||||
return $this->has('breaks_enabled') ? $this->boolean('breaks_enabled') : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Organization;
|
||||
@@ -177,6 +178,12 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
'numeric',
|
||||
'integer',
|
||||
],
|
||||
// Filter by time entry type
|
||||
'properties.time_entry_type' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::enum(TimeEntryType::class),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -240,6 +247,15 @@ class ReportStoreRequest extends BaseFormRequest
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getPropertyTimeEntryType(): ?TimeEntryType
|
||||
{
|
||||
if (! $this->has('properties.time_entry_type') || $this->input('properties.time_entry_type') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return TimeEntryType::from($this->input('properties.time_entry_type'));
|
||||
}
|
||||
|
||||
public function getPropertyGroup(): TimeEntryAggregationType
|
||||
{
|
||||
return TimeEntryAggregationType::from($this->input('properties.group'));
|
||||
|
||||
@@ -9,6 +9,7 @@ use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
@@ -183,6 +184,11 @@ class TimeEntryAggregateExportRequest extends BaseFormRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Filter by time entry type
|
||||
'type' => [
|
||||
'string',
|
||||
Rule::enum(TimeEntryType::class),
|
||||
],
|
||||
'fill_gaps_in_time_groups' => [
|
||||
'string',
|
||||
'in:true,false',
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace App\Http\Requests\V1\TimeEntry;
|
||||
use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
@@ -169,6 +170,11 @@ class TimeEntryAggregateRequest extends BaseFormRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Filter by time entry type
|
||||
'type' => [
|
||||
'string',
|
||||
Rule::enum(TimeEntryType::class),
|
||||
],
|
||||
'fill_gaps_in_time_groups' => [
|
||||
'string',
|
||||
'in:true,false',
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace App\Http\Requests\V1\TimeEntry;
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
@@ -155,6 +156,11 @@ class TimeEntryIndexExportRequest extends TimeEntryIndexRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Filter by time entry type
|
||||
'type' => [
|
||||
'string',
|
||||
Rule::enum(TimeEntryType::class),
|
||||
],
|
||||
// Limit the number of returned time entries (default: 150)
|
||||
'limit' => [
|
||||
'integer',
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Http\Requests\V1\TimeEntry;
|
||||
|
||||
use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Client;
|
||||
use App\Models\Member;
|
||||
@@ -148,6 +149,11 @@ class TimeEntryIndexRequest extends BaseFormRequest
|
||||
'string',
|
||||
'in:true,false',
|
||||
],
|
||||
// Filter by time entry type
|
||||
'type' => [
|
||||
'string',
|
||||
Rule::enum(TimeEntryType::class),
|
||||
],
|
||||
// Limit the number of returned time entries (default: 150)
|
||||
'limit' => [
|
||||
'integer',
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\TimeEntry;
|
||||
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
@@ -14,6 +15,7 @@ use App\Service\PermissionStore;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
@@ -24,7 +26,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule>>
|
||||
* @return array<string, array<string|\Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -42,6 +44,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
||||
'nullable',
|
||||
'string',
|
||||
'required_with:task_id',
|
||||
'prohibited_if:type,break',
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||
@@ -60,6 +63,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
||||
'task_id' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'prohibited_if:type,break',
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Task> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
@@ -85,6 +89,16 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
||||
'billable' => [
|
||||
'required',
|
||||
'boolean',
|
||||
'declined_if:type,break',
|
||||
],
|
||||
// Type of the time entry (work time or a break)
|
||||
'type' => [
|
||||
Rule::enum(TimeEntryType::class),
|
||||
function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if ($value === TimeEntryType::Break->value && ! $this->organization->breaks_enabled) {
|
||||
$fail('Breaks are disabled for this organization.');
|
||||
}
|
||||
},
|
||||
],
|
||||
// Description of time entry
|
||||
'description' => [
|
||||
@@ -96,6 +110,7 @@ class TimeEntryStoreRequest extends BaseFormRequest
|
||||
'tags' => [
|
||||
'nullable',
|
||||
'array',
|
||||
'prohibited_if:type,break',
|
||||
],
|
||||
'tags.*' => [
|
||||
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\TimeEntry;
|
||||
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
@@ -14,6 +15,7 @@ use App\Service\PermissionStore;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
@@ -24,7 +26,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule>>
|
||||
* @return array<string, array<string|ValidationRule|\Illuminate\Contracts\Validation\Rule>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -54,6 +56,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
||||
'nullable',
|
||||
'string',
|
||||
'required_with:task_id',
|
||||
'prohibited_if:changes.type,break',
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||
@@ -72,6 +75,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
||||
'changes.task_id' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'prohibited_if:changes.type,break',
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Task> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
@@ -84,7 +88,13 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
||||
],
|
||||
// Whether time entry is billable
|
||||
'changes.billable' => [
|
||||
'sometimes',
|
||||
'boolean',
|
||||
'declined_if:changes.type,break',
|
||||
],
|
||||
// Type of the time entry (work time or a break)
|
||||
'changes.type' => [
|
||||
Rule::enum(TimeEntryType::class),
|
||||
],
|
||||
// Description of time entry
|
||||
'changes.description' => [
|
||||
@@ -96,6 +106,7 @@ class TimeEntryUpdateMultipleRequest extends BaseFormRequest
|
||||
'changes.tags' => [
|
||||
'nullable',
|
||||
'array',
|
||||
'prohibited_if:changes.type,break',
|
||||
],
|
||||
'changes.tags.*' => [
|
||||
'string',
|
||||
|
||||
@@ -4,16 +4,21 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests\V1\TimeEntry;
|
||||
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Http\Requests\V1\BaseFormRequest;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tag;
|
||||
use App\Models\Task;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\PermissionStore;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ConditionalRules;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\ProhibitedIf;
|
||||
use Korridor\LaravelModelValidationRules\Rules\ExistsEloquent;
|
||||
|
||||
/**
|
||||
@@ -24,10 +29,19 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, array<string|ValidationRule>>
|
||||
* @return array<string, array<string|\Closure|ValidationRule|\Illuminate\Contracts\Validation\Rule|ProhibitedIf|ConditionalRules>>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// Break restrictions need to apply based on the type the entry will have after the
|
||||
// update, not only when the payload itself contains type=break.
|
||||
$timeEntry = $this->route('timeEntry');
|
||||
$timeEntry = $timeEntry instanceof TimeEntry ? $timeEntry : null;
|
||||
$resultingType = $this->has('type')
|
||||
? TimeEntryType::tryFrom((string) $this->input('type'))
|
||||
: $timeEntry?->type;
|
||||
$isBreak = $resultingType === TimeEntryType::Break;
|
||||
|
||||
return [
|
||||
// ID of the organization member that the time entry should belong to
|
||||
'member_id' => [
|
||||
@@ -42,6 +56,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
'nullable',
|
||||
'string',
|
||||
'required_with:task_id',
|
||||
Rule::prohibitedIf($isBreak),
|
||||
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Project> $builder */
|
||||
$builder = $builder->whereBelongsTo($this->organization, 'organization');
|
||||
@@ -60,6 +75,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
'task_id' => [
|
||||
'nullable',
|
||||
'string',
|
||||
Rule::prohibitedIf($isBreak),
|
||||
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
|
||||
/** @var Builder<Task> $builder */
|
||||
return $builder->whereBelongsTo($this->organization, 'organization');
|
||||
@@ -82,7 +98,22 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
],
|
||||
// Whether time entry is billable
|
||||
'billable' => [
|
||||
'sometimes',
|
||||
'boolean',
|
||||
Rule::when($isBreak, ['declined']),
|
||||
],
|
||||
// Type of the time entry (work time or a break)
|
||||
'type' => [
|
||||
Rule::enum(TimeEntryType::class),
|
||||
function (string $attribute, mixed $value, \Closure $fail) use ($timeEntry): void {
|
||||
// While breaks are disabled, entries that already are breaks may stay
|
||||
// breaks, but converting a work entry to a break is not allowed.
|
||||
if ($value === TimeEntryType::Break->value
|
||||
&& ! $this->organization->breaks_enabled
|
||||
&& $timeEntry?->type !== TimeEntryType::Break) {
|
||||
$fail('Breaks are disabled for this organization.');
|
||||
}
|
||||
},
|
||||
],
|
||||
// Description of time entry
|
||||
'description' => [
|
||||
@@ -94,6 +125,7 @@ class TimeEntryUpdateRequest extends BaseFormRequest
|
||||
'tags' => [
|
||||
'nullable',
|
||||
'array',
|
||||
Rule::prohibitedIf($isBreak),
|
||||
],
|
||||
'tags.*' => [
|
||||
'string',
|
||||
|
||||
@@ -58,6 +58,9 @@ class UserUpdateRequest extends BaseFormRequest
|
||||
'week_start' => [
|
||||
Rule::enum(Weekday::class),
|
||||
],
|
||||
'send_time_entry_still_running_email' => [
|
||||
'boolean',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -81,6 +84,13 @@ class UserUpdateRequest extends BaseFormRequest
|
||||
return $this->has('week_start') ? Weekday::from($this->input('week_start')) : null;
|
||||
}
|
||||
|
||||
public function getSendTimeEntryStillRunningEmail(): ?bool
|
||||
{
|
||||
return $this->has('send_time_entry_still_running_email')
|
||||
? $this->boolean('send_time_entry_still_running_email')
|
||||
: null;
|
||||
}
|
||||
|
||||
public function hasPhotoKey(): bool
|
||||
{
|
||||
return $this->has('photo');
|
||||
|
||||
@@ -57,6 +57,8 @@ class OrganizationResource extends BaseResource
|
||||
'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 bool $breaks_enabled Whether members of the organization can track breaks */
|
||||
'breaks_enabled' => $this->resource->breaks_enabled,
|
||||
/** @var string $currency Currency code (ISO 4217) */
|
||||
'currency' => $this->resource->currency,
|
||||
/** @var string $currency_symbol Currency symbol */
|
||||
|
||||
@@ -50,6 +50,8 @@ class DetailedReportResource extends BaseResource
|
||||
'member_ids' => $this->resource->properties->memberIds?->toArray(),
|
||||
/** @var bool|null $billable Filter by billable status */
|
||||
'billable' => $this->resource->properties->billable,
|
||||
/** @var string|null $time_entry_type Filter by time entry type */
|
||||
'time_entry_type' => $this->resource->properties->timeEntryType?->value,
|
||||
/** @var array<string>|null $client_ids Filter by client IDs, client IDs are OR combined */
|
||||
'client_ids' => $this->resource->properties->clientIds?->toArray(),
|
||||
/** @var array<string>|null $project_ids Filter by project IDs, project IDs are OR combined */
|
||||
|
||||
@@ -47,6 +47,8 @@ class TimeEntryResource extends BaseResource
|
||||
'tags' => $this->resource->tags ?? [],
|
||||
/** @var bool $billable Whether time entry is billable */
|
||||
'billable' => $this->resource->billable,
|
||||
/** @var string $type Type of the time entry (`work` time or a `break`) */
|
||||
'type' => $this->resource->type->value,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ class UserResource extends BaseResource
|
||||
'timezone' => $this->resource->timezone,
|
||||
/** @var Weekday $week_start Starting day of the week */
|
||||
'week_start' => $this->resource->week_start->value,
|
||||
/** @var bool $send_time_entry_still_running_email Whether to email the user when a time entry has been running for more than 8 hours */
|
||||
'send_time_entry_still_running_email' => $this->resource->send_time_entry_still_running_email,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
* @property bool $employees_can_see_billable_rates
|
||||
* @property bool $employees_can_manage_tasks
|
||||
* @property bool $prevent_overlapping_time_entries
|
||||
* @property bool $breaks_enabled
|
||||
* @property User $owner
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $updated_at
|
||||
@@ -70,6 +71,7 @@ class Organization extends Model implements AuditableContract
|
||||
'employees_can_see_billable_rates' => 'boolean',
|
||||
'employees_can_manage_tasks' => 'boolean',
|
||||
'prevent_overlapping_time_entries' => 'boolean',
|
||||
'breaks_enabled' => 'boolean',
|
||||
'number_format' => NumberFormat::class,
|
||||
'currency_format' => CurrencyFormat::class,
|
||||
'date_format' => DateFormat::class,
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Models\Concerns\CustomAuditable;
|
||||
use App\Models\Concerns\HasUuids;
|
||||
use App\Service\BillableRateService;
|
||||
@@ -28,6 +29,7 @@ use Staudenmeir\EloquentJsonRelations\Relations\BelongsToJson;
|
||||
* @property Carbon|null $end
|
||||
* @property int|null $billable_rate Billable rate per hour in cents
|
||||
* @property bool $billable
|
||||
* @property TimeEntryType $type
|
||||
* @property array<string> $tags
|
||||
* @property string $user_id
|
||||
* @property string $member_id
|
||||
@@ -71,12 +73,20 @@ class TimeEntry extends Model implements AuditableContract
|
||||
'start' => 'datetime',
|
||||
'end' => 'datetime',
|
||||
'billable' => 'bool',
|
||||
'type' => TimeEntryType::class,
|
||||
'tags' => 'array',
|
||||
'billable_rate' => 'int',
|
||||
'is_imported' => 'bool',
|
||||
'still_active_email_sent_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected $attributes = [
|
||||
'type' => 'work',
|
||||
];
|
||||
|
||||
public const array SELECT_COLUMNS = [
|
||||
'id',
|
||||
'description',
|
||||
@@ -84,6 +94,7 @@ class TimeEntry extends Model implements AuditableContract
|
||||
'end',
|
||||
'billable_rate',
|
||||
'billable',
|
||||
'type',
|
||||
'user_id',
|
||||
'organization_id',
|
||||
'project_id',
|
||||
@@ -117,6 +128,21 @@ class TimeEntry extends Model implements AuditableContract
|
||||
'billable_rate',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
// Break entries can never be billable, have tags or belong to a project/task.
|
||||
static::saving(function (TimeEntry $timeEntry): void {
|
||||
if ($timeEntry->type === TimeEntryType::Break) {
|
||||
$timeEntry->billable = false;
|
||||
$timeEntry->billable_rate = null;
|
||||
$timeEntry->project_id = null;
|
||||
$timeEntry->task_id = null;
|
||||
$timeEntry->client_id = null;
|
||||
$timeEntry->tags = [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function getBillableRateComputed(): ?int
|
||||
{
|
||||
return app(BillableRateService::class)->getBillableRateForTimeEntry($this);
|
||||
@@ -173,6 +199,16 @@ class TimeEntry extends Model implements AuditableContract
|
||||
$builder->whereJsonContains('tags', $tag->getKey());
|
||||
}
|
||||
|
||||
/**
|
||||
* Only work entries — breaks do not count toward tracked/billable time.
|
||||
*
|
||||
* @param Builder<TimeEntry> $builder
|
||||
*/
|
||||
public function scopeWorkTime(Builder $builder): void
|
||||
{
|
||||
$builder->where('type', '=', TimeEntryType::Work);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
|
||||
@@ -42,6 +42,7 @@ use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
|
||||
* @property string $timezone
|
||||
* @property bool $is_placeholder
|
||||
* @property Weekday $week_start
|
||||
* @property bool $send_time_entry_still_running_email
|
||||
* @property string|null $profile_photo_path
|
||||
* @property-read Organization|null $currentOrganization
|
||||
* @property-read string $profile_photo_url
|
||||
@@ -108,6 +109,7 @@ class User extends Authenticatable implements AuditableContract, FilamentUser, M
|
||||
'is_admin' => 'boolean',
|
||||
'is_placeholder' => 'boolean',
|
||||
'week_start' => Weekday::class,
|
||||
'send_time_entry_still_running_email' => 'boolean',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -117,6 +119,7 @@ class User extends Authenticatable implements AuditableContract, FilamentUser, M
|
||||
*/
|
||||
protected $attributes = [
|
||||
'week_start' => Weekday::Monday,
|
||||
'send_time_entry_still_running_email' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -20,6 +20,7 @@ use App\Service\BillingContract;
|
||||
use App\Service\IpLookup\IpLookupServiceContract;
|
||||
use App\Service\IpLookup\NoIpLookupService;
|
||||
use App\Service\PermissionStore;
|
||||
use DateTimeInterface;
|
||||
use Dedoc\Scramble\Scramble;
|
||||
use Dedoc\Scramble\Support\Generator\OpenApi;
|
||||
use Dedoc\Scramble\Support\Generator\SecurityScheme;
|
||||
@@ -29,8 +30,13 @@ use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
@@ -98,6 +104,27 @@ class AppServiceProvider extends ServiceProvider
|
||||
$this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class);
|
||||
$this->app->bind(BillingContract::class);
|
||||
|
||||
// Storage
|
||||
// The local driver ignores the ResponseContentDisposition option of temporaryUrl,
|
||||
// so mirror it through the signed query parameters of the storage route.
|
||||
$privateDisk = config('filesystems.private');
|
||||
if (config('filesystems.disks.'.$privateDisk.'.driver') === 'local') {
|
||||
$disk = Storage::disk($privateDisk);
|
||||
$disk->serveUsing(function (Request $request, string $path, array $headers) use ($disk): StreamedResponse {
|
||||
return $disk->response($path, null, $headers, $request->query('disposition', 'inline'));
|
||||
});
|
||||
$disk->buildTemporaryUrlsUsing(function (string $path, DateTimeInterface $expiration, array $options) use ($privateDisk): string {
|
||||
$parameters = array_filter([
|
||||
'path' => $path,
|
||||
'disposition' => isset($options['ResponseContentDisposition'])
|
||||
? Str::before($options['ResponseContentDisposition'], ';')
|
||||
: null,
|
||||
]);
|
||||
|
||||
return url(URL::temporarySignedRoute('storage.'.$privateDisk, $expiration, $parameters, absolute: false));
|
||||
});
|
||||
}
|
||||
|
||||
// Routing
|
||||
Route::model('member', Member::class);
|
||||
Route::model('invitation', OrganizationInvitation::class);
|
||||
|
||||
@@ -45,6 +45,7 @@ class FortifyServiceProvider extends ServiceProvider
|
||||
|
||||
Fortify::registerView(function () {
|
||||
return Inertia::render('Auth/Register', [
|
||||
'email' => session('registration_email', ''),
|
||||
'terms_url' => config('auth.terms_url'),
|
||||
'privacy_policy_url' => config('auth.privacy_policy_url'),
|
||||
'newsletter_consent' => config('auth.newsletter_consent'),
|
||||
|
||||
@@ -33,8 +33,8 @@ class RouteServiceProvider extends ServiceProvider
|
||||
}
|
||||
|
||||
return $request->user()
|
||||
? Limit::perMinute(200)->by($request->user()->id)
|
||||
: Limit::perMinute(60)->by($request->ip());
|
||||
? Limit::perMinute(config('app.api_rate_limit_authenticated_per_minute'))->by($request->user()->id)
|
||||
: Limit::perMinute(config('app.api_rate_limit_guest_per_minute'))->by($request->ip());
|
||||
});
|
||||
|
||||
$this->routes(function (): void {
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
@@ -154,6 +155,7 @@ class DashboardService
|
||||
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||
->where('user_id', '=', $user->getKey())
|
||||
->where('organization_id', '=', $organization->getKey())
|
||||
->workTime()
|
||||
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')'))
|
||||
->orderBy('date');
|
||||
|
||||
@@ -195,6 +197,7 @@ class DashboardService
|
||||
->select(DB::raw('DATE('.$dateWithTimeZone.') as date, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||
->where('user_id', '=', $user->getKey())
|
||||
->where('organization_id', '=', $organization->getKey())
|
||||
->workTime()
|
||||
->groupBy(DB::raw('DATE('.$dateWithTimeZone.')'))
|
||||
->orderBy('date');
|
||||
|
||||
@@ -222,7 +225,8 @@ class DashboardService
|
||||
$query = TimeEntry::query()
|
||||
->select(DB::raw('round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||
->where('user_id', '=', $user->getKey())
|
||||
->where('organization_id', '=', $organization->getKey());
|
||||
->where('organization_id', '=', $organization->getKey())
|
||||
->workTime();
|
||||
|
||||
$query = $this->constrainDateByPossibleDates($query, $possibleDays, $timezone);
|
||||
/** @var Collection<int, object{aggregate: int}> $resultDb */
|
||||
@@ -290,6 +294,7 @@ class DashboardService
|
||||
->select(DB::raw('project_id, round(sum(extract(epoch from (coalesce("end", now()) - start)))) as aggregate'))
|
||||
->where('user_id', '=', $user->getKey())
|
||||
->where('organization_id', '=', $organization->getKey())
|
||||
->workTime()
|
||||
->groupBy('project_id');
|
||||
|
||||
$query = $this->constrainDateByCurrentWeek($query, $timezone, $user->week_start);
|
||||
@@ -433,7 +438,8 @@ class DashboardService
|
||||
JOIN time_entries ON time_entries.start < time_ranges."end"
|
||||
AND coalesce(time_entries."end", :now::timestamp) > time_ranges.start
|
||||
WHERE time_entries.user_id = :user_id and
|
||||
time_entries.organization_id = :organization_id
|
||||
time_entries.organization_id = :organization_id and
|
||||
time_entries.type = :work_type
|
||||
GROUP BY time_ranges.start
|
||||
ORDER BY time_ranges.start
|
||||
', [
|
||||
@@ -442,6 +448,7 @@ class DashboardService
|
||||
'user_id' => $user->getKey(),
|
||||
'organization_id' => $organization->getKey(),
|
||||
'now' => Carbon::now()->toDateTimeString(),
|
||||
'work_type' => TimeEntryType::Work->value,
|
||||
]))->pluck('aggregate', 'start');
|
||||
|
||||
$response = [];
|
||||
|
||||
@@ -8,6 +8,7 @@ use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeEntryAggregationTypeInterval;
|
||||
use App\Enums\TimeEntryRoundingType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Enums\Weekday;
|
||||
use App\Service\TimeEntryFilter;
|
||||
use Illuminate\Contracts\Database\Eloquent\Castable;
|
||||
@@ -68,6 +69,8 @@ class ReportPropertiesDto implements Castable
|
||||
|
||||
public ?int $roundingMinutes = null;
|
||||
|
||||
public ?TimeEntryType $timeEntryType = null;
|
||||
|
||||
/**
|
||||
* Get the caster class to use when casting from / to this cast target.
|
||||
*
|
||||
@@ -129,6 +132,12 @@ class ReportPropertiesDto implements Castable
|
||||
$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;
|
||||
// Note: timeEntryType was added later, reports persisted before that are missing the value and default to "work"
|
||||
if (property_exists($data, 'timeEntryType')) {
|
||||
$dto->timeEntryType = $data->timeEntryType !== null ? TimeEntryType::from($data->timeEntryType) : null;
|
||||
} else {
|
||||
$dto->timeEntryType = TimeEntryType::Work;
|
||||
}
|
||||
|
||||
return $dto;
|
||||
}
|
||||
@@ -157,6 +166,7 @@ class ReportPropertiesDto implements Castable
|
||||
'timezone' => $value->timezone,
|
||||
'roundingType' => $value->roundingType?->value,
|
||||
'roundingMinutes' => $value->roundingMinutes,
|
||||
'timeEntryType' => $value->timeEntryType?->value,
|
||||
];
|
||||
|
||||
$jsonString = json_encode($data);
|
||||
|
||||
@@ -107,6 +107,7 @@ class ExportService
|
||||
'end',
|
||||
'billable_rate',
|
||||
'billable',
|
||||
'type',
|
||||
'member_id',
|
||||
'user_id',
|
||||
'organization_id',
|
||||
@@ -131,6 +132,7 @@ class ExportService
|
||||
$timeEntry->end?->toIso8601ZuluString() ?? '',
|
||||
$timeEntry->billable_rate ?? '',
|
||||
$timeEntry->billable ? 'true' : 'false',
|
||||
$timeEntry->type->value,
|
||||
$timeEntry->member_id,
|
||||
$timeEntry->user_id,
|
||||
$timeEntry->organization_id,
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Service\Import\Importers;
|
||||
|
||||
use App\Enums\Role;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Jobs\RecalculateSpentTimeForProject;
|
||||
use App\Jobs\RecalculateSpentTimeForTask;
|
||||
use App\Models\TimeEntry;
|
||||
@@ -71,8 +72,12 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
'role' => Role::Placeholder->value,
|
||||
]);
|
||||
$member = $this->memberImportHelper->getModelById($memberId);
|
||||
// Clockify allows a project/task/client/tags/billable on breaks, but those are
|
||||
// meaningless for non-work time. Detect breaks up front and skip creating any of
|
||||
// that so a break can't spawn an orphan project/tag or inflate the import counts.
|
||||
$isBreak = isset($record['Type']) && strtolower($record['Type']) === 'break';
|
||||
$clientId = null;
|
||||
if (($record['Client'] ?? '') !== '') {
|
||||
if (! $isBreak && ($record['Client'] ?? '') !== '') {
|
||||
$clientId = $this->clientImportHelper->getKey([
|
||||
'name' => $record['Client'],
|
||||
'organization_id' => $this->organization->id,
|
||||
@@ -81,7 +86,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
$projectId = null;
|
||||
$project = null;
|
||||
$projectMember = null;
|
||||
if ($record['Project'] !== '') {
|
||||
if (! $isBreak && $record['Project'] !== '') {
|
||||
$projectId = $this->projectImportHelper->getKey([
|
||||
'name' => $record['Project'],
|
||||
'client_id' => $clientId,
|
||||
@@ -97,7 +102,7 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
]);
|
||||
}
|
||||
$taskId = null;
|
||||
if ($taskKey !== null && $record[$taskKey] !== '') {
|
||||
if (! $isBreak && $taskKey !== null && $record[$taskKey] !== '') {
|
||||
$taskId = $this->taskImportHelper->getKey([
|
||||
'name' => $record[$taskKey],
|
||||
'project_id' => $projectId,
|
||||
@@ -123,7 +128,12 @@ class ClockifyTimeEntriesImporter extends DefaultImporter
|
||||
}
|
||||
$timeEntry->billable = $record['Billable'] === 'Yes';
|
||||
}
|
||||
$timeEntry->tags = $this->getTags($record['Tags']);
|
||||
if ($isBreak) {
|
||||
// Breaks can not be billable or belong to a project/task (already skipped above)
|
||||
$timeEntry->type = TimeEntryType::Break;
|
||||
$timeEntry->billable = false;
|
||||
}
|
||||
$timeEntry->tags = $isBreak ? [] : $this->getTags($record['Tags']);
|
||||
$timeEntry->is_imported = true;
|
||||
|
||||
// Start
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Service\Import\Importers;
|
||||
|
||||
use App\Enums\Role;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Jobs\RecalculateSpentTimeForProject;
|
||||
use App\Jobs\RecalculateSpentTimeForTask;
|
||||
use App\Models\TimeEntry;
|
||||
@@ -255,6 +256,14 @@ class SolidtimeImporter extends DefaultImporter
|
||||
throw new ImportException('Invalid billable value');
|
||||
}
|
||||
$timeEntry->billable = $timeEntryRow['billable'] === 'true';
|
||||
// The type column does not exist in old exports
|
||||
if (($timeEntryRow['type'] ?? '') !== '') {
|
||||
$type = TimeEntryType::tryFrom($timeEntryRow['type']);
|
||||
if ($type === null) {
|
||||
throw new ImportException('Invalid type value');
|
||||
}
|
||||
$timeEntry->type = $type;
|
||||
}
|
||||
$timeEntry->tags = $this->getTags($timeEntryRow['tags']);
|
||||
$timeEntry->is_imported = true;
|
||||
|
||||
|
||||
@@ -18,11 +18,31 @@ use Illuminate\Support\Facades\Mail;
|
||||
|
||||
class InvitationService
|
||||
{
|
||||
public function hasAcceptedInvitationForEmail(string $email): bool
|
||||
{
|
||||
return OrganizationInvitation::query()
|
||||
->whereRaw('lower(email) = ?', [strtolower($email)])
|
||||
->whereNotNull('accepted_at')
|
||||
->exists();
|
||||
}
|
||||
|
||||
public function hasPendingInvitationForEmail(string $email): bool
|
||||
{
|
||||
return OrganizationInvitation::query()
|
||||
->whereRaw('lower(email) = ?', [strtolower($email)])
|
||||
->whereNull('accepted_at')
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws UserIsAlreadyMemberOfOrganizationApiException|InvitationForTheEmailAlreadyExistsApiException
|
||||
*/
|
||||
public function inviteUser(Organization $organization, string $email, Role $role, User $inviter): OrganizationInvitation
|
||||
{
|
||||
// Normalize the email so it matches how user emails are stored (see UserService::createUser),
|
||||
// otherwise a mixed-case invite silently fails to link on registration.
|
||||
$email = strtolower($email);
|
||||
|
||||
if (app(MemberService::class)->isEmailAlreadyMember($organization, $email)) {
|
||||
throw new UserIsAlreadyMemberOfOrganizationApiException;
|
||||
}
|
||||
@@ -55,7 +75,7 @@ class InvitationService
|
||||
$organizations = new Collection;
|
||||
|
||||
$invitations = OrganizationInvitation::query()
|
||||
->where('email', $user->email)
|
||||
->whereRaw('lower(email) = ?', [strtolower($user->email)])
|
||||
->whereNotNull('accepted_at')
|
||||
->get();
|
||||
|
||||
|
||||
@@ -8,12 +8,14 @@ use App\Enums\CurrencyFormat;
|
||||
use App\Enums\DateFormat;
|
||||
use App\Enums\IntervalFormat;
|
||||
use App\Enums\NumberFormat;
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Enums\TimeFormat;
|
||||
use App\Models\Organization;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Money\Money;
|
||||
use Carbon\CarbonInterface;
|
||||
use Carbon\CarbonInterval;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class LocalizationService
|
||||
{
|
||||
@@ -152,6 +154,38 @@ class LocalizationService
|
||||
return $date->format($this->dateFormat->toCarbonFormat());
|
||||
}
|
||||
|
||||
/**
|
||||
* Time group types have no server-side descriptor; their keys are ISO dates and are
|
||||
* formatted here instead. A Week key is the first day of that week, so it renders as the
|
||||
* range it covers. A Year key is already a bare year, so it is returned unchanged - it must
|
||||
* not be parsed, Carbon reads a four digit string as a time of day.
|
||||
*/
|
||||
public function formatTimeGroupKey(?string $key, TimeEntryAggregationType $groupType): ?string
|
||||
{
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($groupType === TimeEntryAggregationType::Day) {
|
||||
return $this->formatDate(Carbon::parse($key));
|
||||
}
|
||||
|
||||
if ($groupType === TimeEntryAggregationType::Week) {
|
||||
$weekStart = Carbon::parse($key);
|
||||
|
||||
return $this->formatDate($weekStart).' - '.$this->formatDate($weekStart->copy()->addDays(6));
|
||||
}
|
||||
|
||||
if ($groupType === TimeEntryAggregationType::Month) {
|
||||
// Note: the leading "!" resets all fields the format does not name. Without it the
|
||||
// day of the month is taken from today, and a day that the parsed month does not
|
||||
// have overflows the date into the next month.
|
||||
return Carbon::createFromFormat('!Y-m', $key)->format('F Y');
|
||||
}
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
public function setDateFormat(DateFormat $dateFormat): void
|
||||
{
|
||||
$this->dateFormat = $dateFormat;
|
||||
|
||||
@@ -80,6 +80,10 @@ class PermissionStore
|
||||
'invoices:update',
|
||||
'invoices:download',
|
||||
'invoices:delete',
|
||||
'invoice-recipients:view',
|
||||
'invoice-recipients:create',
|
||||
'invoice-recipients:update',
|
||||
'invoice-recipients:delete',
|
||||
'invoice-settings:view',
|
||||
'invoice-settings:update',
|
||||
],
|
||||
@@ -147,6 +151,10 @@ class PermissionStore
|
||||
'invoices:update',
|
||||
'invoices:download',
|
||||
'invoices:delete',
|
||||
'invoice-recipients:view',
|
||||
'invoice-recipients:create',
|
||||
'invoice-recipients:update',
|
||||
'invoice-recipients:delete',
|
||||
'invoice-settings:view',
|
||||
'invoice-settings:update',
|
||||
],
|
||||
@@ -203,6 +211,10 @@ class PermissionStore
|
||||
'invoices:update',
|
||||
'invoices:download',
|
||||
'invoices:delete',
|
||||
'invoice-recipients:view',
|
||||
'invoice-recipients:create',
|
||||
'invoice-recipients:update',
|
||||
'invoice-recipients:delete',
|
||||
'invoice-settings:view',
|
||||
'invoice-settings:update',
|
||||
],
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Service\ReportExport;
|
||||
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\IntervalService;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
@@ -25,6 +26,7 @@ class TimeEntriesDetailedCsvExport extends CsvExport
|
||||
'Duration',
|
||||
'Duration (decimal)',
|
||||
'Billable',
|
||||
'Break',
|
||||
'Tags',
|
||||
];
|
||||
|
||||
@@ -58,6 +60,7 @@ class TimeEntriesDetailedCsvExport extends CsvExport
|
||||
'Duration' => $duration !== null ? $interval->format($model->getDuration()) : null,
|
||||
'Duration (decimal)' => $duration?->totalHours,
|
||||
'Billable' => $model->billable ? 'Yes' : 'No',
|
||||
'Break' => $model->type === TimeEntryType::Break ? 'Yes' : 'No',
|
||||
'Tags' => $model->tagsRelation->pluck('name')->implode(', '),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Service\ReportExport;
|
||||
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Models\TimeEntry;
|
||||
use App\Service\LocalizationService;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
@@ -106,6 +107,7 @@ class TimeEntriesDetailedExport implements FromQuery, ShouldAutoSize, WithColumn
|
||||
'Duration',
|
||||
'Duration (decimal)',
|
||||
'Billable',
|
||||
'Break',
|
||||
'Tags',
|
||||
];
|
||||
}
|
||||
@@ -130,6 +132,7 @@ class TimeEntriesDetailedExport implements FromQuery, ShouldAutoSize, WithColumn
|
||||
$duration !== null ? $this->localizationService->formatInterval($duration) : null,
|
||||
$duration?->totalHours,
|
||||
$model->billable ? 'Yes' : 'No',
|
||||
$model->type === TimeEntryType::Break ? 'Yes' : 'No',
|
||||
$model->tagsRelation->pluck('name')->implode(', '),
|
||||
];
|
||||
} elseif ($this->exportFormat === ExportFormat::ODS) {
|
||||
@@ -144,6 +147,7 @@ class TimeEntriesDetailedExport implements FromQuery, ShouldAutoSize, WithColumn
|
||||
$duration !== null ? $this->localizationService->formatInterval($duration) : null,
|
||||
$duration?->totalHours,
|
||||
$model->billable ? 'Yes' : 'No',
|
||||
$model->type === TimeEntryType::Break ? 'Yes' : 'No',
|
||||
$model->tagsRelation->pluck('name')->implode(', '),
|
||||
];
|
||||
} else {
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace App\Service\ReportExport;
|
||||
|
||||
use App\Enums\ExportFormat;
|
||||
use App\Enums\TimeEntryAggregationType;
|
||||
use App\Service\LocalizationService;
|
||||
use Illuminate\View\View;
|
||||
use Maatwebsite\Excel\Concerns\Exportable;
|
||||
use Maatwebsite\Excel\Concerns\FromView;
|
||||
@@ -48,6 +49,8 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
|
||||
|
||||
private bool $showBillableRate;
|
||||
|
||||
private LocalizationService $localization;
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* grouped_type: string|null,
|
||||
@@ -68,7 +71,7 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
|
||||
* cost: int|null
|
||||
* } $data
|
||||
*/
|
||||
public function __construct(array $data, ExportFormat $exportFormat, string $currency, TimeEntryAggregationType $group, TimeEntryAggregationType $subGroup, bool $showBillableRate)
|
||||
public function __construct(array $data, ExportFormat $exportFormat, string $currency, TimeEntryAggregationType $group, TimeEntryAggregationType $subGroup, bool $showBillableRate, LocalizationService $localization)
|
||||
{
|
||||
$this->data = $data;
|
||||
$this->exportFormat = $exportFormat;
|
||||
@@ -76,6 +79,7 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
|
||||
$this->group = $group;
|
||||
$this->subGroup = $subGroup;
|
||||
$this->showBillableRate = $showBillableRate;
|
||||
$this->localization = $localization;
|
||||
}
|
||||
|
||||
public function view(): View
|
||||
@@ -87,6 +91,7 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
|
||||
'subGroup' => $this->subGroup,
|
||||
'exportFormat' => $this->exportFormat,
|
||||
'showBillableRate' => $this->showBillableRate,
|
||||
'localization' => $this->localization,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -353,6 +353,13 @@ class TimeEntryAggregationService
|
||||
'color' => null,
|
||||
];
|
||||
}
|
||||
} elseif ($type === TimeEntryAggregationType::Type) {
|
||||
foreach ($keys as $key) {
|
||||
$descriptorMap[$key] = [
|
||||
'description' => $key === 'break' ? 'Break' : 'Work time',
|
||||
'color' => null,
|
||||
];
|
||||
}
|
||||
} elseif ($type === TimeEntryAggregationType::Tag) {
|
||||
$tags = Tag::query()
|
||||
->whereIn('id', $keys)
|
||||
@@ -504,6 +511,8 @@ class TimeEntryAggregationService
|
||||
return 'client_id';
|
||||
} elseif ($group === TimeEntryAggregationType::Billable) {
|
||||
return 'billable';
|
||||
} elseif ($group === TimeEntryAggregationType::Type) {
|
||||
return 'type';
|
||||
} elseif ($group === TimeEntryAggregationType::Description) {
|
||||
return 'description';
|
||||
} elseif ($group === TimeEntryAggregationType::Tag) {
|
||||
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace App\Service;
|
||||
|
||||
use App\Enums\TagMatchType;
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Models\Member;
|
||||
use App\Models\TimeEntry;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
@@ -144,6 +145,32 @@ class TimeEntryFilter
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function addTypeFilter(?string $type): self
|
||||
{
|
||||
if ($type === null) {
|
||||
return $this;
|
||||
}
|
||||
$typeEnum = TimeEntryType::tryFrom($type);
|
||||
if ($typeEnum === null) {
|
||||
Log::warning('Invalid type filter value', ['value' => $type]);
|
||||
|
||||
return $this;
|
||||
}
|
||||
$this->addType($typeEnum);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function addType(?TimeEntryType $type): self
|
||||
{
|
||||
if ($type === null) {
|
||||
return $this;
|
||||
}
|
||||
$this->builder->where('type', '=', $type->value);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string>|null $clientIds
|
||||
*/
|
||||
|
||||
@@ -75,11 +75,32 @@ return [
|
||||
|
||||
'url' => env('APP_URL', 'http://localhost'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Trusted Hosts
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Additional hostnames (besides the APP_URL host and its subdomains) that
|
||||
| the application is allowed to respond on. This is needed for multi-host
|
||||
| setups, e.g. reaching the instance over both a public domain and a
|
||||
| Tailscale name. A request arriving on any host that is neither APP_URL
|
||||
| (nor a subdomain of it) nor listed here is rejected, which prevents
|
||||
| Host-header poisoning of password reset and other out-of-band links.
|
||||
|
|
||||
| See App\Http\Middleware\TrustHosts.
|
||||
|
|
||||
*/
|
||||
|
||||
'trusted_hosts' => array_values(array_filter(array_map(
|
||||
'trim',
|
||||
explode(',', (string) env('TRUSTED_HOSTS', ''))
|
||||
))),
|
||||
|
||||
'asset_url' => env('ASSET_URL'),
|
||||
|
||||
'force_https' => (bool) env('APP_FORCE_HTTPS', false),
|
||||
|
||||
'enable_registration' => (bool) env('APP_ENABLE_REGISTRATION', false),
|
||||
'enable_registration' => env('APP_ENABLE_REGISTRATION', 'off'),
|
||||
|
||||
'local_email_verification' => (bool) env('APP_LOCAL_EMAIL_VERIFICATION', false),
|
||||
|
||||
@@ -137,6 +158,21 @@ return [
|
||||
|
||||
'pagination_per_page_default' => (int) env('PAGINATION_PER_PAGE_DEFAULT', 15),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| API Rate Limiting
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The number of API requests allowed per minute, counted per user for
|
||||
| authenticated requests and per IP address for guest requests. These
|
||||
| limits are only enforced when the application runs in production.
|
||||
|
|
||||
*/
|
||||
|
||||
'api_rate_limit_authenticated_per_minute' => (int) (env('API_RATE_LIMIT_AUTH_PER_MINUTE') ?: 200),
|
||||
|
||||
'api_rate_limit_guest_per_minute' => (int) (env('API_RATE_LIMIT_GUEST_PER_MINUTE') ?: 60),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Encryption Key
|
||||
|
||||
@@ -33,6 +33,7 @@ class OrganizationFactory extends Factory
|
||||
'user_id' => User::factory(),
|
||||
'personal_team' => true,
|
||||
'employees_can_see_billable_rates' => false,
|
||||
'breaks_enabled' => false,
|
||||
'number_format' => $this->faker->randomElement(NumberFormat::values()),
|
||||
'currency_format' => $this->faker->randomElement(CurrencyFormat::values()),
|
||||
'date_format' => $this->faker->randomElement(DateFormat::values()),
|
||||
@@ -55,6 +56,13 @@ class OrganizationFactory extends Factory
|
||||
]);
|
||||
}
|
||||
|
||||
public function withBreaksEnabled(): self
|
||||
{
|
||||
return $this->state(fn (array $attributes) => [
|
||||
'breaks_enabled' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
public function withOwner(?User $owner = null): self
|
||||
{
|
||||
return $this->state(fn (array $attributes) => [
|
||||
|
||||
@@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Enums\TimeEntryType;
|
||||
use App\Models\Member;
|
||||
use App\Models\Organization;
|
||||
use App\Models\Project;
|
||||
@@ -33,6 +34,7 @@ class TimeEntryFactory extends Factory
|
||||
'start' => $start,
|
||||
'end' => $this->faker->dateTimeBetween($start, 'now'),
|
||||
'billable' => $this->faker->boolean(),
|
||||
'type' => TimeEntryType::Work,
|
||||
'is_imported' => false,
|
||||
'tags' => [],
|
||||
'user_id' => User::factory(),
|
||||
@@ -44,6 +46,18 @@ class TimeEntryFactory extends Factory
|
||||
];
|
||||
}
|
||||
|
||||
public function isBreak(): self
|
||||
{
|
||||
return $this->state(function (array $attributes): array {
|
||||
return [
|
||||
'type' => TimeEntryType::Break,
|
||||
'billable' => false,
|
||||
'project_id' => null,
|
||||
'task_id' => null,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public function notBillable(): self
|
||||
{
|
||||
return $this->state(function (array $attributes): array {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('time_entries', function (Blueprint $table): void {
|
||||
$table->string('type')->default('work');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('time_entries', function (Blueprint $table): void {
|
||||
$table->dropColumn('type');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('organizations', function (Blueprint $table): void {
|
||||
$table->boolean('breaks_enabled')->default(false)->after('prevent_overlapping_time_entries');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('organizations', function (Blueprint $table): void {
|
||||
$table->dropColumn('breaks_enabled');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
use function Laravel\Prompts\info as consoleInfo;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* PostgreSQL cannot build or drop an index concurrently inside a transaction.
|
||||
* Keeping this migration non-transactional prevents long write locks in production.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
public $withinTransaction = false;
|
||||
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
// Tenant-scoped client pagination ordered by newest first; also covers the organization FK.
|
||||
$this->runIndexOperation('create', 'clients_organization_created_id_index', 'CREATE INDEX CONCURRENTLY clients_organization_created_id_index ON clients (organization_id, created_at DESC, id)');
|
||||
|
||||
// Tenant-scoped project pagination ordered by newest first; also covers the organization FK.
|
||||
$this->runIndexOperation('create', 'projects_organization_created_id_index', 'CREATE INDEX CONCURRENTLY projects_organization_created_id_index ON projects (organization_id, created_at DESC, id)');
|
||||
// Speeds client relationship loads and the FK check when a client is deleted or its ID changes.
|
||||
$this->runIndexOperation('create', 'projects_client_id_index', 'CREATE INDEX CONCURRENTLY projects_client_id_index ON projects (client_id)');
|
||||
|
||||
// Tenant-scoped task pagination ordered by newest first; also covers the organization FK.
|
||||
$this->runIndexOperation('create', 'tasks_organization_created_id_index', 'CREATE INDEX CONCURRENTLY tasks_organization_created_id_index ON tasks (organization_id, created_at DESC, id)');
|
||||
// Speeds project task lists and the FK check when a project is deleted or its ID changes.
|
||||
$this->runIndexOperation('create', 'tasks_project_id_index', 'CREATE INDEX CONCURRENTLY tasks_project_id_index ON tasks (project_id)');
|
||||
|
||||
// Tenant-scoped tag pagination ordered by newest first; also covers the organization FK.
|
||||
$this->runIndexOperation('create', 'tags_organization_created_id_index', 'CREATE INDEX CONCURRENTLY tags_organization_created_id_index ON tags (organization_id, created_at DESC, id)');
|
||||
|
||||
// Tenant-scoped report pagination ordered by newest first; also covers the organization FK.
|
||||
$this->runIndexOperation('create', 'reports_organization_created_id_index', 'CREATE INDEX CONCURRENTLY reports_organization_created_id_index ON reports (organization_id, created_at DESC, id)');
|
||||
|
||||
// Tenant-scoped member pagination; the existing (organization_id, user_id) unique index remains for membership lookup.
|
||||
$this->runIndexOperation('create', 'members_organization_created_id_index', 'CREATE INDEX CONCURRENTLY members_organization_created_id_index ON members (organization_id, created_at DESC, id)');
|
||||
// Supports reverse user-to-membership lookups and the FK check when a user is deleted or its ID changes.
|
||||
$this->runIndexOperation('create', 'members_user_id_index', 'CREATE INDEX CONCURRENTLY members_user_id_index ON members (user_id)');
|
||||
|
||||
// The existing (project_id, user_id) unique index covers project_id, but member_id and legacy user_id need reverse indexes.
|
||||
$this->runIndexOperation('create', 'project_members_member_id_index', 'CREATE INDEX CONCURRENTLY project_members_member_id_index ON project_members (member_id)');
|
||||
$this->runIndexOperation('create', 'project_members_user_id_index', 'CREATE INDEX CONCURRENTLY project_members_user_id_index ON project_members (user_id)');
|
||||
|
||||
// Supports organization deletion/current-team cleanup and the FK check on users.current_team_id.
|
||||
$this->runIndexOperation('create', 'users_current_team_id_index', 'CREATE INDEX CONCURRENTLY users_current_team_id_index ON users (current_team_id)');
|
||||
|
||||
// Filament loads the newest audits first; this avoids scanning and sorting the large append-only audit table.
|
||||
$this->runIndexOperation('create', 'audits_created_at_index', 'CREATE INDEX CONCURRENTLY audits_created_at_index ON audits (created_at DESC)');
|
||||
|
||||
// Main tenant time-entry range/pagination path, including its start DESC, id ordering; also covers the organization FK.
|
||||
$this->runIndexOperation('create', 'time_entries_organization_start_id_index', 'CREATE INDEX CONCURRENTLY time_entries_organization_start_id_index ON time_entries (organization_id, start DESC, id)');
|
||||
// Filament lists time entries globally by creation time, so the tenant-prefixed index cannot provide this ordering.
|
||||
$this->runIndexOperation('create', 'time_entries_created_at_index', 'CREATE INDEX CONCURRENTLY time_entries_created_at_index ON time_entries (created_at DESC)');
|
||||
// Dashboard history is consistently filtered by user and organization, then bounded by start; user first also covers its FK.
|
||||
$this->runIndexOperation('create', 'time_entries_user_organization_start_index', 'CREATE INDEX CONCURRENTLY time_entries_user_organization_start_index ON time_entries (user_id, organization_id, start)');
|
||||
// Member timelines, overlap checks, and billable-rate updates start with member_id; also covers its FK.
|
||||
$this->runIndexOperation('create', 'time_entries_member_start_index', 'CREATE INDEX CONCURRENTLY time_entries_member_start_index ON time_entries (member_id, start)');
|
||||
// These relationship/filter indexes also prevent full scans for FK checks when parent rows change or are deleted.
|
||||
$this->runIndexOperation('create', 'time_entries_project_id_index', 'CREATE INDEX CONCURRENTLY time_entries_project_id_index ON time_entries (project_id)');
|
||||
$this->runIndexOperation('create', 'time_entries_task_id_index', 'CREATE INDEX CONCURRENTLY time_entries_task_id_index ON time_entries (task_id)');
|
||||
$this->runIndexOperation('create', 'time_entries_client_id_index', 'CREATE INDEX CONCURRENTLY time_entries_client_id_index ON time_entries (client_id)');
|
||||
// Active-timer checks touch only open entries, so a partial index stays small while serving the hot member_id lookup.
|
||||
$this->runIndexOperation('create', 'time_entries_active_member_index', 'CREATE INDEX CONCURRENTLY time_entries_active_member_index ON time_entries (member_id) WHERE "end" IS NULL');
|
||||
// whereJsonContains(tags, tag_id) compiles to JSONB containment, which is supported by a GIN index.
|
||||
$this->runIndexOperation('create', 'time_entries_tags_gin_index', 'CREATE INDEX CONCURRENTLY time_entries_tags_gin_index ON time_entries USING GIN (tags)');
|
||||
|
||||
// Passport already indexes user_id; these indexes cover the other FK used during OAuth client deletion/update.
|
||||
$this->runIndexOperation('create', 'oauth_access_tokens_client_id_index', 'CREATE INDEX CONCURRENTLY oauth_access_tokens_client_id_index ON oauth_access_tokens (client_id)');
|
||||
$this->runIndexOperation('create', 'oauth_auth_codes_client_id_index', 'CREATE INDEX CONCURRENTLY oauth_auth_codes_client_id_index ON oauth_auth_codes (client_id)');
|
||||
|
||||
// owner_id is already the leading column of oauth_clients_owner_id_owner_type_index.
|
||||
$this->runIndexOperation('drop', 'oauth_clients_user_id_index', 'DROP INDEX CONCURRENTLY oauth_clients_user_id_index');
|
||||
// Public report lookup starts with the unique share_secret index; no query filters only by this boolean.
|
||||
$this->runIndexOperation('drop', 'reports_is_public_index', 'DROP INDEX CONCURRENTLY reports_is_public_index');
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
$indexes = [
|
||||
'clients_organization_created_id_index',
|
||||
'projects_organization_created_id_index',
|
||||
'projects_client_id_index',
|
||||
'tasks_organization_created_id_index',
|
||||
'tasks_project_id_index',
|
||||
'tags_organization_created_id_index',
|
||||
'reports_organization_created_id_index',
|
||||
'members_organization_created_id_index',
|
||||
'members_user_id_index',
|
||||
'project_members_member_id_index',
|
||||
'project_members_user_id_index',
|
||||
'users_current_team_id_index',
|
||||
'audits_created_at_index',
|
||||
'time_entries_organization_start_id_index',
|
||||
'time_entries_created_at_index',
|
||||
'time_entries_user_organization_start_index',
|
||||
'time_entries_member_start_index',
|
||||
'time_entries_project_id_index',
|
||||
'time_entries_task_id_index',
|
||||
'time_entries_client_id_index',
|
||||
'time_entries_active_member_index',
|
||||
'time_entries_tags_gin_index',
|
||||
'oauth_access_tokens_client_id_index',
|
||||
'oauth_auth_codes_client_id_index',
|
||||
];
|
||||
|
||||
$concurrently = DB::transactionLevel() === 0 ? ' CONCURRENTLY' : '';
|
||||
foreach ($indexes as $index) {
|
||||
$this->runIndexOperation('drop', $index, 'DROP INDEX'.$concurrently.' IF EXISTS '.$index);
|
||||
}
|
||||
|
||||
$this->runIndexOperation('create', 'oauth_clients_user_id_index', 'CREATE INDEX'.$concurrently.' oauth_clients_user_id_index ON oauth_clients (owner_id)');
|
||||
$this->runIndexOperation('create', 'reports_is_public_index', 'CREATE INDEX'.$concurrently.' reports_is_public_index ON reports (is_public)');
|
||||
}
|
||||
|
||||
private function runIndexOperation(string $operation, string $index, string $statement): void
|
||||
{
|
||||
$indexState = $this->indexState($index);
|
||||
|
||||
if ($operation === 'create' && $indexState === ['valid' => true, 'ready' => true]) {
|
||||
$this->writeProgress(sprintf('Skipping index [%s] because it already exists and is valid', $index));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($operation === 'drop' && $indexState === null) {
|
||||
$this->writeProgress(sprintf('Skipping index [%s] because it does not exist', $index));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($operation === 'create' && $indexState !== null) {
|
||||
$this->writeProgress(sprintf(
|
||||
'Index [%s] exists but is incomplete (valid=%s, ready=%s); dropping it before rebuilding',
|
||||
$index,
|
||||
$indexState['valid'] ? 'true' : 'false',
|
||||
$indexState['ready'] ? 'true' : 'false',
|
||||
));
|
||||
$this->executeIndexStatement(
|
||||
'drop incomplete',
|
||||
$index,
|
||||
(DB::transactionLevel() === 0 ? 'DROP INDEX CONCURRENTLY ' : 'DROP INDEX ').$this->quoteIdentifier($index),
|
||||
);
|
||||
}
|
||||
|
||||
$this->executeIndexStatement($operation, $index, $statement);
|
||||
}
|
||||
|
||||
private function executeIndexStatement(string $operation, string $index, string $statement): void
|
||||
{
|
||||
$startedAt = microtime(true);
|
||||
$this->writeProgress(sprintf('Starting to %s index [%s]', $operation, $index));
|
||||
|
||||
try {
|
||||
DB::statement($statement);
|
||||
} catch (Throwable $exception) {
|
||||
$this->writeProgress(sprintf(
|
||||
'Failed to %s index [%s] after %.2f seconds: %s',
|
||||
$operation,
|
||||
$index,
|
||||
microtime(true) - $startedAt,
|
||||
$exception->getMessage(),
|
||||
));
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->writeProgress(sprintf(
|
||||
'Finished %s index [%s] in %.2f seconds',
|
||||
$operation === 'create' ? 'creating' : 'dropping',
|
||||
$index,
|
||||
microtime(true) - $startedAt,
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{valid: bool, ready: bool}|null
|
||||
*/
|
||||
private function indexState(string $index): ?array
|
||||
{
|
||||
$state = DB::selectOne(
|
||||
<<<'SQL'
|
||||
SELECT pg_index.indisvalid::int AS valid, pg_index.indisready::int AS ready
|
||||
FROM pg_index
|
||||
JOIN pg_class ON pg_class.oid = pg_index.indexrelid
|
||||
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
|
||||
WHERE pg_namespace.nspname = current_schema()
|
||||
AND pg_class.relname = ?
|
||||
SQL,
|
||||
[$index],
|
||||
);
|
||||
|
||||
if ($state === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'valid' => (bool) $state->valid,
|
||||
'ready' => (bool) $state->ready,
|
||||
];
|
||||
}
|
||||
|
||||
private function quoteIdentifier(string $identifier): string
|
||||
{
|
||||
return DB::connection()->getQueryGrammar()->wrap($identifier);
|
||||
}
|
||||
|
||||
private function writeProgress(string $message): void
|
||||
{
|
||||
if (app()->runningUnitTests()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$message = sprintf('[%s] %s', date(DATE_ATOM), $message);
|
||||
Log::info($message);
|
||||
consoleInfo($message);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table): void {
|
||||
$table->boolean('send_time_entry_still_running_email')->default(true)->after('week_start');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table): void {
|
||||
$table->dropColumn('send_time_entry_still_running_email');
|
||||
});
|
||||
}
|
||||
};
|
||||
278
e2e/breaks.spec.ts
Normal file
278
e2e/breaks.spec.ts
Normal file
@@ -0,0 +1,278 @@
|
||||
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 { createTimeEntryViaApi, updateOrganizationSettingViaApi } from './utils/api';
|
||||
|
||||
async function goToDashboard(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
}
|
||||
|
||||
function visibleBreakButton(page: Page) {
|
||||
return page.getByRole('button', { name: 'Take a break' }).locator('visible=true').first();
|
||||
}
|
||||
|
||||
// Breaks are disabled by default for new organizations, so enable them for the break flows.
|
||||
// The tests that assert the disabled behaviour turn them back off explicitly.
|
||||
test.beforeEach(async ({ ctx }) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
});
|
||||
|
||||
test('test that switching to a break stops the work timer and starts a break entry', async ({
|
||||
page,
|
||||
}) => {
|
||||
await goToDashboard(page);
|
||||
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||
await page.getByTestId('time_entry_description').fill('Work before break');
|
||||
await Promise.all([
|
||||
newTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||
page.getByTestId('time_entry_description').press('Enter'),
|
||||
]);
|
||||
await assertThatTimerHasStarted(page);
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
// Switch to break: stops the work entry and starts a break entry
|
||||
await Promise.all([
|
||||
newTimeEntryResponse(page, { description: '', type: 'break' }),
|
||||
visibleBreakButton(page).click(),
|
||||
]);
|
||||
await expect(page.getByText('On break')).toBeVisible();
|
||||
|
||||
// The break bar offers a one-click resume that stops the break and restores
|
||||
// the interrupted work context
|
||||
await page.waitForTimeout(1500);
|
||||
const resumeButton = page.getByRole('button', { name: 'Resume "Work before break"' });
|
||||
await expect(resumeButton).toBeVisible();
|
||||
await Promise.all([
|
||||
stoppedTimeEntryResponse(page, { type: 'break' }),
|
||||
newTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||
resumeButton.click(),
|
||||
]);
|
||||
await assertThatTimerHasStarted(page);
|
||||
await expect(page.getByTestId('time_entry_description')).toHaveValue('Work before break');
|
||||
|
||||
// Cleanup: stop the running entry
|
||||
await Promise.all([
|
||||
stoppedTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||
startOrStopTimerWithButton(page),
|
||||
]);
|
||||
await assertThatTimerIsStopped(page);
|
||||
});
|
||||
|
||||
test('test that stopping a break returns to an idle tracker where a fresh entry starts normally', async ({
|
||||
page,
|
||||
}) => {
|
||||
await goToDashboard(page);
|
||||
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||
await page.getByTestId('time_entry_description').fill('Work before break');
|
||||
await Promise.all([
|
||||
newTimeEntryResponse(page, { description: 'Work before break', type: 'work' }),
|
||||
page.getByTestId('time_entry_description').press('Enter'),
|
||||
]);
|
||||
await assertThatTimerHasStarted(page);
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
// Switch to a break
|
||||
await Promise.all([
|
||||
newTimeEntryResponse(page, { description: '', type: 'break' }),
|
||||
visibleBreakButton(page).click(),
|
||||
]);
|
||||
await expect(page.getByText('On break')).toBeVisible();
|
||||
|
||||
// Stopping the break just ends it — no modal, the tracker returns to the
|
||||
// empty idle input with focus so typing starts a fresh entry
|
||||
await page.waitForTimeout(1500);
|
||||
await Promise.all([
|
||||
stoppedTimeEntryResponse(page, { type: 'break' }),
|
||||
startOrStopTimerWithButton(page),
|
||||
]);
|
||||
await assertThatTimerIsStopped(page);
|
||||
await expect(page.getByTestId('time_entry_description')).toHaveValue('');
|
||||
await expect(page.getByTestId('time_entry_description')).toBeFocused();
|
||||
|
||||
// A fresh entry is the normal start flow: type + Enter
|
||||
await page.getByTestId('time_entry_description').fill('Fresh after break');
|
||||
await Promise.all([
|
||||
newTimeEntryResponse(page, { description: 'Fresh after break', type: 'work' }),
|
||||
page.getByTestId('time_entry_description').press('Enter'),
|
||||
]);
|
||||
await assertThatTimerHasStarted(page);
|
||||
|
||||
// Cleanup: stop the running entry
|
||||
await Promise.all([
|
||||
stoppedTimeEntryResponse(page, { description: 'Fresh after break', type: 'work' }),
|
||||
startOrStopTimerWithButton(page),
|
||||
]);
|
||||
await assertThatTimerIsStopped(page);
|
||||
});
|
||||
|
||||
test('test that the more options dropdown can start a break directly', async ({ page }) => {
|
||||
await goToDashboard(page);
|
||||
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||
|
||||
// Start a break straight from the more options dropdown (no create modal)
|
||||
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||
await Promise.all([
|
||||
newTimeEntryResponse(page, { description: '', type: 'break' }),
|
||||
page.getByRole('menuitem', { name: 'Start Break' }).click(),
|
||||
]);
|
||||
await expect(page.getByText('On break')).toBeVisible();
|
||||
|
||||
// Without interrupted work there is nothing to resume, so no resume button is offered
|
||||
await expect(page.getByRole('button', { name: /^Resume/ })).toHaveCount(0);
|
||||
|
||||
// Cleanup: stop the break
|
||||
await page.waitForTimeout(1500);
|
||||
await Promise.all([
|
||||
stoppedTimeEntryResponse(page, { type: 'break' }),
|
||||
startOrStopTimerWithButton(page),
|
||||
]);
|
||||
await assertThatTimerIsStopped(page);
|
||||
});
|
||||
|
||||
test('test that disabling breaks hides every break-creation entry point', async ({ page, ctx }) => {
|
||||
// Breaks disabled for the organization (delivered to the client via the organization endpoint)
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: false });
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', description: 'Regular work' });
|
||||
|
||||
// Calendar: the empty-slot context menu offers "Create Time Entry" but no "Add Break",
|
||||
// and the edit modal drops the work-time/break type selector
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/calendar');
|
||||
await expect(page.locator('.fc')).toBeVisible();
|
||||
const event = page.locator('.fc-event').filter({ hasText: 'Regular work' }).first();
|
||||
await event.scrollIntoViewIfNeeded();
|
||||
await expect(event).toBeVisible();
|
||||
|
||||
const box = await event.boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
await page.mouse.click(box!.x + box!.width / 2, box!.y + box!.height + 40, { button: 'right' });
|
||||
await expect(page.getByRole('menu')).toBeVisible();
|
||||
await expect(page.getByRole('menuitem', { name: 'Create Time Entry' })).toBeVisible();
|
||||
await expect(page.getByRole('menuitem', { name: 'Add Break' })).toHaveCount(0);
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
await event.click({ button: 'right' });
|
||||
await expect(page.getByRole('menu')).toBeVisible();
|
||||
await page.getByRole('menuitem', { name: 'Edit' }).click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole('dialog').getByRole('combobox').filter({ hasText: 'Work time' })
|
||||
).toHaveCount(0);
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
// Timesheet: no break row is shown
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/timesheet');
|
||||
await expect(page.getByRole('button', { name: 'Add row' }).first()).toBeVisible();
|
||||
await expect(page.getByText('Break', { exact: true })).toHaveCount(0);
|
||||
|
||||
// Dashboard tracker: no "Start Break" in the more options dropdown
|
||||
await goToDashboard(page);
|
||||
await expect(page.getByTestId('time_entry_description')).toBeEditable();
|
||||
await page.getByRole('button', { name: 'Time entry actions' }).click();
|
||||
await expect(page.getByRole('menuitem', { name: 'Switch to simple mode' })).toBeVisible();
|
||||
await expect(page.getByRole('menuitem', { name: 'Start Break' })).toHaveCount(0);
|
||||
});
|
||||
|
||||
// The employee fixture registers a second user and accepts an invitation via Mailpit,
|
||||
// which does not fit into the default per-test timeout.
|
||||
test.describe('Org-level breaks setting', () => {
|
||||
test.describe.configure({ timeout: 60000 });
|
||||
|
||||
test('test that the org-level breaks setting is respected for employees', async ({
|
||||
ctx,
|
||||
employee,
|
||||
}) => {
|
||||
const employeePage = employee.page;
|
||||
|
||||
// Breaks enabled (via beforeEach): the employee sees "Start Break" in the more options dropdown
|
||||
await employeePage.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employeePage.getByTestId('dashboard_view')).toBeVisible();
|
||||
await employeePage.getByRole('button', { name: 'Time entry actions' }).click();
|
||||
await expect(
|
||||
employeePage.getByRole('menuitem', { name: 'Switch to simple mode' })
|
||||
).toBeVisible();
|
||||
await expect(employeePage.getByRole('menuitem', { name: 'Start Break' })).toBeVisible();
|
||||
await employeePage.keyboard.press('Escape');
|
||||
|
||||
// The owner disables breaks for the whole organization
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: false });
|
||||
|
||||
// The employee reloads: "Start Break" is gone from the dropdown
|
||||
await employeePage.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await expect(employeePage.getByTestId('dashboard_view')).toBeVisible();
|
||||
await employeePage.getByRole('button', { name: 'Time entry actions' }).click();
|
||||
await expect(
|
||||
employeePage.getByRole('menuitem', { name: 'Switch to simple mode' })
|
||||
).toBeVisible();
|
||||
await expect(employeePage.getByRole('menuitem', { name: 'Start Break' })).toHaveCount(0);
|
||||
await employeePage.keyboard.press('Escape');
|
||||
|
||||
// With an active timer the break (coffee) button is not shown either
|
||||
await employeePage.getByTestId('time_entry_description').fill('Employee work');
|
||||
await Promise.all([
|
||||
newTimeEntryResponse(employeePage, { description: 'Employee work', type: 'work' }),
|
||||
employeePage.getByTestId('time_entry_description').press('Enter'),
|
||||
]);
|
||||
await assertThatTimerHasStarted(employeePage);
|
||||
await expect(employeePage.getByRole('button', { name: 'Take a break' })).toHaveCount(0);
|
||||
|
||||
// Cleanup: stop the running entry
|
||||
await Promise.all([
|
||||
stoppedTimeEntryResponse(employeePage, { description: 'Employee work', type: 'work' }),
|
||||
startOrStopTimerWithButton(employeePage),
|
||||
]);
|
||||
await assertThatTimerIsStopped(employeePage);
|
||||
});
|
||||
});
|
||||
|
||||
test('test that mass update warns about selected breaks and reports skipped entries instead of success', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// One work entry and one break: a billable mass update applies to the work
|
||||
// entry but the server skips the break entirely — the UI must say so.
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', description: 'Mass update work entry' });
|
||||
await createTimeEntryViaApi(ctx, { duration: '30min', type: 'break' });
|
||||
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
|
||||
await expect(page.locator('[data-testid="time_entry_row"]')).toHaveCount(2);
|
||||
await page.getByLabel('Select All').click();
|
||||
await expect(page.getByText('2 selected')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Edit' }).click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// No warning while the changeset is compatible with breaks
|
||||
await expect(page.getByTestId('mass_update_break_warning')).not.toBeVisible();
|
||||
|
||||
// Making the entries billable is break-incompatible → warning appears
|
||||
await page
|
||||
.getByRole('dialog')
|
||||
.getByRole('combobox')
|
||||
.filter({ hasText: 'Set billable status' })
|
||||
.click();
|
||||
await page.getByRole('option', { name: 'Billable', exact: true }).click();
|
||||
await expect(page.getByTestId('mass_update_break_warning')).toBeVisible();
|
||||
await expect(page.getByTestId('mass_update_break_warning')).toContainText('skipped entirely');
|
||||
|
||||
// Submit: the work entry updates, the break is skipped, and the toast
|
||||
// reports the skip instead of claiming success for all entries
|
||||
const [massUpdateResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries') &&
|
||||
response.request().method() === 'PATCH' &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('button', { name: 'Update Time Entries' }).click(),
|
||||
]);
|
||||
const massUpdateBody = await massUpdateResponse.json();
|
||||
expect(massUpdateBody.success.length).toBe(1);
|
||||
expect(massUpdateBody.error.length).toBe(1);
|
||||
await expect(page.getByText('1 of 2 time entries was skipped')).toBeVisible();
|
||||
});
|
||||
@@ -2874,3 +2874,54 @@ test.describe('Daily Total After Create', () => {
|
||||
}).toPass({ timeout: 5000 });
|
||||
});
|
||||
});
|
||||
|
||||
test('test that calendar context menu can add a break that fills the gap between two entries', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
// Two work entries today (09:00-10:00 and 11:00-12:00 UTC) with a one hour gap
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const gapStart = `${today}T10:00:00Z`;
|
||||
const gapEnd = `${today}T11:00:00Z`;
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${today}T09:00:00Z`,
|
||||
end: gapStart,
|
||||
description: 'Gap work A',
|
||||
});
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: gapEnd,
|
||||
end: `${today}T12:00:00Z`,
|
||||
description: 'Gap work B',
|
||||
});
|
||||
|
||||
await goToCalendar(page);
|
||||
const eventA = page.locator('.fc-event').filter({ hasText: 'Gap work A' }).first();
|
||||
await eventA.scrollIntoViewIfNeeded();
|
||||
await expect(eventA).toBeVisible();
|
||||
|
||||
// Right-click just below entry A (inside the gap, in the same day column)
|
||||
const box = await eventA.boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
await page.mouse.click(box!.x + box!.width / 2, box!.y + box!.height + 15, {
|
||||
button: 'right',
|
||||
});
|
||||
await expect(page.getByRole('menu')).toBeVisible();
|
||||
await page.getByRole('menuitem', { name: 'Add Break' }).click();
|
||||
await expect(page.getByRole('dialog')).toBeVisible();
|
||||
|
||||
// The break is prefilled to fill the gap exactly
|
||||
const [createResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
async (response) =>
|
||||
response.url().includes('/time-entries') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 201 &&
|
||||
(await response.json()).data.type === 'break'
|
||||
),
|
||||
page.getByRole('button', { name: 'Add Break' }).click(),
|
||||
]);
|
||||
const body = await createResponse.json();
|
||||
expect(body.data.start).toBe(gapStart);
|
||||
expect(body.data.end).toBe(gapEnd);
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
createProjectViaApi,
|
||||
createPublicProjectViaApi,
|
||||
} from './utils/api';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
import { clearTableState, getTableRowNames } from './utils/table';
|
||||
|
||||
async function goToClientsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/clients');
|
||||
@@ -210,18 +210,12 @@ test('test that client context menu delete deletes the client', async ({ page, c
|
||||
// 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 clearTableState(page, 'client-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
@@ -253,7 +247,7 @@ test('test that sorting clients by project count works', async ({ page, ctx }) =
|
||||
await createProjectViaApi(ctx, { name: 'Proj2', client_id: clientWithMany.id });
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
@@ -274,7 +268,7 @@ test('test that sorting clients by project count works', async ({ page, ctx }) =
|
||||
|
||||
test('test that client sort state persists after page reload', async ({ page }) => {
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
@@ -397,7 +391,7 @@ test.describe('Clients Pagination', () => {
|
||||
);
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await page.reload();
|
||||
|
||||
// Default sort is name asc; first 15 clients (00–14) on page 1.
|
||||
@@ -450,7 +444,7 @@ test.describe('Clients Pagination', () => {
|
||||
);
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId('client_table')).toBeVisible();
|
||||
@@ -470,7 +464,7 @@ test.describe('Clients Pagination', () => {
|
||||
);
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearClientTableState(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
32
e2e/invitation-registration-prefill.spec.ts
Normal file
32
e2e/invitation-registration-prefill.spec.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { expect, test } from '../playwright/fixtures';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { getInvitationAcceptUrl } from './utils/mailpit';
|
||||
|
||||
test('prefills the registration email after accepting an invitation', async ({ page, browser }) => {
|
||||
const memberId = `${Date.now()}-${Math.floor(Math.random() * 100000)}`;
|
||||
const memberEmail = `prefill-${memberId}@invitation.test`;
|
||||
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/members');
|
||||
await page.getByRole('button', { name: 'Invite Member' }).click();
|
||||
await page.getByPlaceholder('Member Email').fill(memberEmail);
|
||||
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(),
|
||||
]);
|
||||
|
||||
const inviteeContext = await browser.newContext();
|
||||
const inviteePage = await inviteeContext.newPage();
|
||||
const acceptUrl = await getInvitationAcceptUrl(inviteePage.request, memberEmail);
|
||||
await inviteePage.goto(acceptUrl);
|
||||
await inviteePage.waitForURL(/\/register$/);
|
||||
|
||||
await expect(inviteePage.getByLabel('Email')).toHaveValue(memberEmail);
|
||||
|
||||
await inviteeContext.close();
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
updateMemberBillableRateViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
import { clearTableState, getTableRowNames } from './utils/table';
|
||||
|
||||
// Tests that invite + accept members need more time
|
||||
test.describe.configure({ timeout: 45000 });
|
||||
@@ -779,20 +779,18 @@ test('test that accepted invitation disappears from invitations tab', async ({ p
|
||||
// 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"
|
||||
// Create two placeholder members with names that sort predictably around "John Doe".
|
||||
// Seeded alphabetically a second apart: created_at only has second precision and
|
||||
// same-second rows fall back to a random UUID order. The spacing is what makes the
|
||||
// API order (created_at desc: ZZZ, AAA, John) deterministic, so the tie-break
|
||||
// assertions below are testing the tie-break rather than a coin flip.
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'AAA SortFirst');
|
||||
await page.waitForTimeout(1100);
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'ZZZ SortLast');
|
||||
|
||||
await goToMembersPage(page);
|
||||
await clearMemberTableState(page);
|
||||
await clearTableState(page, 'member-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
@@ -814,20 +812,24 @@ test('test that sorting members by name, role, and status works', async ({ page,
|
||||
const ownerIdx = names.indexOf('John Doe');
|
||||
const placeholderIdx = names.indexOf('AAA SortFirst');
|
||||
expect(ownerIdx).toBeLessThan(placeholderIdx);
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
|
||||
|
||||
await roleHeader.click(); // desc: Placeholder first
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe'));
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
|
||||
|
||||
// -- 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'));
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
|
||||
|
||||
await statusHeader.click(); // desc: Inactive first
|
||||
names = await getTableRowNames(table);
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('John Doe'));
|
||||
expect(names.indexOf('AAA SortFirst')).toBeLessThan(names.indexOf('ZZZ SortLast'));
|
||||
|
||||
// -- Email: just verify sort indicator appears --
|
||||
const emailHeader = table.getByText('Email').first();
|
||||
@@ -837,7 +839,7 @@ test('test that sorting members by name, role, and status works', async ({ page,
|
||||
|
||||
test('test that member sort state persists after page reload', async ({ page }) => {
|
||||
await goToMembersPage(page);
|
||||
await clearMemberTableState(page);
|
||||
await clearTableState(page, 'member-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
@@ -875,7 +877,7 @@ test('test that sorting members by billable rate works', async ({ page, ctx }) =
|
||||
await updateMemberBillableRateViaApi(ctx, lowRateMember!.id, 5000);
|
||||
|
||||
await goToMembersPage(page);
|
||||
await clearMemberTableState(page);
|
||||
await clearTableState(page, 'member-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
|
||||
@@ -4,7 +4,7 @@ import { PLAYWRIGHT_BASE_URL, TEST_USER_PASSWORD } from '../playwright/config';
|
||||
async function goToOrganizationSettings(page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await page.locator('[data-testid="organization_switcher"]:visible').click();
|
||||
await page.getByText('Organization Settings').click();
|
||||
await page.getByRole('menuitem', { name: 'Organization Settings' }).click();
|
||||
}
|
||||
|
||||
async function createTimeEntry(page, duration: string) {
|
||||
|
||||
@@ -20,6 +20,12 @@ function profileInformationForm(page: Page) {
|
||||
.locator('xpath=ancestor::*[descendant::form][1]');
|
||||
}
|
||||
|
||||
function notificationSettingsForm(page: Page) {
|
||||
return page
|
||||
.getByRole('heading', { name: 'Notifications', exact: true })
|
||||
.locator('xpath=ancestor::*[descendant::form][1]');
|
||||
}
|
||||
|
||||
async function saveProfileForm(page: Page): Promise<void> {
|
||||
const form = profileInformationForm(page);
|
||||
await form.getByRole('button', { name: 'Save' }).click();
|
||||
@@ -50,6 +56,22 @@ test('week-start change persists across reload', async ({ page }) => {
|
||||
await expect(page.getByLabel('Start of the week')).toHaveValue('sunday');
|
||||
});
|
||||
|
||||
test('still-running email notification setting persists across reload', async ({ page }) => {
|
||||
await goToProfilePage(page);
|
||||
const form = notificationSettingsForm(page);
|
||||
const checkbox = form.getByLabel('Still-running time entry reminders');
|
||||
|
||||
await expect(checkbox).toBeChecked();
|
||||
await checkbox.uncheck();
|
||||
await form.getByRole('button', { name: 'Save' }).click();
|
||||
await expect(form.getByText('Saved.', { exact: true })).toBeVisible();
|
||||
|
||||
await page.reload();
|
||||
await expect(
|
||||
notificationSettingsForm(page).getByLabel('Still-running time entry reminders')
|
||||
).not.toBeChecked();
|
||||
});
|
||||
|
||||
test('profile photo can be uploaded, persists across reload, and can be removed', async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -13,18 +13,12 @@ import {
|
||||
archiveProjectViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
import { clearTableState, getSeededRowOrder } from './utils/table';
|
||||
|
||||
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);
|
||||
@@ -84,7 +78,7 @@ test('test that archiving and unarchiving projects works', async ({ page, ctx })
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
@@ -480,7 +474,7 @@ test('test that sorting projects by all columns works', async ({ page, ctx }) =>
|
||||
});
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
await expect(page.getByTestId('project_table')).toBeVisible();
|
||||
await expect(page.getByText('AAA Project')).toBeVisible();
|
||||
@@ -609,7 +603,7 @@ test('test that filtering projects by status works', async ({ page, ctx }) => {
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
@@ -640,7 +634,7 @@ test('test that filtering projects by status works', async ({ page, ctx }) => {
|
||||
|
||||
test('test that filter state persists after page reload', async ({ page }) => {
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
|
||||
// Apply Active status filter
|
||||
@@ -656,9 +650,96 @@ test('test that filter state persists after page reload', async ({ page }) => {
|
||||
await expect(page.getByTestId('status-filter-badge')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that projects without a client or estimate are ordered by name at the bottom', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Seeded a second apart: created_at only has second precision and same-second rows
|
||||
// fall back to a random UUID order. The spacing makes the API order of the clientless
|
||||
// rows (created_at desc: ZZZ, AAA) deterministic and different from the alphabetical
|
||||
// order the name tie-break should produce.
|
||||
await createProjectViaApi(ctx, { name: 'AAA Tiebreak Project' });
|
||||
await page.waitForTimeout(1100);
|
||||
await createProjectViaApi(ctx, { name: 'ZZZ Tiebreak Project' });
|
||||
|
||||
const clientAardvark = await createClientViaApi(ctx, { name: 'Aardvark Co' });
|
||||
const clientZulu = await createClientViaApi(ctx, { name: 'Zulu Co' });
|
||||
const projectM = await createProjectViaApi(ctx, {
|
||||
name: 'MMM Tiebreak Project',
|
||||
client_id: clientAardvark.id,
|
||||
estimated_time: 36000, // 10h, 1h tracked below = 10%
|
||||
});
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', projectId: projectM.id });
|
||||
const projectN = await createProjectViaApi(ctx, {
|
||||
name: 'NNN Tiebreak Project',
|
||||
client_id: clientZulu.id,
|
||||
estimated_time: 14400, // 4h, 2h tracked below = 50%
|
||||
});
|
||||
await createTimeEntryViaApi(ctx, { duration: '2h', projectId: projectN.id });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('project_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
const seeded = [
|
||||
'AAA Tiebreak Project',
|
||||
'MMM Tiebreak Project',
|
||||
'NNN Tiebreak Project',
|
||||
'ZZZ Tiebreak Project',
|
||||
];
|
||||
const getOrder = () => getSeededRowOrder(table, seeded);
|
||||
|
||||
// -- Client: empty rows last in both directions, alphabetical among themselves --
|
||||
const clientHeader = table.locator('.select-none', { hasText: 'Client' }).first();
|
||||
await clientHeader.click();
|
||||
await expect
|
||||
.poll(getOrder)
|
||||
.toEqual([
|
||||
'MMM Tiebreak Project',
|
||||
'NNN Tiebreak Project',
|
||||
'AAA Tiebreak Project',
|
||||
'ZZZ Tiebreak Project',
|
||||
]);
|
||||
|
||||
await clientHeader.click();
|
||||
await expect
|
||||
.poll(getOrder)
|
||||
.toEqual([
|
||||
'NNN Tiebreak Project',
|
||||
'MMM Tiebreak Project',
|
||||
'AAA Tiebreak Project',
|
||||
'ZZZ Tiebreak Project',
|
||||
]);
|
||||
|
||||
// -- Progress: same, and the first click sorts highest first --
|
||||
const progressHeader = table.locator('.select-none', { hasText: 'Progress' }).first();
|
||||
await progressHeader.click();
|
||||
await expect
|
||||
.poll(getOrder)
|
||||
.toEqual([
|
||||
'NNN Tiebreak Project',
|
||||
'MMM Tiebreak Project',
|
||||
'AAA Tiebreak Project',
|
||||
'ZZZ Tiebreak Project',
|
||||
]);
|
||||
|
||||
await progressHeader.click();
|
||||
await expect
|
||||
.poll(getOrder)
|
||||
.toEqual([
|
||||
'MMM Tiebreak Project',
|
||||
'NNN Tiebreak Project',
|
||||
'AAA Tiebreak Project',
|
||||
'ZZZ Tiebreak Project',
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that sort state persists after page reload', async ({ page }) => {
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
|
||||
// Click on Name header twice to sort descending
|
||||
@@ -1114,7 +1195,7 @@ test.describe('Projects Pagination', () => {
|
||||
);
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
|
||||
// Default sort is name asc; first 15 projects (00–14) should be on page 1.
|
||||
@@ -1168,7 +1249,7 @@ test.describe('Projects Pagination', () => {
|
||||
);
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId('project_table')).toBeVisible();
|
||||
@@ -1185,7 +1266,7 @@ test.describe('Projects Pagination', () => {
|
||||
);
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearProjectTableState(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 });
|
||||
@@ -1207,3 +1288,36 @@ test.describe('Projects Pagination', () => {
|
||||
await expect(page.getByText(prefix + '00')).not.toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test('test that searching projects by name works', async ({ page, ctx }) => {
|
||||
const suffix = Math.floor(1 + Math.random() * 10000);
|
||||
const matchingProjectName = 'Searchable Project ' + suffix;
|
||||
const otherProjectName = 'Unrelated Work ' + suffix;
|
||||
await createProjectViaApi(ctx, { name: matchingProjectName });
|
||||
await createProjectViaApi(ctx, { name: otherProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await page.reload();
|
||||
await expect(page.getByText(matchingProjectName)).toBeVisible({ timeout: 10000 });
|
||||
await expect(page.getByText(otherProjectName)).toBeVisible();
|
||||
|
||||
const searchInput = page.getByRole('searchbox', { name: 'Search projects' });
|
||||
|
||||
// Searching is case insensitive and matches part of the name
|
||||
await searchInput.fill('SEARCHABLE');
|
||||
await expect(page.getByText(matchingProjectName)).toBeVisible();
|
||||
await expect(page.getByText(otherProjectName)).not.toBeVisible();
|
||||
|
||||
// A term that matches nothing empties the table
|
||||
await searchInput.fill('no project has this name');
|
||||
await expect(page.getByText(matchingProjectName)).not.toBeVisible();
|
||||
await expect(page.getByText(otherProjectName)).not.toBeVisible();
|
||||
await expect(page.getByText('No matching projects')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Create your First Project' })).not.toBeVisible();
|
||||
|
||||
// Clearing the search restores both projects
|
||||
await searchInput.fill('');
|
||||
await expect(page.getByText(matchingProjectName)).toBeVisible();
|
||||
await expect(page.getByText(otherProjectName)).toBeVisible();
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
createTimeEntryWithTagViaApi,
|
||||
createTimeEntryWithBillableStatusViaApi,
|
||||
createBareTimeEntryViaApi,
|
||||
createTimeEntryOnDateViaApi,
|
||||
createPublicProjectViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
@@ -841,6 +842,127 @@ test('test that setting group by to current sub group triggers sub group fallbac
|
||||
await expect(groupBySelects.filter({ hasText: 'Members' }).first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that group by date groups the report by day and formats the date labels with organization settings', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { date_format: 'point-separated-d-m-yyyy' });
|
||||
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
description: 'Entry for group by date',
|
||||
duration: '1h',
|
||||
});
|
||||
|
||||
// Go to reporting page
|
||||
await goToReporting(page);
|
||||
await expect(page.getByRole('button', { name: 'Export' })).toBeVisible();
|
||||
|
||||
// Find the "Group by" selects within the reporting table
|
||||
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
|
||||
|
||||
// Default state: group=Project
|
||||
await groupBySelects.filter({ hasText: 'Project' }).first().click();
|
||||
|
||||
const [aggregateResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/aggregate') &&
|
||||
response.url().includes('group=day') &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('option', { name: 'Date', exact: true }).click(),
|
||||
]);
|
||||
|
||||
// Verify the API request contains the correct group parameter
|
||||
const requestUrl = new URL(aggregateResponse.url());
|
||||
expect(requestUrl.searchParams.get('group')).toBe('day');
|
||||
|
||||
// The row label is rendered in the organization date format (D.M.YYYY)
|
||||
await expect(
|
||||
page.getByTestId('reporting_view').getByText(/^\d{1,2}\.\d{1,2}\.\d{4}$/)
|
||||
).toBeVisible();
|
||||
await expect(page.getByTestId('reporting_view').getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(
|
||||
0
|
||||
);
|
||||
});
|
||||
|
||||
test('test that group by week requests week grouping and does not leak the raw group key', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
description: 'Entry for group by week',
|
||||
duration: '1h',
|
||||
});
|
||||
|
||||
await goToReporting(page);
|
||||
await expect(page.getByRole('button', { name: 'Export' })).toBeVisible();
|
||||
|
||||
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
|
||||
await groupBySelects.filter({ hasText: 'Project' }).first().click();
|
||||
|
||||
const [aggregateResponse] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/aggregate') &&
|
||||
response.url().includes('group=week') &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('option', { name: 'Week', exact: true }).click(),
|
||||
]);
|
||||
|
||||
const requestUrl = new URL(aggregateResponse.url());
|
||||
expect(requestUrl.searchParams.get('group')).toBe('week');
|
||||
|
||||
// The raw group key is the first day of the week and must not leak through.
|
||||
await expect(page.getByTestId('reporting_view').getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(
|
||||
0
|
||||
);
|
||||
});
|
||||
|
||||
test('test that group by week labels a week spanning new year with a range crossing the year', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { date_format: 'slash-separated-dd-mm-yyyy' });
|
||||
|
||||
for (const day of ['2025-12-22', '2025-12-29', '2026-01-05']) {
|
||||
await createTimeEntryOnDateViaApi(ctx, {
|
||||
date: new Date(`${day}T09:00:00Z`),
|
||||
duration: '1h',
|
||||
description: `Entry for ${day}`,
|
||||
});
|
||||
}
|
||||
|
||||
// The reporting page keeps its range in session storage, so seed a range spanning new year
|
||||
// rather than driving the date picker.
|
||||
await page.addInitScript(() => {
|
||||
window.sessionStorage.setItem('reporting-start-date', '2025-12-15');
|
||||
window.sessionStorage.setItem('reporting-end-date', '2026-01-15');
|
||||
});
|
||||
|
||||
await goToReporting(page);
|
||||
await expect(page.getByRole('button', { name: 'Export' })).toBeVisible();
|
||||
|
||||
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
|
||||
await groupBySelects.filter({ hasText: 'Project' }).first().click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/aggregate') &&
|
||||
response.url().includes('group=week') &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('option', { name: 'Week', exact: true }).click(),
|
||||
]);
|
||||
|
||||
const reportingView = page.getByTestId('reporting_view');
|
||||
await expect(reportingView.getByText('22/12/2025 - 28/12/2025', { exact: true })).toBeVisible();
|
||||
await expect(reportingView.getByText('29/12/2025 - 04/01/2026', { exact: true })).toBeVisible();
|
||||
await expect(reportingView.getByText('05/01/2026 - 11/01/2026', { exact: true })).toBeVisible();
|
||||
await expect(reportingView.getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(0);
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────
|
||||
// Export Tests
|
||||
// ──────────────────────────────────────────────────
|
||||
@@ -1019,3 +1141,24 @@ test.describe('Employee Reporting Restrictions', () => {
|
||||
await expect(employee.page.getByText('100,00 EUR').first()).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
test('test that reporting has a type filter that can show only breaks', async ({ page, ctx }) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
await createTimeEntryViaApi(ctx, { duration: '1h', description: 'Regular work entry' });
|
||||
await createTimeEntryViaApi(ctx, { duration: '20min', type: 'break' });
|
||||
|
||||
await goToReporting(page);
|
||||
// The type filter defaults to "Work time"; switching it to "Breaks" re-aggregates.
|
||||
const typeFilter = page.getByRole('combobox').filter({ hasText: 'Work time' });
|
||||
await expect(typeFilter).toBeVisible();
|
||||
await typeFilter.click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/aggregate') &&
|
||||
response.url().includes('type=break') &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('option', { name: 'Breaks' }).click(),
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
createTimeEntryWithBillableStatusViaApi,
|
||||
createTagViaApi,
|
||||
createReportViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
import {
|
||||
goToReporting,
|
||||
@@ -68,6 +69,42 @@ test('test that saving a report creates a shared report and its shareable link s
|
||||
await expect(page.getByText('Total')).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that a shared report grouped by date shows date labels formatted by the organization setting', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
const reportName = 'DateGroupReport ' + Math.floor(Math.random() * 10000);
|
||||
|
||||
await updateOrganizationSettingViaApi(ctx, { date_format: 'point-separated-d-m-yyyy' });
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
description: 'Entry for date grouping',
|
||||
duration: '1h',
|
||||
});
|
||||
|
||||
await goToReporting(page);
|
||||
|
||||
// Switch the grouping to "Date"
|
||||
const groupBySelects = page.locator('[data-testid="reporting_view"]').getByRole('combobox');
|
||||
await groupBySelects.filter({ hasText: 'Project' }).first().click();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/time-entries/aggregate') &&
|
||||
response.url().includes('group=day') &&
|
||||
response.status() === 200
|
||||
),
|
||||
page.getByRole('option', { name: 'Date', exact: true }).click(),
|
||||
]);
|
||||
|
||||
const { shareableLink } = await saveAsSharedReport(page, reportName);
|
||||
|
||||
// Verify row labels are formatted correctly
|
||||
await page.goto(shareableLink);
|
||||
await expect(page.getByText('Total')).toBeVisible();
|
||||
await expect(page.getByText(/^\d{1,2}\.\d{1,2}\.\d{4}$/)).toBeVisible();
|
||||
await expect(page.getByText(/^\d{4}-\d{2}-\d{2}$/)).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('test that shared report with invalid secret shows no data', async ({ page }) => {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/shared-report#invalid-secret-value');
|
||||
await expect(page.getByText('No time entries found').first()).toBeVisible();
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Page } from '@playwright/test';
|
||||
import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { test } from '../playwright/fixtures';
|
||||
import { createTagViaApi } from './utils/api';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
import { clearTableState, getTableRowNames } from './utils/table';
|
||||
|
||||
async function goToTagsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/tags');
|
||||
@@ -147,18 +147,12 @@ test('test that tag context menu delete deletes the tag', async ({ page, ctx })
|
||||
// Sorting Tests
|
||||
// =============================================
|
||||
|
||||
async function clearTagTableState(page: Page) {
|
||||
await page.evaluate(() => {
|
||||
localStorage.removeItem('tag-table-state');
|
||||
});
|
||||
}
|
||||
|
||||
test('test that sorting tags by name works', async ({ page, ctx }) => {
|
||||
await createTagViaApi(ctx, { name: 'AAA SortTag' });
|
||||
await createTagViaApi(ctx, { name: 'ZZZ SortTag' });
|
||||
|
||||
await goToTagsOverview(page);
|
||||
await clearTagTableState(page);
|
||||
await clearTableState(page, 'tag-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('tag_table');
|
||||
@@ -176,7 +170,7 @@ test('test that sorting tags by name works', async ({ page, ctx }) => {
|
||||
|
||||
test('test that tag sort state persists after page reload', async ({ page }) => {
|
||||
await goToTagsOverview(page);
|
||||
await clearTagTableState(page);
|
||||
await clearTableState(page, 'tag-table-state');
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('tag_table');
|
||||
|
||||
@@ -7,13 +7,56 @@ import {
|
||||
createPublicProjectViaApi,
|
||||
createTaskViaApi,
|
||||
createClientViaApi,
|
||||
createTimeEntryViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
type TestContext,
|
||||
} from './utils/api';
|
||||
import { clearTableState, getTableRowNames } from './utils/table';
|
||||
|
||||
async function goToProjectsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/projects');
|
||||
}
|
||||
|
||||
async function createSortableTasks(ctx: TestContext) {
|
||||
const project = await createProjectViaApi(ctx, { name: 'Task Sorting Project' });
|
||||
const taskA = await createTaskViaApi(ctx, {
|
||||
name: 'AAA Sorting Task',
|
||||
project_id: project.id,
|
||||
estimated_time: 36000,
|
||||
});
|
||||
const taskB = await createTaskViaApi(ctx, {
|
||||
name: 'BBB Sorting Task',
|
||||
project_id: project.id,
|
||||
estimated_time: 14400,
|
||||
});
|
||||
const taskC = await createTaskViaApi(ctx, {
|
||||
name: 'CCC Sorting Task',
|
||||
project_id: project.id,
|
||||
});
|
||||
|
||||
expect(taskA.estimated_time).toBe(36000);
|
||||
expect(taskB.estimated_time).toBe(14400);
|
||||
expect(taskC.estimated_time).toBeNull();
|
||||
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
duration: '1h',
|
||||
projectId: project.id,
|
||||
taskId: taskA.id,
|
||||
});
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
duration: '2h',
|
||||
projectId: project.id,
|
||||
taskId: taskB.id,
|
||||
});
|
||||
await createTimeEntryViaApi(ctx, {
|
||||
duration: '3h',
|
||||
projectId: project.id,
|
||||
taskId: taskC.id,
|
||||
});
|
||||
|
||||
return { project, taskA, taskB, taskC };
|
||||
}
|
||||
|
||||
test('test that creating and deleting a new task in a new project works', async ({ page }) => {
|
||||
const newProjectName = 'New Project ' + Math.floor(1 + Math.random() * 10000);
|
||||
await goToProjectsOverview(page);
|
||||
@@ -301,6 +344,59 @@ test('test that creating a new project from the task create modal project dropdo
|
||||
await expect(page.getByTestId('task_table')).toContainText(newTaskName);
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Sorting Tests
|
||||
// =============================================
|
||||
|
||||
test('test that sorting tasks by name, total time and progress works', async ({ page, ctx }) => {
|
||||
const { project, taskA, taskB, taskC } = await createSortableTasks(ctx);
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'task-table-state');
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/projects/' + project.id);
|
||||
const table = page.getByTestId('task_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// This project contains only the seeded tasks, so assert the complete order.
|
||||
const expectOrder = async (expected: string[]) => {
|
||||
await expect.poll(() => getTableRowNames(table)).toEqual(expected);
|
||||
};
|
||||
const clickHeader = async (headerText: string) => {
|
||||
await table.getByText(headerText).first().click();
|
||||
};
|
||||
|
||||
await expectOrder([taskA.name, taskB.name, taskC.name]);
|
||||
await clickHeader('Task Name');
|
||||
await expectOrder([taskC.name, taskB.name, taskA.name]);
|
||||
await clickHeader('Task Name');
|
||||
await expectOrder([taskA.name, taskB.name, taskC.name]);
|
||||
|
||||
await clickHeader('Total Time');
|
||||
await expectOrder([taskC.name, taskB.name, taskA.name]);
|
||||
await clickHeader('Total Time');
|
||||
await expectOrder([taskA.name, taskB.name, taskC.name]);
|
||||
|
||||
await clickHeader('Progress');
|
||||
await expectOrder([taskB.name, taskA.name, taskC.name]);
|
||||
await clickHeader('Progress');
|
||||
await expectOrder([taskA.name, taskB.name, taskC.name]);
|
||||
});
|
||||
|
||||
test('test that task sort state persists after page reload', async ({ page, ctx }) => {
|
||||
const { project, taskA, taskB, taskC } = await createSortableTasks(ctx);
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'task-table-state');
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/projects/' + project.id);
|
||||
const table = page.getByTestId('task_table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
await table.getByText('Progress').first().click();
|
||||
await expect.poll(() => getTableRowNames(table)).toEqual([taskB.name, taskA.name, taskC.name]);
|
||||
await page.reload();
|
||||
|
||||
// Verify the persisted row order, not just the sort indicator.
|
||||
await expect.poll(() => getTableRowNames(table)).toEqual([taskB.name, taskA.name, taskC.name]);
|
||||
});
|
||||
|
||||
// =============================================
|
||||
// Employee Permission Tests
|
||||
// =============================================
|
||||
|
||||
@@ -50,7 +50,7 @@ async function goToTimeOverview(page: Page) {
|
||||
async function goToOrganizationSettings(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/dashboard');
|
||||
await page.locator('[data-testid="organization_switcher"]:visible').click();
|
||||
await page.getByText('Organization Settings').click();
|
||||
await page.getByRole('menuitem', { name: 'Organization Settings' }).click();
|
||||
}
|
||||
|
||||
async function createEmptyTimeEntry(page: Page) {
|
||||
@@ -2303,3 +2303,21 @@ test('test that aggregate row context menu delete removes all grouped entries',
|
||||
page.locator('[data-testid="time_entry_row"]').filter({ hasText: description })
|
||||
).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('test that break entries show a break badge and split day total on the time page', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
await createTimeEntryViaApi(ctx, { duration: '2h', description: 'Some work' });
|
||||
await createTimeEntryViaApi(ctx, { duration: '30min', type: 'break', description: '' });
|
||||
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/time');
|
||||
await expect(page.getByTestId('break_badge').first()).toBeVisible();
|
||||
await expect(page.getByTestId('break_badge').first()).toContainText('Break');
|
||||
// Day heading shows worked time first, then the break portion
|
||||
await expect(page.getByTestId('day_break_duration').first()).toBeVisible();
|
||||
await expect(page.getByTestId('day_break_duration').first().locator('..')).toContainText(
|
||||
'2h 00min work · 0h 30min break'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2,7 +2,15 @@ import { PLAYWRIGHT_BASE_URL } from '../playwright/config';
|
||||
import { test } from '../playwright/fixtures';
|
||||
import { expect } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { createProjectViaApi, createTaskViaApi, createTimeEntryOnDateViaApi } from './utils/api';
|
||||
import {
|
||||
createProjectViaApi,
|
||||
createTaskViaApi,
|
||||
createTimeEntryOnDateViaApi,
|
||||
createTimeEntryWithTimestampsViaApi,
|
||||
getTimeEntriesViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
type TestContext,
|
||||
} from './utils/api';
|
||||
|
||||
// ──────────────────────────────────────────────────
|
||||
// Helpers
|
||||
@@ -58,6 +66,34 @@ function addRowButton(page: Page) {
|
||||
return page.getByRole('button', { name: /Add row/i }).first();
|
||||
}
|
||||
|
||||
async function fillBreakCell(page: Page, hours: string, dayIndex = 0) {
|
||||
const input = page
|
||||
.locator('[data-testid="timesheet_row"]')
|
||||
.filter({ has: page.getByText('Break', { exact: true }) })
|
||||
.locator('[data-testid="timesheet_cell"]')
|
||||
.nth(dayIndex)
|
||||
.locator('input');
|
||||
await input.click();
|
||||
await input.fill(hours);
|
||||
return input;
|
||||
}
|
||||
|
||||
function waitForBreakCreated(page: Page) {
|
||||
return page.waitForResponse(
|
||||
async (resp) =>
|
||||
resp.url().includes('/time-entries') &&
|
||||
resp.request().method() === 'POST' &&
|
||||
resp.status() === 201 &&
|
||||
(await resp.json()).data.type === 'break'
|
||||
);
|
||||
}
|
||||
|
||||
async function getDayEntriesViaApi(ctx: TestContext, day: string) {
|
||||
return (await getTimeEntriesViaApi(ctx))
|
||||
.filter((e) => e.start.startsWith(day))
|
||||
.sort((a, b) => a.start.localeCompare(b.start));
|
||||
}
|
||||
|
||||
async function chooseRowIdentity(page: Page, optionName: string) {
|
||||
await addRowButton(page).click();
|
||||
|
||||
@@ -639,3 +675,252 @@ test('cell accepts various duration input formats', async ({ page, ctx }) => {
|
||||
// 1.5 hours = 1h 30min
|
||||
await expect(mondayInput).toHaveValue('1h 30min');
|
||||
});
|
||||
|
||||
test('test that adding a timesheet break to a full day splits the work entry via the placement modal', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// A single work entry filling the day leaves no gap for a break, so the placement
|
||||
// modal must offer to split it (the only entry) and drop the break in the middle.
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T09:00:00Z`,
|
||||
end: `${day}T17:00:00Z`,
|
||||
description: 'Split me',
|
||||
});
|
||||
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
|
||||
// The break row is always present — enter a 30m break on Monday
|
||||
const breakCell = await fillBreakCell(page, '0.5');
|
||||
await breakCell.press('Enter');
|
||||
|
||||
// The placement modal opens with the split preview, naming the entry that
|
||||
// will be split so the user can recognize it.
|
||||
await expect(page.getByTestId('break_placement_summary')).toBeVisible();
|
||||
await expect(page.getByTestId('break_placement_summary')).toContainText(
|
||||
'No Project · Split me'
|
||||
);
|
||||
await Promise.all([
|
||||
waitForBreakCreated(page),
|
||||
page.getByRole('button', { name: 'Add break' }).click(),
|
||||
]);
|
||||
|
||||
// The break is inserted without reducing the eight hours of work.
|
||||
const dayEntries = await getDayEntriesViaApi(ctx, day);
|
||||
expect(dayEntries.map((e) => [e.type, e.start, e.end])).toEqual([
|
||||
['work', `${day}T09:00:00Z`, `${day}T13:00:00Z`],
|
||||
['break', `${day}T13:00:00Z`, `${day}T13:30:00Z`],
|
||||
['work', `${day}T13:30:00Z`, `${day}T17:30:00Z`],
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that adding a break into an oversized gap places it without moving other entries', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// 09-12 and 15-17 leave a 3h gap — wider than the placement tolerance allows,
|
||||
// but easily big enough to hold the break. Such a gap is deliberate (the app
|
||||
// itself never creates one), so the break goes flush after the morning entry
|
||||
// and nothing else moves — no placement modal.
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T09:00:00Z`,
|
||||
end: `${day}T12:00:00Z`,
|
||||
description: 'Morning',
|
||||
});
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T15:00:00Z`,
|
||||
end: `${day}T17:00:00Z`,
|
||||
description: 'Afternoon',
|
||||
});
|
||||
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
|
||||
const breakCell = await fillBreakCell(page, '0.5');
|
||||
await Promise.all([waitForBreakCreated(page), breakCell.press('Enter')]);
|
||||
|
||||
await expect(page.getByTestId('break_placement_summary')).not.toBeVisible();
|
||||
const dayEntries = await getDayEntriesViaApi(ctx, day);
|
||||
expect(dayEntries.map((e) => [e.type, e.start, e.end])).toEqual([
|
||||
['work', `${day}T09:00:00Z`, `${day}T12:00:00Z`],
|
||||
['break', `${day}T12:00:00Z`, `${day}T12:30:00Z`],
|
||||
['work', `${day}T15:00:00Z`, `${day}T17:00:00Z`],
|
||||
]);
|
||||
});
|
||||
|
||||
test('test that the placement modal warns when the chosen time would leave the break misaligned', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Back-to-back 09-12 and 12-17 leave no gap, so the placement modal opens.
|
||||
// The suggested slot (flush at 12:00) is aligned — no warning. Moving the
|
||||
// break to 07:00, before any work, keeps the plan feasible but the result
|
||||
// would immediately carry the misaligned hint, so the modal warns upfront.
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T09:00:00Z`,
|
||||
end: `${day}T12:00:00Z`,
|
||||
description: 'Morning',
|
||||
});
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T12:00:00Z`,
|
||||
end: `${day}T17:00:00Z`,
|
||||
description: 'Afternoon',
|
||||
});
|
||||
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
|
||||
const breakCell = await fillBreakCell(page, '0.5');
|
||||
await breakCell.press('Enter');
|
||||
|
||||
// Default suggestion sits flush between work → no warning
|
||||
await expect(page.getByTestId('break_placement_summary')).toBeVisible();
|
||||
await expect(page.getByTestId('break_placement_misaligned_warning')).not.toBeVisible();
|
||||
|
||||
// Move the break to 07:00-07:30, before all work
|
||||
const modal = page.getByRole('dialog');
|
||||
const startTimeInput = modal.getByTestId('time_picker_input').first();
|
||||
await startTimeInput.fill('07:00');
|
||||
await startTimeInput.press('Tab');
|
||||
const endTimeInput = modal.getByTestId('time_picker_input').nth(1);
|
||||
await endTimeInput.fill('07:30');
|
||||
await endTimeInput.press('Tab');
|
||||
|
||||
// Feasible (nothing has to move), but flagged as misaligned beforehand
|
||||
await expect(page.getByTestId('break_placement_misaligned_warning')).toBeVisible();
|
||||
await expect(page.getByTestId('break_placement_summary')).toContainText(
|
||||
'No entries need to move.'
|
||||
);
|
||||
|
||||
// The warning is non-blocking: the break can still be added as chosen
|
||||
await Promise.all([
|
||||
waitForBreakCreated(page),
|
||||
page.getByRole('button', { name: 'Add break' }).click(),
|
||||
]);
|
||||
|
||||
const dayEntries = await getDayEntriesViaApi(ctx, day);
|
||||
expect(dayEntries.map((e) => [e.type, e.start, e.end])).toEqual([
|
||||
['break', `${day}T07:00:00Z`, `${day}T07:30:00Z`],
|
||||
['work', `${day}T09:00:00Z`, `${day}T12:00:00Z`],
|
||||
['work', `${day}T12:00:00Z`, `${day}T17:00:00Z`],
|
||||
]);
|
||||
// ...and the timesheet now shows the misaligned-break hint for that day
|
||||
const hint = page.getByRole('button', {
|
||||
name: 'does not align with your work entries',
|
||||
});
|
||||
await expect(hint).toBeVisible();
|
||||
|
||||
// The resulting warning links to the calendar on the affected date.
|
||||
await hint.click();
|
||||
await expect(page.getByRole('link', { name: 'Fix in calendar' })).toHaveAttribute(
|
||||
'href',
|
||||
`/calendar?date=${day}`
|
||||
);
|
||||
});
|
||||
|
||||
test('test that editing a timesheet break re-places it as one entry instead of fragmenting it', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Two work entries with a 1h gap, and a 30m break created directly inside it (12:15–12:45).
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T09:00:00Z`,
|
||||
end: `${day}T12:00:00Z`,
|
||||
description: 'Work',
|
||||
});
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T13:00:00Z`,
|
||||
end: `${day}T17:00:00Z`,
|
||||
description: 'Work',
|
||||
});
|
||||
const breakEntry = await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T12:15:00Z`,
|
||||
end: `${day}T12:45:00Z`,
|
||||
type: 'break',
|
||||
});
|
||||
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
const breakCell = await fillBreakCell(page, '0.75');
|
||||
await Promise.all([
|
||||
// A break that still fits its gap is re-placed in place (PUT on the same entry),
|
||||
// not deleted and recreated — that's what keeps it a single entry.
|
||||
page.waitForResponse(
|
||||
async (resp) =>
|
||||
resp.url().includes(`/time-entries/${breakEntry.id}`) &&
|
||||
resp.request().method() === 'PUT' &&
|
||||
resp.status() === 200 &&
|
||||
(await resp.json()).data.type === 'break'
|
||||
),
|
||||
breakCell.press('Enter'),
|
||||
]);
|
||||
|
||||
// Still exactly one break on the day (not fragmented). It stays anchored at its current
|
||||
// start (12:15) rather than re-centering, growing its end to 13:00 to reach 45 minutes.
|
||||
const breaks = (await getDayEntriesViaApi(ctx, day)).filter((e) => e.type === 'break');
|
||||
expect(breaks).toHaveLength(1);
|
||||
expect(breaks[0].duration).toBe(2700);
|
||||
expect(breaks[0].start).toBe(`${day}T12:15:00Z`);
|
||||
expect(breaks[0].end).toBe(`${day}T13:00:00Z`);
|
||||
});
|
||||
|
||||
test('test that editing an adjacent break vacates its old slot before extending work', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// The existing break must move before work can extend through its old slot.
|
||||
await updateOrganizationSettingViaApi(ctx, {
|
||||
breaks_enabled: true,
|
||||
prevent_overlapping_time_entries: true,
|
||||
});
|
||||
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T09:00:00Z`,
|
||||
end: `${day}T17:00:00Z`,
|
||||
description: 'Work before break',
|
||||
});
|
||||
const breakEntry = await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T17:00:00Z`,
|
||||
end: `${day}T17:30:00Z`,
|
||||
type: 'break',
|
||||
});
|
||||
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
const breakCell = await fillBreakCell(page, '1');
|
||||
await breakCell.press('Enter');
|
||||
|
||||
await expect(page.getByTestId('break_placement_summary')).toBeVisible();
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
(resp) =>
|
||||
resp.url().includes(`/time-entries/${breakEntry.id}`) &&
|
||||
resp.request().method() === 'PUT' &&
|
||||
resp.status() === 200
|
||||
),
|
||||
page.waitForResponse(
|
||||
async (resp) =>
|
||||
resp.url().includes('/time-entries') &&
|
||||
resp.request().method() === 'POST' &&
|
||||
resp.status() === 201 &&
|
||||
(await resp.json()).data.type === 'work'
|
||||
),
|
||||
page.getByRole('button', { name: 'Add break' }).click(),
|
||||
]);
|
||||
|
||||
const entries = await getDayEntriesViaApi(ctx, day);
|
||||
expect(entries.map((entry) => [entry.id, entry.type, entry.start, entry.end])).toEqual([
|
||||
[expect.any(String), 'work', `${day}T09:00:00Z`, `${day}T13:00:00Z`],
|
||||
[breakEntry.id, 'break', `${day}T13:00:00Z`, `${day}T14:00:00Z`],
|
||||
[expect.any(String), 'work', `${day}T14:00:00Z`, `${day}T18:00:00Z`],
|
||||
]);
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user