mirror of
https://github.com/solidtime-io/solidtime.git
synced 2026-10-17 10:13:16 +01:00
Compare commits
5 Commits
feature/su
...
f6311eddfd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6311eddfd | ||
|
|
2639b62744 | ||
|
|
8a68673a48 | ||
|
|
34f8eb0970 | ||
|
|
64ca1e9115 |
@@ -1,7 +1,5 @@
|
||||
.git
|
||||
**/.git
|
||||
.gitmodules
|
||||
**/.gitmodules
|
||||
.github
|
||||
.DS_Store
|
||||
.fleet
|
||||
@@ -10,13 +8,6 @@
|
||||
*.log
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
k8s
|
||||
docs
|
||||
e2e
|
||||
tests
|
||||
|
||||
docker-compose.yml
|
||||
docker/local
|
||||
|
||||
.phpunit.cache
|
||||
.phpunit.result.cache
|
||||
@@ -25,18 +16,6 @@ test-results
|
||||
playwright-report
|
||||
blob-report
|
||||
playwright/.cache
|
||||
openapi.json
|
||||
playwright
|
||||
playwright.config.ts
|
||||
vitest.config.ts
|
||||
phpunit.xml
|
||||
phpstan.neon
|
||||
pint.json
|
||||
eslint.config.mjs
|
||||
tsconfig.json
|
||||
jsconfig.json
|
||||
postcss.config.js
|
||||
tailwind.config.js
|
||||
|
||||
node_modules
|
||||
extensions/*/node_modules
|
||||
@@ -51,4 +30,3 @@ _ide_helper.php
|
||||
.phpstorm.meta.php
|
||||
|
||||
storage/logs/*
|
||||
storage/*.key
|
||||
|
||||
27
.github/VOUCHED.td
vendored
27
.github/VOUCHED.td
vendored
@@ -1,27 +0,0 @@
|
||||
# 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
|
||||
1
.github/workflows/build-onpremise.yml
vendored
1
.github/workflows/build-onpremise.yml
vendored
@@ -8,7 +8,6 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/build-onpremise.yml'
|
||||
- '.dockerignore'
|
||||
- 'extensions/manifest.json'
|
||||
- 'docker/prod/**'
|
||||
workflow_dispatch:
|
||||
|
||||
1
.github/workflows/build-private.yml
vendored
1
.github/workflows/build-private.yml
vendored
@@ -8,7 +8,6 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/build-private.yml'
|
||||
- '.dockerignore'
|
||||
- 'extensions/manifest.json'
|
||||
- 'docker/prod/**'
|
||||
workflow_dispatch:
|
||||
|
||||
1
.github/workflows/build-public.yml
vendored
1
.github/workflows/build-public.yml
vendored
@@ -8,7 +8,6 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/build-public.yml'
|
||||
- '.dockerignore'
|
||||
- 'docker/prod/**'
|
||||
workflow_dispatch:
|
||||
|
||||
|
||||
75
.github/workflows/vouch-check-pr.yml
vendored
75
.github/workflows/vouch-check-pr.yml
vendored
@@ -1,75 +0,0 @@
|
||||
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
33
.github/workflows/vouch-manage-by-discussion.yml
vendored
@@ -1,33 +0,0 @@
|
||||
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
35
.github/workflows/vouch-manage-by-issue.yml
vendored
@@ -1,35 +0,0 @@
|
||||
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,22 +12,6 @@ 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,8 +39,6 @@ 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.
|
||||
|
||||
@@ -60,6 +60,7 @@ abstract class ApiException extends Exception
|
||||
*/
|
||||
public function report(): bool
|
||||
{
|
||||
// TODO: temporary activated
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ 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,16 +19,6 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ namespace App\Exceptions\Api;
|
||||
class OnlyOwnerCanChangeOwnership extends ApiException
|
||||
{
|
||||
public const string KEY = 'only_owner_can_change_ownership';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ namespace App\Exceptions\Api;
|
||||
class OverlappingTimeEntryApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'overlapping_time_entry';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,4 @@ 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,9 +7,4 @@ 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,14 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ 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,9 +7,4 @@ namespace App\Exceptions\Api;
|
||||
class UserNotPlaceholderApiException extends ApiException
|
||||
{
|
||||
public const string KEY = 'user_not_placeholder';
|
||||
|
||||
public function report(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,9 +7,4 @@ 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,11 +6,7 @@ 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
|
||||
@@ -34,33 +30,6 @@ 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,9 +28,7 @@ class ExportController extends Controller
|
||||
|
||||
$filepath = $exportService->export($organization);
|
||||
$downloadUrl = Storage::disk(config('filesystems.private'))
|
||||
->temporaryUrl($filepath, Carbon::now()->addMinutes(10), [
|
||||
'ResponseContentDisposition' => 'attachment; filename="'.basename($filepath).'"',
|
||||
]);
|
||||
->temporaryUrl($filepath, Carbon::now()->addMinutes(10));
|
||||
|
||||
return new JsonResponse([
|
||||
'success' => true,
|
||||
|
||||
@@ -68,7 +68,7 @@ class TimeEntryController extends Controller
|
||||
|
||||
$query = TimeEntry::query()
|
||||
->where('organization_id', $organization->getKey())
|
||||
->where('member_id', $member->getKey())
|
||||
->where('user_id', $member->user_id)
|
||||
->when($exclude !== null, function (Builder $q) use ($exclude): void {
|
||||
$q->where('id', '!=', $exclude->getKey());
|
||||
})
|
||||
@@ -108,8 +108,8 @@ class TimeEntryController extends Controller
|
||||
/**
|
||||
* Get time entries in organization
|
||||
*
|
||||
* If you only need time entries for a specific user, you can filter by `member_id`.
|
||||
* Users with the permission `time-entries:view:own` can only use this endpoint with their own member ID in the member_id filter.
|
||||
* If you only need time entries for a specific user, you can filter by `user_id`.
|
||||
* Users with the permission `time-entries:view:own` can only use this endpoint with their own user ID in the user_id filter.
|
||||
*
|
||||
* @return TimeEntryCollection<TimeEntryResource>
|
||||
*
|
||||
@@ -119,17 +119,16 @@ class TimeEntryController extends Controller
|
||||
*/
|
||||
public function index(Organization $organization, TimeEntryIndexRequest $request): JsonResource
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $memberFilter */
|
||||
$memberFilter = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($memberFilter !== null && $memberFilter->getKey() === $member->getKey()) {
|
||||
/** @var Member|null $member */
|
||||
$member = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($member !== null && $member->user_id === Auth::id()) {
|
||||
$this->checkPermission($organization, 'time-entries:view:own');
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
}
|
||||
|
||||
$canAccessPremiumFeatures = $this->canAccessPremiumFeatures($organization);
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $memberFilter, $canAccessPremiumFeatures);
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $member, $canAccessPremiumFeatures);
|
||||
|
||||
$totalCount = $timeEntriesQuery->count();
|
||||
|
||||
@@ -160,7 +159,7 @@ class TimeEntryController extends Controller
|
||||
if ($timeEntries->count() === 0) {
|
||||
Log::warning('User has has more than '.$limit.' time entries on one date', [
|
||||
'date' => $lastDate->toDateString(),
|
||||
'member_id' => $request->input('member_id'),
|
||||
'user_id' => $request->input('user_id'),
|
||||
'auth_user_id' => Auth::id(),
|
||||
'limit' => $limit,
|
||||
]);
|
||||
@@ -224,10 +223,9 @@ class TimeEntryController extends Controller
|
||||
*/
|
||||
public function indexExport(Organization $organization, TimeEntryIndexExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService): JsonResponse
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $memberFilter */
|
||||
$memberFilter = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($memberFilter !== null && $memberFilter->getKey() === $member->getKey()) {
|
||||
/** @var Member|null $member */
|
||||
$member = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($member !== null && $member->user_id === Auth::id()) {
|
||||
$this->checkPermission($organization, 'time-entries:view:own');
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
@@ -244,7 +242,7 @@ class TimeEntryController extends Controller
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $memberFilter, $canAccessPremiumFeatures);
|
||||
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $member, $canAccessPremiumFeatures);
|
||||
$timeEntriesQuery->with([
|
||||
'task',
|
||||
'client',
|
||||
@@ -267,7 +265,7 @@ class TimeEntryController extends Controller
|
||||
if ($viewFile === false) {
|
||||
throw new \LogicException('View file not found');
|
||||
}
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $memberFilter);
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
|
||||
$aggregatedData = $timeEntryAggregationService->getAggregatedTimeEntries(
|
||||
$timeEntriesAggregateQuery,
|
||||
null,
|
||||
@@ -336,9 +334,7 @@ class TimeEntryController extends Controller
|
||||
|
||||
return response()->json([
|
||||
'download_url' => Storage::disk(config('filesystems.private'))
|
||||
->temporaryUrl($path, now()->addMinutes(5), [
|
||||
'ResponseContentDisposition' => 'attachment; filename="'.$filename.'"',
|
||||
]),
|
||||
->temporaryUrl($path, now()->addMinutes(5)),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -376,10 +372,9 @@ class TimeEntryController extends Controller
|
||||
*/
|
||||
public function aggregate(Organization $organization, TimeEntryAggregateRequest $request, TimeEntryAggregationService $timeEntryAggregationService): array
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $memberFilter */
|
||||
$memberFilter = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($memberFilter !== null && $memberFilter->getKey() === $member->getKey()) {
|
||||
/** @var Member|null $member */
|
||||
$member = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($member !== null && $member->user_id === Auth::id()) {
|
||||
$this->checkPermission($organization, 'time-entries:view:own');
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
@@ -390,7 +385,7 @@ class TimeEntryController extends Controller
|
||||
|
||||
$group1Type = $request->getGroup();
|
||||
$group2Type = $request->getSubGroup();
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $memberFilter);
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
|
||||
@@ -426,10 +421,9 @@ class TimeEntryController extends Controller
|
||||
*/
|
||||
public function aggregateExport(Organization $organization, TimeEntryAggregateExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService): JsonResponse
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $memberFilter */
|
||||
$memberFilter = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($memberFilter !== null && $memberFilter->getKey() === $member->getKey()) {
|
||||
/** @var Member|null $member */
|
||||
$member = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($member !== null && $member->user_id === Auth::id()) {
|
||||
$this->checkPermission($organization, 'time-entries:view:own');
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:view:all');
|
||||
@@ -445,7 +439,7 @@ class TimeEntryController extends Controller
|
||||
|
||||
$group = $request->getGroup();
|
||||
$subGroup = $request->getSubGroup();
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $memberFilter);
|
||||
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
|
||||
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
|
||||
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
|
||||
|
||||
@@ -537,7 +531,7 @@ class TimeEntryController extends Controller
|
||||
->putFileAs($folderPath, new File($tempFolder->path($filenameTemp)), $filename);
|
||||
} else {
|
||||
Excel::store(
|
||||
new TimeEntriesReportExport($aggregatedData, $format, $currency, $group, $subGroup, $showBillableRate, $localizationService),
|
||||
new TimeEntriesReportExport($aggregatedData, $format, $currency, $group, $subGroup, $showBillableRate),
|
||||
$path,
|
||||
config('filesystems.private'),
|
||||
$format->getExportPackageType(),
|
||||
@@ -549,9 +543,7 @@ class TimeEntryController extends Controller
|
||||
|
||||
return response()->json([
|
||||
'download_url' => Storage::disk(config('filesystems.private'))
|
||||
->temporaryUrl($path, now()->addMinutes(5), [
|
||||
'ResponseContentDisposition' => 'attachment; filename="'.$filename.'"',
|
||||
]),
|
||||
->temporaryUrl($path, now()->addMinutes(5)),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -591,7 +583,7 @@ class TimeEntryController extends Controller
|
||||
{
|
||||
/** @var Member $member */
|
||||
$member = Member::query()->findOrFail($request->input('member_id'));
|
||||
if ($member->getKey() === $this->member($organization)->getKey()) {
|
||||
if ($member->user_id === Auth::id()) {
|
||||
$this->checkPermission($organization, 'time-entries:create:own');
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:create:all');
|
||||
@@ -638,10 +630,9 @@ class TimeEntryController extends Controller
|
||||
*/
|
||||
public function update(Organization $organization, TimeEntry $timeEntry, TimeEntryUpdateRequest $request): JsonResource
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
/** @var Member|null $newMember */
|
||||
$newMember = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($timeEntry->member_id === $member->getKey() && ($newMember === null || $newMember->getKey() === $member->getKey())) {
|
||||
/** @var Member|null $member */
|
||||
$member = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : null;
|
||||
if ($timeEntry->member->user_id === Auth::id() && ($member === null || $member->user_id === Auth::id())) {
|
||||
$this->checkPermission($organization, 'time-entries:update:own', $timeEntry);
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:update:all', $timeEntry);
|
||||
@@ -673,10 +664,6 @@ class TimeEntryController extends Controller
|
||||
}
|
||||
|
||||
$timeEntry->fill($request->validated());
|
||||
if ($newMember !== null) {
|
||||
$timeEntry->member()->associate($newMember);
|
||||
$timeEntry->user()->associate($newMember->user);
|
||||
}
|
||||
$timeEntry->description = $request->input('description', $timeEntry->description) ?? '';
|
||||
$timeEntry->setComputedAttributeValue('billable_rate');
|
||||
$timeEntry->save();
|
||||
@@ -706,7 +693,6 @@ class TimeEntryController extends Controller
|
||||
*/
|
||||
public function updateMultiple(Organization $organization, TimeEntryUpdateMultipleRequest $request): JsonResponse
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
$this->checkAnyPermission($organization, ['time-entries:update:all', 'time-entries:update:own']);
|
||||
$canAccessAll = $this->hasPermission($organization, 'time-entries:update:all');
|
||||
|
||||
@@ -731,9 +717,6 @@ class TimeEntryController extends Controller
|
||||
throw new AuthorizationException;
|
||||
}
|
||||
|
||||
/** @var Member|null $newMember */
|
||||
$newMember = isset($changes['member_id']) ? Member::query()->findOrFail($changes['member_id']) : null;
|
||||
|
||||
$project = null;
|
||||
$client = null;
|
||||
$overwriteClient = false;
|
||||
@@ -760,7 +743,7 @@ class TimeEntryController extends Controller
|
||||
|
||||
continue;
|
||||
}
|
||||
if (! $canAccessAll && $timeEntry->member_id !== $member->getKey()) {
|
||||
if (! $canAccessAll && $timeEntry->user_id !== Auth::id()) {
|
||||
$error->push($id);
|
||||
|
||||
continue;
|
||||
@@ -783,10 +766,6 @@ class TimeEntryController extends Controller
|
||||
$oldTask = $timeEntry->task;
|
||||
|
||||
$timeEntry->fill($changes);
|
||||
if ($newMember !== null) {
|
||||
$timeEntry->member()->associate($newMember);
|
||||
$timeEntry->user_id = $newMember->user_id;
|
||||
}
|
||||
// If project is changed, but task is not, we remove the old task from the time entry
|
||||
if ($oldProject !== null && $project !== null && $oldProject->isNot($project) && $task === null) {
|
||||
$timeEntry->task()->disassociate();
|
||||
@@ -827,8 +806,7 @@ class TimeEntryController extends Controller
|
||||
*/
|
||||
public function destroy(Organization $organization, TimeEntry $timeEntry): JsonResponse
|
||||
{
|
||||
$member = $this->member($organization);
|
||||
if ($timeEntry->member_id === $member->getKey()) {
|
||||
if ($timeEntry->member->user_id === Auth::id()) {
|
||||
$this->checkPermission($organization, 'time-entries:delete:own', $timeEntry);
|
||||
} else {
|
||||
$this->checkPermission($organization, 'time-entries:delete:all', $timeEntry);
|
||||
@@ -885,7 +863,7 @@ class TimeEntryController extends Controller
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $canDeleteAll && $timeEntry->member_id !== $this->member($organization)->getKey()) {
|
||||
if (! $canDeleteAll && $timeEntry->user_id !== Auth::id()) {
|
||||
$error->push($id);
|
||||
|
||||
continue;
|
||||
|
||||
@@ -15,7 +15,6 @@ 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;
|
||||
@@ -48,7 +47,6 @@ class Kernel extends HttpKernel
|
||||
*/
|
||||
protected $middleware = [
|
||||
ForceHttps::class,
|
||||
TrustHosts::class,
|
||||
TrustProxies::class,
|
||||
HandleCors::class,
|
||||
PreventRequestsDuringMaintenance::class,
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,6 @@ 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;
|
||||
@@ -30,13 +29,8 @@ 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
|
||||
{
|
||||
@@ -104,27 +98,6 @@ 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);
|
||||
|
||||
@@ -33,8 +33,8 @@ class RouteServiceProvider extends ServiceProvider
|
||||
}
|
||||
|
||||
return $request->user()
|
||||
? 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());
|
||||
? Limit::perMinute(200)->by($request->user()->id)
|
||||
: Limit::perMinute(60)->by($request->ip());
|
||||
});
|
||||
|
||||
$this->routes(function (): void {
|
||||
|
||||
@@ -23,10 +23,6 @@ class InvitationService
|
||||
*/
|
||||
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;
|
||||
}
|
||||
@@ -59,7 +55,7 @@ class InvitationService
|
||||
$organizations = new Collection;
|
||||
|
||||
$invitations = OrganizationInvitation::query()
|
||||
->whereRaw('lower(email) = ?', [strtolower($user->email)])
|
||||
->where('email', $user->email)
|
||||
->whereNotNull('accepted_at')
|
||||
->get();
|
||||
|
||||
|
||||
@@ -8,14 +8,12 @@ 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
|
||||
{
|
||||
@@ -154,38 +152,6 @@ 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;
|
||||
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -49,8 +48,6 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
|
||||
|
||||
private bool $showBillableRate;
|
||||
|
||||
private LocalizationService $localization;
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* grouped_type: string|null,
|
||||
@@ -71,7 +68,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, LocalizationService $localization)
|
||||
public function __construct(array $data, ExportFormat $exportFormat, string $currency, TimeEntryAggregationType $group, TimeEntryAggregationType $subGroup, bool $showBillableRate)
|
||||
{
|
||||
$this->data = $data;
|
||||
$this->exportFormat = $exportFormat;
|
||||
@@ -79,7 +76,6 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
|
||||
$this->group = $group;
|
||||
$this->subGroup = $subGroup;
|
||||
$this->showBillableRate = $showBillableRate;
|
||||
$this->localization = $localization;
|
||||
}
|
||||
|
||||
public function view(): View
|
||||
@@ -91,7 +87,6 @@ class TimeEntriesReportExport implements FromView, ShouldAutoSize, WithCustomCsv
|
||||
'subGroup' => $this->subGroup,
|
||||
'exportFormat' => $this->exportFormat,
|
||||
'showBillableRate' => $this->showBillableRate,
|
||||
'localization' => $this->localization,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -75,27 +75,6 @@ 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),
|
||||
@@ -158,21 +137,6 @@ 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
|
||||
|
||||
@@ -1,230 +0,0 @@
|
||||
<?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);
|
||||
}
|
||||
};
|
||||
@@ -189,9 +189,7 @@ ENV WITH_HORIZON=false \
|
||||
WITH_SCHEDULER=false \
|
||||
WITH_REVERB=false
|
||||
|
||||
COPY --link --chown=${WWWUSER}:${WWWUSER} . ./
|
||||
|
||||
RUN test -z "$(find . -name .git -print -quit)"
|
||||
COPY --link --chown=${WWWUSER}:${WWWUSER} . .
|
||||
#COPY --link --chown=${WWWUSER}:${WWWUSER} --from=build ${ROOT}/public public
|
||||
|
||||
RUN mkdir -p \
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
createProjectViaApi,
|
||||
createPublicProjectViaApi,
|
||||
} from './utils/api';
|
||||
import { clearTableState, getTableRowNames } from './utils/table';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
|
||||
async function goToClientsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/clients');
|
||||
@@ -210,12 +210,18 @@ 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 clearTableState(page, 'client-table-state');
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
@@ -247,7 +253,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 clearTableState(page, 'client-table-state');
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
@@ -268,7 +274,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 clearTableState(page, 'client-table-state');
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('client_table');
|
||||
@@ -391,7 +397,7 @@ test.describe('Clients Pagination', () => {
|
||||
);
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
// Default sort is name asc; first 15 clients (00–14) on page 1.
|
||||
@@ -444,7 +450,7 @@ test.describe('Clients Pagination', () => {
|
||||
);
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId('client_table')).toBeVisible();
|
||||
@@ -464,7 +470,7 @@ test.describe('Clients Pagination', () => {
|
||||
);
|
||||
|
||||
await goToClientsOverview(page);
|
||||
await clearTableState(page, 'client-table-state');
|
||||
await clearClientTableState(page);
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 });
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
updateMemberBillableRateViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
import { clearTableState, getTableRowNames } from './utils/table';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
|
||||
// Tests that invite + accept members need more time
|
||||
test.describe.configure({ timeout: 45000 });
|
||||
@@ -779,18 +779,20 @@ 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".
|
||||
// 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.
|
||||
// Create two placeholder members with names that sort predictably around "John Doe"
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'AAA SortFirst');
|
||||
await page.waitForTimeout(1100);
|
||||
await createPlaceholderMemberViaImportApi(ctx, 'ZZZ SortLast');
|
||||
|
||||
await goToMembersPage(page);
|
||||
await clearTableState(page, 'member-table-state');
|
||||
await clearMemberTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
@@ -812,24 +814,20 @@ 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();
|
||||
@@ -839,7 +837,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 clearTableState(page, 'member-table-state');
|
||||
await clearMemberTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
@@ -877,7 +875,7 @@ test('test that sorting members by billable rate works', async ({ page, ctx }) =
|
||||
await updateMemberBillableRateViaApi(ctx, lowRateMember!.id, 5000);
|
||||
|
||||
await goToMembersPage(page);
|
||||
await clearTableState(page, 'member-table-state');
|
||||
await clearMemberTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('member_table');
|
||||
|
||||
@@ -13,12 +13,18 @@ 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);
|
||||
@@ -78,7 +84,7 @@ test('test that archiving and unarchiving projects works', async ({ page, ctx })
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
@@ -474,7 +480,7 @@ test('test that sorting projects by all columns works', async ({ page, ctx }) =>
|
||||
});
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
await expect(page.getByTestId('project_table')).toBeVisible();
|
||||
await expect(page.getByText('AAA Project')).toBeVisible();
|
||||
@@ -603,7 +609,7 @@ test('test that filtering projects by status works', async ({ page, ctx }) => {
|
||||
await createProjectViaApi(ctx, { name: newProjectName });
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
await expect(page.getByText(newProjectName)).toBeVisible({ timeout: 10000 });
|
||||
|
||||
@@ -634,7 +640,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 clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
|
||||
// Apply Active status filter
|
||||
@@ -650,96 +656,9 @@ 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 clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
|
||||
// Click on Name header twice to sort descending
|
||||
@@ -1195,7 +1114,7 @@ test.describe('Projects Pagination', () => {
|
||||
);
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
|
||||
// Default sort is name asc; first 15 projects (00–14) should be on page 1.
|
||||
@@ -1249,7 +1168,7 @@ test.describe('Projects Pagination', () => {
|
||||
);
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByTestId('project_table')).toBeVisible();
|
||||
@@ -1266,7 +1185,7 @@ test.describe('Projects Pagination', () => {
|
||||
);
|
||||
|
||||
await goToProjectsOverview(page);
|
||||
await clearTableState(page, 'project-table-state');
|
||||
await clearProjectTableState(page);
|
||||
await page.reload();
|
||||
|
||||
await expect(page.getByText(prefix + '00')).toBeVisible({ timeout: 10000 });
|
||||
@@ -1288,36 +1207,3 @@ 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,7 +10,6 @@ import {
|
||||
createTimeEntryWithTagViaApi,
|
||||
createTimeEntryWithBillableStatusViaApi,
|
||||
createBareTimeEntryViaApi,
|
||||
createTimeEntryOnDateViaApi,
|
||||
createPublicProjectViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
@@ -842,127 +841,6 @@ 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
|
||||
// ──────────────────────────────────────────────────
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
createTimeEntryWithBillableStatusViaApi,
|
||||
createTagViaApi,
|
||||
createReportViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
} from './utils/api';
|
||||
import {
|
||||
goToReporting,
|
||||
@@ -69,42 +68,6 @@ 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 { clearTableState, getTableRowNames } from './utils/table';
|
||||
import { getTableRowNames } from './utils/table';
|
||||
|
||||
async function goToTagsOverview(page: Page) {
|
||||
await page.goto(PLAYWRIGHT_BASE_URL + '/tags');
|
||||
@@ -147,12 +147,18 @@ 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 clearTableState(page, 'tag-table-state');
|
||||
await clearTagTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('tag_table');
|
||||
@@ -170,7 +176,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 clearTableState(page, 'tag-table-state');
|
||||
await clearTagTableState(page);
|
||||
await page.reload();
|
||||
|
||||
const table = page.getByTestId('tag_table');
|
||||
|
||||
@@ -7,56 +7,13 @@ 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);
|
||||
@@ -344,59 +301,6 @@ 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
|
||||
// =============================================
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
createTimeEntryWithTimestampsViaApi,
|
||||
getTimeEntriesViaApi,
|
||||
updateOrganizationSettingViaApi,
|
||||
type TestContext,
|
||||
} from './utils/api';
|
||||
|
||||
// ──────────────────────────────────────────────────
|
||||
@@ -66,34 +65,6 @@ 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();
|
||||
|
||||
@@ -694,27 +665,37 @@ test('test that adding a timesheet break to a full day splits the work entry via
|
||||
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');
|
||||
const breakRow = page
|
||||
.locator('[data-testid="timesheet_row"]')
|
||||
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||
await breakCell.click();
|
||||
await breakCell.fill('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.
|
||||
// The placement modal opens with the split preview
|
||||
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.waitForResponse(
|
||||
async (resp) =>
|
||||
resp.url().includes('/time-entries') &&
|
||||
resp.request().method() === 'POST' &&
|
||||
resp.status() === 201 &&
|
||||
(await resp.json()).data.type === 'break'
|
||||
),
|
||||
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`],
|
||||
]);
|
||||
// The day now has two work halves and one break, none overlapping
|
||||
const entries = await getTimeEntriesViaApi(ctx);
|
||||
const dayEntries = entries
|
||||
.filter((e) => e.start.startsWith(day))
|
||||
.sort((a, b) => a.start.localeCompare(b.start));
|
||||
expect(dayEntries).toHaveLength(3);
|
||||
expect(dayEntries.map((e) => e.type)).toEqual(['work', 'break', 'work']);
|
||||
// The break sits flush between the two halves
|
||||
expect(dayEntries[0].end).toBe(dayEntries[1].start);
|
||||
expect(dayEntries[1].end).toBe(dayEntries[2].start);
|
||||
});
|
||||
|
||||
test('test that adding a break into an oversized gap places it without moving other entries', async ({
|
||||
@@ -741,11 +722,28 @@ test('test that adding a break into an oversized gap places it without moving ot
|
||||
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')]);
|
||||
const breakRow = page
|
||||
.locator('[data-testid="timesheet_row"]')
|
||||
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||
await breakCell.click();
|
||||
await breakCell.fill('0.5');
|
||||
await Promise.all([
|
||||
page.waitForResponse(
|
||||
async (resp) =>
|
||||
resp.url().includes('/time-entries') &&
|
||||
resp.request().method() === 'POST' &&
|
||||
resp.status() === 201 &&
|
||||
(await resp.json()).data.type === 'break'
|
||||
),
|
||||
breakCell.press('Enter'),
|
||||
]);
|
||||
|
||||
await expect(page.getByTestId('break_placement_summary')).not.toBeVisible();
|
||||
const dayEntries = await getDayEntriesViaApi(ctx, day);
|
||||
const entries = await getTimeEntriesViaApi(ctx);
|
||||
const dayEntries = entries
|
||||
.filter((e) => e.start.startsWith(day))
|
||||
.sort((a, b) => a.start.localeCompare(b.start));
|
||||
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`],
|
||||
@@ -777,7 +775,12 @@ test('test that the placement modal warns when the chosen time would leave the b
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
|
||||
const breakCell = await fillBreakCell(page, '0.5');
|
||||
const breakRow = page
|
||||
.locator('[data-testid="timesheet_row"]')
|
||||
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||
await breakCell.click();
|
||||
await breakCell.fill('0.5');
|
||||
await breakCell.press('Enter');
|
||||
|
||||
// Default suggestion sits flush between work → no warning
|
||||
@@ -801,23 +804,64 @@ test('test that the placement modal warns when the chosen time would leave the b
|
||||
|
||||
// The warning is non-blocking: the break can still be added as chosen
|
||||
await Promise.all([
|
||||
waitForBreakCreated(page),
|
||||
page.waitForResponse(
|
||||
async (resp) =>
|
||||
resp.url().includes('/time-entries') &&
|
||||
resp.request().method() === 'POST' &&
|
||||
resp.status() === 201 &&
|
||||
(await resp.json()).data.type === 'break'
|
||||
),
|
||||
page.getByRole('button', { name: 'Add break' }).click(),
|
||||
]);
|
||||
|
||||
const dayEntries = await getDayEntriesViaApi(ctx, day);
|
||||
const entries = await getTimeEntriesViaApi(ctx);
|
||||
const dayEntries = entries
|
||||
.filter((e) => e.start.startsWith(day))
|
||||
.sort((a, b) => a.start.localeCompare(b.start));
|
||||
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
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'does not align with your work entries' })
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('test that a misplaced break shows a warning on its timesheet day cell', async ({
|
||||
page,
|
||||
ctx,
|
||||
}) => {
|
||||
// Work ends at 10:00 and the break starts hours later with no work after it,
|
||||
// so it is misplaced and its day header should carry the warning hint.
|
||||
await updateOrganizationSettingViaApi(ctx, { breaks_enabled: true });
|
||||
const day = getCurrentWeekMonday().toISOString().slice(0, 10);
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T09:00:00Z`,
|
||||
end: `${day}T10:00:00Z`,
|
||||
});
|
||||
await createTimeEntryWithTimestampsViaApi(ctx, {
|
||||
start: `${day}T14:00:00Z`,
|
||||
end: `${day}T14:30:00Z`,
|
||||
type: 'break',
|
||||
});
|
||||
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
|
||||
// Exactly one warning, sitting in Monday's day header
|
||||
const hint = page.getByRole('button', {
|
||||
name: 'does not align with your work entries',
|
||||
});
|
||||
await expect(hint).toBeVisible();
|
||||
await expect(hint).toHaveCount(1);
|
||||
await expect(
|
||||
page.getByTestId('timesheet_day_header').first().getByRole('button', {
|
||||
name: 'does not align with your work entries',
|
||||
})
|
||||
).toBeVisible();
|
||||
|
||||
// The resulting warning links to the calendar on the affected date.
|
||||
// The hint links to the calendar on the affected date
|
||||
await hint.click();
|
||||
await expect(page.getByRole('link', { name: 'Fix in calendar' })).toHaveAttribute(
|
||||
'href',
|
||||
@@ -850,7 +894,12 @@ test('test that editing a timesheet break re-places it as one entry instead of f
|
||||
|
||||
await goToTimesheet(page);
|
||||
await expect(page.getByTestId('timesheet_view')).toBeVisible();
|
||||
const breakCell = await fillBreakCell(page, '0.75');
|
||||
const breakRow = page
|
||||
.locator('[data-testid="timesheet_row"]')
|
||||
.filter({ has: page.getByText('Break', { exact: true }) });
|
||||
const breakCell = breakRow.locator('[data-testid="timesheet_cell"]').nth(0).locator('input');
|
||||
await breakCell.click();
|
||||
await breakCell.fill('0.75'); // 45 minutes — still fits the 1h gap, so it stays anchored
|
||||
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.
|
||||
@@ -866,61 +915,10 @@ test('test that editing a timesheet break re-places it as one entry instead of f
|
||||
|
||||
// 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');
|
||||
const after = await getTimeEntriesViaApi(ctx);
|
||||
const breaks = after.filter((e) => e.start.startsWith(day) && 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`],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -357,7 +357,7 @@ export async function createProjectWithClientViaApi(
|
||||
|
||||
export async function createTaskViaApi(
|
||||
ctx: TestContext,
|
||||
data: { name: string; project_id: string; estimated_time?: number }
|
||||
data: { name: string; project_id: string }
|
||||
) {
|
||||
const response = await ctx.request.post(
|
||||
`${PLAYWRIGHT_BASE_URL}/api/v1/organizations/${ctx.orgId}/tasks`,
|
||||
@@ -365,20 +365,12 @@ export async function createTaskViaApi(
|
||||
data: {
|
||||
name: data.name,
|
||||
project_id: data.project_id,
|
||||
...(data.estimated_time !== undefined
|
||||
? { estimated_time: data.estimated_time }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
);
|
||||
expect(response.status()).toBe(201);
|
||||
const body = await response.json();
|
||||
return body.data as {
|
||||
id: string;
|
||||
name: string;
|
||||
project_id: string;
|
||||
estimated_time: number | null;
|
||||
};
|
||||
return body.data as { id: string; name: string; project_id: string };
|
||||
}
|
||||
|
||||
export async function markTaskDoneViaApi(ctx: TestContext, task: { id: string; name: string }) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
import type { Locator } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Extract the first cell's text content from each row in a table.
|
||||
@@ -14,22 +14,3 @@ export async function getTableRowNames(table: Locator): Promise<string[]> {
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* The visual order of the given seeded names within the table, ignoring any other rows.
|
||||
*/
|
||||
export async function getSeededRowOrder(table: Locator, seeded: string[]): Promise<string[]> {
|
||||
const rowNames = await getTableRowNames(table);
|
||||
return rowNames
|
||||
.map((rowName) => seeded.find((name) => rowName.includes(name)))
|
||||
.filter((name): name is string => Boolean(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a table's persisted sort/filter state so a test starts from the defaults.
|
||||
*/
|
||||
export async function clearTableState(page: Page, key: string) {
|
||||
await page.evaluate((storageKey) => {
|
||||
localStorage.removeItem(storageKey);
|
||||
}, key);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
{
|
||||
"Billing": {
|
||||
"repository": "solidtime-io/extension-billing",
|
||||
"ref": "v0.0.6"
|
||||
"ref": "v0.0.1"
|
||||
},
|
||||
"Services": {
|
||||
"repository": "solidtime-io/extension-services",
|
||||
"ref": "v0.0.2"
|
||||
"ref": "v0.0.1"
|
||||
},
|
||||
"Invoicing": {
|
||||
"repository": "solidtime-io/extension-invoicing",
|
||||
"ref": "v0.0.2"
|
||||
"ref": "v0.0.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,14 @@ import Pagination from '@/Components/Common/Pagination.vue';
|
||||
import { canCreateClients } from '@/utils/permissions';
|
||||
import { useProjectsQuery } from '@/utils/useProjectsQuery';
|
||||
import {
|
||||
useSortableTable,
|
||||
type SortableColumnDef,
|
||||
type SortDirection,
|
||||
} from '@/utils/useSortableTable';
|
||||
useVueTable,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
type SortingState,
|
||||
} from '@tanstack/vue-table';
|
||||
|
||||
export type SortColumn = 'name' | 'projects_count' | 'status';
|
||||
export type { SortDirection } from '@/utils/useSortableTable';
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
const props = defineProps<{
|
||||
clients: Client[];
|
||||
@@ -43,7 +44,17 @@ const projectCountMap = computed(() => {
|
||||
return map;
|
||||
});
|
||||
|
||||
const columns = computed<SortableColumnDef<Client, SortColumn>[]>(() => [
|
||||
// Name is always the secondary sort so rows with equal values render
|
||||
// alphabetically instead of in API (created_at) order.
|
||||
const sorting = computed<SortingState>(() => [
|
||||
{
|
||||
id: props.sortColumn,
|
||||
desc: props.sortDirection === 'desc',
|
||||
},
|
||||
...(props.sortColumn !== 'name' ? [{ id: 'name', desc: false }] : []),
|
||||
]);
|
||||
|
||||
const columns = computed(() => [
|
||||
{
|
||||
id: 'name',
|
||||
accessorFn: (row: Client) => row.name.toLowerCase(),
|
||||
@@ -59,22 +70,41 @@ const columns = computed<SortableColumnDef<Client, SortColumn>[]>(() => [
|
||||
},
|
||||
]);
|
||||
|
||||
const {
|
||||
sortedRows: sortedClients,
|
||||
descFirstColumns,
|
||||
nextDirection,
|
||||
} = useSortableTable({
|
||||
data: () => props.clients,
|
||||
columns: () => columns.value,
|
||||
sortColumn: () => props.sortColumn,
|
||||
sortDirection: () => props.sortDirection,
|
||||
tieBreakColumn: 'name',
|
||||
});
|
||||
const descFirstColumns = new Set<SortColumn>(
|
||||
columns.value
|
||||
.filter((c) => 'sortDescFirst' in c && c.sortDescFirst)
|
||||
.map((c) => c.id as SortColumn)
|
||||
);
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column, nextDirection(column));
|
||||
if (props.sortColumn === column) {
|
||||
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
|
||||
}
|
||||
}
|
||||
|
||||
const table = useVueTable({
|
||||
get data() {
|
||||
return props.clients;
|
||||
},
|
||||
get columns() {
|
||||
return columns.value;
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
get sorting() {
|
||||
return sorting.value;
|
||||
},
|
||||
},
|
||||
manualSorting: false,
|
||||
});
|
||||
|
||||
const sortedClients = computed(() => {
|
||||
return table.getRowModel().rows.map((row) => row.original);
|
||||
});
|
||||
|
||||
// Client-side pagination: the full list is in memory, only one page is mounted at a time.
|
||||
const PAGE_SIZE = 15;
|
||||
const currentPage = ref(1);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import TableHeading from '@/Components/Common/TableHeading.vue';
|
||||
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue';
|
||||
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Client/ClientTable.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -9,29 +9,57 @@ const props = defineProps<{
|
||||
descFirstColumns: ReadonlySet<SortColumn>;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
const emit = defineEmits<{
|
||||
sort: [column: SortColumn];
|
||||
}>();
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column);
|
||||
}
|
||||
|
||||
function isSorted(column: SortColumn): boolean {
|
||||
return props.sortColumn === column;
|
||||
}
|
||||
|
||||
function isChevronDown(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return props.descFirstColumns.has(column)
|
||||
? props.sortDirection === 'desc'
|
||||
: props.sortDirection === 'asc';
|
||||
}
|
||||
|
||||
function isChevronUp(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return !isChevronDown(column);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TableHeading>
|
||||
<SortableTableHeaderCell
|
||||
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12"
|
||||
column="name"
|
||||
v-bind="props"
|
||||
@sort="$emit('sort', $event)">
|
||||
<div
|
||||
class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('name')">
|
||||
Name
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell
|
||||
column="projects_count"
|
||||
v-bind="props"
|
||||
@sort="$emit('sort', $event)">
|
||||
<ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('projects_count')">
|
||||
Projects
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="status" v-bind="props" @sort="$emit('sort', $event)">
|
||||
<ChevronDownIcon v-if="isChevronDown('projects_count')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('projects_count')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('status')">
|
||||
Status
|
||||
</SortableTableHeaderCell>
|
||||
<ChevronDownIcon v-if="isChevronDown('status')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('status')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
|
||||
<span class="sr-only">Edit</span>
|
||||
</div>
|
||||
|
||||
@@ -3,14 +3,16 @@ import MemberTableHeading from '@/Components/Common/Member/MemberTableHeading.vu
|
||||
import MemberTableRow from '@/Components/Common/Member/MemberTableRow.vue';
|
||||
import { useMembersQuery } from '@/utils/useMembersQuery';
|
||||
import type { Member } from '@/packages/api/src';
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
useSortableTable,
|
||||
type SortableColumnDef,
|
||||
type SortDirection,
|
||||
} from '@/utils/useSortableTable';
|
||||
useVueTable,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
type SortingState,
|
||||
} from '@tanstack/vue-table';
|
||||
|
||||
export type SortColumn = 'name' | 'email' | 'role' | 'billable_rate' | 'status';
|
||||
export type { SortDirection } from '@/utils/useSortableTable';
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
const props = defineProps<{
|
||||
sortColumn: SortColumn;
|
||||
@@ -31,7 +33,14 @@ const roleOrder: Record<string, number> = {
|
||||
placeholder: 4,
|
||||
};
|
||||
|
||||
const columns: SortableColumnDef<Member, SortColumn>[] = [
|
||||
const sorting = computed<SortingState>(() => [
|
||||
{
|
||||
id: props.sortColumn,
|
||||
desc: props.sortDirection === 'desc',
|
||||
},
|
||||
]);
|
||||
|
||||
const columns = [
|
||||
{
|
||||
id: 'name',
|
||||
accessorFn: (row: Member) => row.name.toLowerCase(),
|
||||
@@ -47,6 +56,7 @@ const columns: SortableColumnDef<Member, SortColumn>[] = [
|
||||
{
|
||||
id: 'billable_rate',
|
||||
sortDescFirst: true,
|
||||
sortUndefined: 'last' as const,
|
||||
accessorFn: (row: Member) => {
|
||||
if (row.billable_rate === null) return undefined;
|
||||
return row.billable_rate;
|
||||
@@ -58,21 +68,36 @@ const columns: SortableColumnDef<Member, SortColumn>[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const {
|
||||
sortedRows: sortedMembers,
|
||||
descFirstColumns,
|
||||
nextDirection,
|
||||
} = useSortableTable({
|
||||
data: () => members.value,
|
||||
columns: () => columns,
|
||||
sortColumn: () => props.sortColumn,
|
||||
sortDirection: () => props.sortDirection,
|
||||
tieBreakColumn: 'name',
|
||||
});
|
||||
const descFirstColumns = new Set<SortColumn>(
|
||||
columns.filter((c) => c.sortDescFirst).map((c) => c.id as SortColumn)
|
||||
);
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column, nextDirection(column));
|
||||
if (props.sortColumn === column) {
|
||||
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
|
||||
}
|
||||
}
|
||||
|
||||
const table = useVueTable({
|
||||
get data() {
|
||||
return members.value;
|
||||
},
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
get sorting() {
|
||||
return sorting.value;
|
||||
},
|
||||
},
|
||||
manualSorting: false,
|
||||
});
|
||||
|
||||
const sortedMembers = computed(() => {
|
||||
return table.getRowModel().rows.map((row) => row.original);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import TableHeading from '@/Components/Common/TableHeading.vue';
|
||||
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue';
|
||||
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Member/MemberTable.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -9,35 +9,73 @@ const props = defineProps<{
|
||||
descFirstColumns: ReadonlySet<SortColumn>;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
const emit = defineEmits<{
|
||||
sort: [column: SortColumn];
|
||||
}>();
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column);
|
||||
}
|
||||
|
||||
function isSorted(column: SortColumn): boolean {
|
||||
return props.sortColumn === column;
|
||||
}
|
||||
|
||||
function isChevronDown(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return props.descFirstColumns.has(column)
|
||||
? props.sortDirection === 'desc'
|
||||
: props.sortDirection === 'asc';
|
||||
}
|
||||
|
||||
function isChevronUp(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return !isChevronDown(column);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TableHeading>
|
||||
<SortableTableHeaderCell
|
||||
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12"
|
||||
column="name"
|
||||
v-bind="props"
|
||||
@sort="$emit('sort', $event)">
|
||||
<div
|
||||
class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('name')">
|
||||
Name
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="email" v-bind="props" @sort="$emit('sort', $event)">
|
||||
<ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('email')">
|
||||
Email
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="role" v-bind="props" @sort="$emit('sort', $event)">
|
||||
<ChevronDownIcon v-if="isChevronDown('email')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('email')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('role')">
|
||||
Role
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell
|
||||
column="billable_rate"
|
||||
v-bind="props"
|
||||
@sort="$emit('sort', $event)">
|
||||
<ChevronDownIcon v-if="isChevronDown('role')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('role')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('billable_rate')">
|
||||
Billable Rate
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="status" v-bind="props" @sort="$emit('sort', $event)">
|
||||
<ChevronDownIcon v-if="isChevronDown('billable_rate')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('billable_rate')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('status')">
|
||||
Status
|
||||
</SortableTableHeaderCell>
|
||||
<ChevronDownIcon v-if="isChevronDown('status')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('status')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12 bg-row-heading-background">
|
||||
<span class="sr-only">Edit</span>
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,6 @@ import ProjectCreateModal from '@/packages/ui/src/Project/ProjectCreateModal.vue
|
||||
import ProjectTableHeading from '@/Components/Common/Project/ProjectTableHeading.vue';
|
||||
import ProjectTableRow from '@/Components/Common/Project/ProjectTableRow.vue';
|
||||
import Pagination from '@/Components/Common/Pagination.vue';
|
||||
import LoadingSpinner from '@/packages/ui/src/LoadingSpinner.vue';
|
||||
|
||||
export type SortColumn =
|
||||
| 'name'
|
||||
@@ -17,7 +16,7 @@ export type SortColumn =
|
||||
| 'billable_rate'
|
||||
| 'status'
|
||||
| 'visibility';
|
||||
export type { SortDirection } from '@/utils/useSortableTable';
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
import { canCreateProjects } from '@/utils/permissions';
|
||||
import type { CreateProjectBody, Project, Client, CreateClientBody } from '@/packages/api/src';
|
||||
import { useProjectsStore } from '@/utils/useProjects';
|
||||
@@ -28,24 +27,20 @@ import { isAllowedToPerformPremiumAction } from '@/utils/billing';
|
||||
import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
|
||||
import { getCurrentOrganizationId } from '@/utils/useUser';
|
||||
import {
|
||||
useSortableTable,
|
||||
type SortableColumnDef,
|
||||
type SortDirection,
|
||||
} from '@/utils/useSortableTable';
|
||||
useVueTable,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
type SortingState,
|
||||
} from '@tanstack/vue-table';
|
||||
|
||||
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
projects: Project[];
|
||||
showBillableRate: boolean;
|
||||
sortColumn: SortColumn;
|
||||
sortDirection: SortDirection;
|
||||
isFiltered?: boolean;
|
||||
isLoading?: boolean;
|
||||
}>(),
|
||||
{ isFiltered: false, isLoading: false }
|
||||
);
|
||||
const props = defineProps<{
|
||||
projects: Project[];
|
||||
showBillableRate: boolean;
|
||||
sortColumn: SortColumn;
|
||||
sortDirection: SortDirection;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
sort: [column: SortColumn, direction: SortDirection];
|
||||
@@ -62,16 +57,28 @@ const clientNameMap = computed(() => {
|
||||
return map;
|
||||
});
|
||||
|
||||
// Convert sort props to TanStack Table format.
|
||||
// Name is always the secondary sort so rows with equal values render
|
||||
// alphabetically instead of in API (created_at) order.
|
||||
const sorting = computed<SortingState>(() => [
|
||||
{
|
||||
id: props.sortColumn,
|
||||
desc: props.sortDirection === 'desc',
|
||||
},
|
||||
...(props.sortColumn !== 'name' ? [{ id: 'name', desc: false }] : []),
|
||||
]);
|
||||
|
||||
// Define column accessors for sorting.
|
||||
// Numeric columns use sortDescFirst so that the first click (chevron down) sorts highest-first,
|
||||
// while text columns default to ascending (A-Z) on first click (chevron down).
|
||||
const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
|
||||
const columns = computed(() => [
|
||||
{
|
||||
id: 'name',
|
||||
accessorFn: (row: Project) => row.name.toLowerCase(),
|
||||
},
|
||||
{
|
||||
id: 'client_name',
|
||||
sortUndefined: 'last' as const,
|
||||
accessorFn: (row: Project) => {
|
||||
if (!row.client_id) return undefined;
|
||||
return (clientNameMap.value.get(row.client_id) ?? '').toLowerCase();
|
||||
@@ -80,11 +87,12 @@ const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
|
||||
{
|
||||
id: 'spent_time',
|
||||
sortDescFirst: true,
|
||||
accessorFn: (row: Project) => row.spent_time,
|
||||
accessorFn: (row: Project) => row.spent_time ?? 0,
|
||||
},
|
||||
{
|
||||
id: 'progress',
|
||||
sortDescFirst: true,
|
||||
sortUndefined: 'last' as const,
|
||||
accessorFn: (row: Project) => {
|
||||
if (!row.estimated_time) return undefined;
|
||||
return (row.spent_time / row.estimated_time) * 100;
|
||||
@@ -93,7 +101,7 @@ const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
|
||||
{
|
||||
id: 'billable_rate',
|
||||
sortDescFirst: true,
|
||||
accessorFn: (row: Project) => row.billable_rate,
|
||||
accessorFn: (row: Project) => row.billable_rate ?? 0,
|
||||
},
|
||||
{
|
||||
id: 'status',
|
||||
@@ -105,22 +113,40 @@ const columns = computed<SortableColumnDef<Project, SortColumn>[]>(() => [
|
||||
},
|
||||
]);
|
||||
|
||||
const {
|
||||
sortedRows: sortedProjects,
|
||||
descFirstColumns,
|
||||
nextDirection,
|
||||
} = useSortableTable({
|
||||
data: () => props.projects,
|
||||
columns: () => columns.value,
|
||||
sortColumn: () => props.sortColumn,
|
||||
sortDirection: () => props.sortDirection,
|
||||
tieBreakColumn: 'name',
|
||||
});
|
||||
// Columns with sortDescFirst get desc as default direction on first click.
|
||||
const descFirstColumns = new Set<SortColumn>(
|
||||
columns.value.filter((c) => c.sortDescFirst).map((c) => c.id as SortColumn)
|
||||
);
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column, nextDirection(column));
|
||||
if (props.sortColumn === column) {
|
||||
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
|
||||
}
|
||||
}
|
||||
|
||||
const table = useVueTable({
|
||||
get data() {
|
||||
return props.projects;
|
||||
},
|
||||
get columns() {
|
||||
return columns.value;
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
get sorting() {
|
||||
return sorting.value;
|
||||
},
|
||||
},
|
||||
manualSorting: false,
|
||||
});
|
||||
|
||||
const sortedProjects = computed(() => {
|
||||
return table.getRowModel().rows.map((row) => row.original);
|
||||
});
|
||||
|
||||
// Client-side pagination: the full list is in memory, only one page is mounted at a time.
|
||||
const PAGE_SIZE = 15;
|
||||
const currentPage = ref(1);
|
||||
@@ -134,28 +160,6 @@ const paginatedProjects = computed(() => {
|
||||
return sortedProjects.value.slice(start, start + PAGE_SIZE);
|
||||
});
|
||||
|
||||
const emptyState = computed(() => {
|
||||
if (props.isFiltered) {
|
||||
return {
|
||||
title: 'No matching projects',
|
||||
description: 'Try a different search term or adjust your filters.',
|
||||
showCreateButton: false,
|
||||
};
|
||||
}
|
||||
if (!canCreateProjects()) {
|
||||
return {
|
||||
title: 'You are not a member of any projects',
|
||||
description: 'Ask your manager to add you to a project as a team member.',
|
||||
showCreateButton: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: 'No projects found',
|
||||
description: 'Create your first project now!',
|
||||
showCreateButton: true,
|
||||
};
|
||||
});
|
||||
|
||||
const showCreateProjectModal = ref(false);
|
||||
|
||||
async function createProject(project: CreateProjectBody): Promise<Project | undefined> {
|
||||
@@ -189,21 +193,24 @@ const gridTemplate = computed(() => {
|
||||
:sort-direction="props.sortDirection"
|
||||
:desc-first-columns="descFirstColumns"
|
||||
@sort="handleSort"></ProjectTableHeading>
|
||||
<div
|
||||
v-if="props.isLoading"
|
||||
class="col-span-full flex justify-center items-center py-24">
|
||||
<LoadingSpinner></LoadingSpinner>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="sortedProjects.length === 0"
|
||||
class="col-span-full py-24 text-center">
|
||||
<div v-if="sortedProjects.length === 0" class="col-span-full py-24 text-center">
|
||||
<FolderPlusIcon class="w-8 text-icon-default inline pb-2"></FolderPlusIcon>
|
||||
<h3 class="text-text-primary font-semibold">{{ emptyState.title }}</h3>
|
||||
<h3 class="text-text-primary font-semibold">
|
||||
{{
|
||||
canCreateProjects()
|
||||
? 'No projects found'
|
||||
: 'You are not a member of any projects'
|
||||
}}
|
||||
</h3>
|
||||
<p class="pb-5 max-w-md mx-auto text-sm pt-1">
|
||||
{{ emptyState.description }}
|
||||
{{
|
||||
canCreateProjects()
|
||||
? 'Create your first project now!'
|
||||
: 'Ask your manager to add you to a project as a team member.'
|
||||
}}
|
||||
</p>
|
||||
<SecondaryButton
|
||||
v-if="emptyState.showCreateButton"
|
||||
v-if="canCreateProjects()"
|
||||
:icon="PlusIcon"
|
||||
@click="showCreateProjectModal = true"
|
||||
>Create your First Project
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import TableHeading from '@/Components/Common/TableHeading.vue';
|
||||
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue';
|
||||
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Project/ProjectTable.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -15,51 +14,90 @@ const emit = defineEmits<{
|
||||
sort: [column: SortColumn];
|
||||
}>();
|
||||
|
||||
// Bound once per cell instead of repeating the three sort props on every column.
|
||||
const sortState = computed(() => ({
|
||||
sortColumn: props.sortColumn,
|
||||
sortDirection: props.sortDirection,
|
||||
descFirstColumns: props.descFirstColumns,
|
||||
}));
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column);
|
||||
}
|
||||
|
||||
function isSorted(column: SortColumn): boolean {
|
||||
return props.sortColumn === column;
|
||||
}
|
||||
|
||||
function isChevronDown(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return props.descFirstColumns.has(column)
|
||||
? props.sortDirection === 'desc'
|
||||
: props.sortDirection === 'asc';
|
||||
}
|
||||
|
||||
function isChevronUp(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return !isChevronDown(column);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TableHeading>
|
||||
<SortableTableHeaderCell
|
||||
class="pr-3 pl-2 sm:pl-4 lg:pl-6"
|
||||
column="name"
|
||||
v-bind="sortState"
|
||||
@sort="handleSort">
|
||||
<div
|
||||
class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('name')">
|
||||
Name
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="client_name" v-bind="sortState" @sort="handleSort">
|
||||
<ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('client_name')">
|
||||
Client
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="spent_time" v-bind="sortState" @sort="handleSort">
|
||||
<ChevronDownIcon v-if="isChevronDown('client_name')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('client_name')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('spent_time')">
|
||||
Total Time
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="progress" v-bind="sortState" @sort="handleSort">
|
||||
<ChevronDownIcon v-if="isChevronDown('spent_time')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('spent_time')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('progress')">
|
||||
Progress
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell
|
||||
<ChevronDownIcon v-if="isChevronDown('progress')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('progress')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
v-if="showBillableRate"
|
||||
column="billable_rate"
|
||||
v-bind="sortState"
|
||||
@sort="handleSort">
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('billable_rate')">
|
||||
Billable Rate
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="status" v-bind="sortState" @sort="handleSort">
|
||||
<ChevronDownIcon v-if="isChevronDown('billable_rate')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('billable_rate')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('status')">
|
||||
Status
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="visibility" v-bind="sortState" @sort="handleSort">
|
||||
<ChevronDownIcon v-if="isChevronDown('status')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('status')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div
|
||||
class="px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('visibility')">
|
||||
Visibility
|
||||
</SortableTableHeaderCell>
|
||||
<div class="relative py-1.5 pl-3 pr-2 sm:pr-4 lg:pr-6">
|
||||
<ChevronDownIcon v-if="isChevronDown('visibility')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('visibility')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
|
||||
<span class="sr-only">Edit</span>
|
||||
</div>
|
||||
</TableHeading>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
|
||||
@@ -88,13 +88,13 @@ const showEditProjectModal = ref(false);
|
||||
<ContextMenuTrigger as-child>
|
||||
<TableRow :href="route('projects.show', { project: project.id })">
|
||||
<div
|
||||
class="whitespace-nowrap min-w-0 flex items-center space-x-5 py-4 pr-3 text-sm font-medium text-text-primary pl-2 sm:pl-4 lg:pl-6">
|
||||
class="whitespace-nowrap min-w-0 flex items-center space-x-5 3xl:pl-12 py-4 pr-3 text-sm font-medium text-text-primary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12">
|
||||
<div
|
||||
:style="{
|
||||
backgroundColor: project.color,
|
||||
boxShadow: `var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) ${project.color}30`,
|
||||
}"
|
||||
class="w-3 h-3 ml-1 rounded-full"></div>
|
||||
class="w-3 h-3 rounded-full"></div>
|
||||
<span class="overflow-ellipsis overflow-hidden">
|
||||
{{ project.name }}
|
||||
</span>
|
||||
@@ -155,7 +155,7 @@ const showEditProjectModal = ref(false);
|
||||
</template>
|
||||
</div>
|
||||
<div
|
||||
class="relative whitespace-nowrap flex items-center pl-3 text-right text-sm font-medium pr-2 sm:pr-4 lg:pr-6">
|
||||
class="relative whitespace-nowrap flex items-center pl-3 text-right text-sm font-medium pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
|
||||
<ProjectMoreOptionsDropdown
|
||||
:project="project"
|
||||
@edit="showEditProjectModal = true"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { UserGroupIcon, CheckCircleIcon, GlobeAltIcon } from '@heroicons/vue/16/solid';
|
||||
import ListFilterIcon from '@/packages/ui/src/Icons/ListFilterIcon.vue';
|
||||
import {
|
||||
@@ -81,18 +81,23 @@ function toggleNoClient() {
|
||||
clientIds,
|
||||
});
|
||||
}
|
||||
|
||||
const hasActiveFilters = computed(() => {
|
||||
return (
|
||||
props.filters.status !== 'all' ||
|
||||
props.filters.visibility !== 'all' ||
|
||||
props.filters.clientIds.length > 0
|
||||
);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DropdownMenu v-model:open="open">
|
||||
<DropdownMenuTrigger as-child>
|
||||
<!-- -ml-1.5 cancels the icon's inset inside the button so it sits flush with the toolbar's left padding -->
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="-ml-1.5 h-7 w-7 flex-shrink-0"
|
||||
aria-label="Filter projects">
|
||||
<ListFilterIcon class="h-4 w-4 text-icon-default" />
|
||||
<Button variant="ghost" size="xs" aria-label="Filter projects">
|
||||
<ListFilterIcon
|
||||
:class="[hasActiveFilters ? '' : '-ml-0.5', 'h-4 w-4 text-icon-default']" />
|
||||
<span v-if="!hasActiveFilters" class="text-nowrap">Filter</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" class="w-56">
|
||||
|
||||
@@ -9,7 +9,7 @@ const showExportModal = defineModel('show', { default: false });
|
||||
|
||||
function downloadCurrentExport() {
|
||||
if (props.exportUrl) {
|
||||
window.open(props.exportUrl, '_self');
|
||||
window.open(props.exportUrl, '_blank')?.focus();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -240,8 +240,7 @@ const groupedPieChartData = computed(() => {
|
||||
aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
|
||||
const name = getNameForReportingRowEntry(
|
||||
entry.key,
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? null,
|
||||
organization?.value?.date_format
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? null
|
||||
);
|
||||
let color = getRandomColorWithSeed(entry.key ?? 'none');
|
||||
if (
|
||||
@@ -256,7 +255,11 @@ const groupedPieChartData = computed(() => {
|
||||
}
|
||||
return {
|
||||
value: entry.seconds,
|
||||
name: name ?? '',
|
||||
name:
|
||||
getNameForReportingRowEntry(
|
||||
entry.key,
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? null
|
||||
) ?? '',
|
||||
color: color,
|
||||
};
|
||||
}) ?? []
|
||||
@@ -266,25 +269,18 @@ const groupedPieChartData = computed(() => {
|
||||
const tableData = computed(() => {
|
||||
return aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
|
||||
return {
|
||||
key: entry.key,
|
||||
seconds: entry.seconds,
|
||||
cost: entry.cost,
|
||||
description: getNameForReportingRowEntry(
|
||||
entry.key,
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? null,
|
||||
organization?.value?.date_format
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? null
|
||||
),
|
||||
grouped_data:
|
||||
entry.grouped_data?.map((el) => {
|
||||
return {
|
||||
key: el.key,
|
||||
seconds: el.seconds,
|
||||
cost: el.cost,
|
||||
description: getNameForReportingRowEntry(
|
||||
el.key,
|
||||
entry.grouped_type,
|
||||
organization?.value?.date_format
|
||||
),
|
||||
description: getNameForReportingRowEntry(el.key, entry.grouped_type),
|
||||
};
|
||||
}) ?? [],
|
||||
};
|
||||
@@ -425,8 +421,9 @@ const tableData = computed(() => {
|
||||
">
|
||||
<ReportingRow
|
||||
v-for="entry in tableData"
|
||||
:key="entry.key ?? 'none'"
|
||||
:key="entry.description ?? 'none'"
|
||||
:currency="getOrganizationCurrencyString()"
|
||||
:type="aggregatedTableTimeEntries.grouped_type"
|
||||
:show-cost="showBillableRate"
|
||||
:entry="entry"></ReportingRow>
|
||||
<div class="contents [&>*]:transition text-text-tertiary [&>*]:h-[50px]">
|
||||
|
||||
@@ -11,7 +11,6 @@ type AggregatedGroupedData = GroupedData & {
|
||||
};
|
||||
|
||||
type GroupedData = {
|
||||
key: string | null;
|
||||
seconds: number;
|
||||
cost: number | null;
|
||||
description: string | null | undefined;
|
||||
@@ -73,7 +72,7 @@ const organization = inject<ComputedRef<Organization>>('organization');
|
||||
:style="`grid-template-columns: 1fr 150px ${showCost ? '150px' : ''}`">
|
||||
<ReportingRow
|
||||
v-for="subEntry in entry.grouped_data"
|
||||
:key="subEntry.key ?? 'none'"
|
||||
:key="subEntry.description ?? 'none'"
|
||||
:currency="props.currency"
|
||||
:show-cost="showCost"
|
||||
indent
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
<script setup lang="ts" generic="TColumn extends string">
|
||||
import { computed, useAttrs } from 'vue';
|
||||
import type { ClassValue } from 'clsx';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
|
||||
import type { SortDirection } from '@/utils/useSortableTable';
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
const props = defineProps<{
|
||||
column: TColumn;
|
||||
sortColumn: TColumn;
|
||||
sortDirection: SortDirection;
|
||||
descFirstColumns: ReadonlySet<TColumn>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
sort: [column: TColumn];
|
||||
}>();
|
||||
|
||||
const attrs = useAttrs();
|
||||
|
||||
const isSorted = computed(() => props.sortColumn === props.column);
|
||||
|
||||
const isChevronDown = computed(() => {
|
||||
if (!isSorted.value) return false;
|
||||
return props.descFirstColumns.has(props.column)
|
||||
? props.sortDirection === 'desc'
|
||||
: props.sortDirection === 'asc';
|
||||
});
|
||||
|
||||
const cellClass = computed(() =>
|
||||
cn(
|
||||
'px-3 py-1.5 text-left text-text-tertiary cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1',
|
||||
attrs.class as ClassValue
|
||||
)
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<button type="button" :class="cellClass" @click="emit('sort', column)">
|
||||
<slot></slot>
|
||||
<span class="sr-only">
|
||||
{{
|
||||
isSorted
|
||||
? `sorted ${sortDirection === 'asc' ? 'ascending' : 'descending'}`
|
||||
: 'not sorted'
|
||||
}}
|
||||
</span>
|
||||
<ChevronDownIcon v-if="isChevronDown" aria-hidden="true" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isSorted" aria-hidden="true" class="w-4 h-4" />
|
||||
<span v-else aria-hidden="true" class="w-4 h-4"></span>
|
||||
</button>
|
||||
</template>
|
||||
@@ -2,7 +2,7 @@
|
||||
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||
import { FolderPlusIcon } from '@heroicons/vue/24/solid';
|
||||
import { PlusIcon } from '@heroicons/vue/16/solid';
|
||||
import { ref } from 'vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { useTagsQuery } from '@/utils/useTagsQuery';
|
||||
import TagTableRow from '@/Components/Common/Tag/TagTableRow.vue';
|
||||
import TagCreateModal from '@/packages/ui/src/Tag/TagCreateModal.vue';
|
||||
@@ -10,13 +10,14 @@ import TagTableHeading from '@/Components/Common/Tag/TagTableHeading.vue';
|
||||
import { canCreateTags } from '@/utils/permissions';
|
||||
import type { Tag } from '@/packages/api/src';
|
||||
import {
|
||||
useSortableTable,
|
||||
type SortableColumnDef,
|
||||
type SortDirection,
|
||||
} from '@/utils/useSortableTable';
|
||||
useVueTable,
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
type SortingState,
|
||||
} from '@tanstack/vue-table';
|
||||
|
||||
export type SortColumn = 'name';
|
||||
export type { SortDirection } from '@/utils/useSortableTable';
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
const props = defineProps<{
|
||||
createTag: (name: string) => Promise<Tag | undefined>;
|
||||
@@ -31,27 +32,50 @@ const emit = defineEmits<{
|
||||
const { tags } = useTagsQuery();
|
||||
const showCreateTagModal = ref(false);
|
||||
|
||||
const columns: SortableColumnDef<Tag, SortColumn>[] = [
|
||||
const sorting = computed<SortingState>(() => [
|
||||
{
|
||||
id: props.sortColumn,
|
||||
desc: props.sortDirection === 'desc',
|
||||
},
|
||||
]);
|
||||
|
||||
const columns = [
|
||||
{
|
||||
id: 'name',
|
||||
accessorFn: (row: Tag) => row.name.toLowerCase(),
|
||||
},
|
||||
];
|
||||
|
||||
const {
|
||||
sortedRows: sortedTags,
|
||||
descFirstColumns,
|
||||
nextDirection,
|
||||
} = useSortableTable({
|
||||
data: () => tags.value,
|
||||
columns: () => columns,
|
||||
sortColumn: () => props.sortColumn,
|
||||
sortDirection: () => props.sortDirection,
|
||||
});
|
||||
const descFirstColumns = new Set<SortColumn>(
|
||||
columns.filter((c) => 'sortDescFirst' in c && c.sortDescFirst).map((c) => c.id as SortColumn)
|
||||
);
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column, nextDirection(column));
|
||||
if (props.sortColumn === column) {
|
||||
emit('sort', column, props.sortDirection === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
emit('sort', column, descFirstColumns.has(column) ? 'desc' : 'asc');
|
||||
}
|
||||
}
|
||||
|
||||
const table = useVueTable({
|
||||
get data() {
|
||||
return tags.value;
|
||||
},
|
||||
columns,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
get sorting() {
|
||||
return sorting.value;
|
||||
},
|
||||
},
|
||||
manualSorting: false,
|
||||
});
|
||||
|
||||
const sortedTags = computed(() => {
|
||||
return table.getRowModel().rows.map((row) => row.original);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import TableHeading from '@/Components/Common/TableHeading.vue';
|
||||
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue';
|
||||
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/vue/16/solid';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Tag/TagTable.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -9,20 +9,41 @@ const props = defineProps<{
|
||||
descFirstColumns: ReadonlySet<SortColumn>;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
const emit = defineEmits<{
|
||||
sort: [column: SortColumn];
|
||||
}>();
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column);
|
||||
}
|
||||
|
||||
function isSorted(column: SortColumn): boolean {
|
||||
return props.sortColumn === column;
|
||||
}
|
||||
|
||||
function isChevronDown(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return props.descFirstColumns.has(column)
|
||||
? props.sortDirection === 'desc'
|
||||
: props.sortDirection === 'asc';
|
||||
}
|
||||
|
||||
function isChevronUp(column: SortColumn): boolean {
|
||||
if (!isSorted(column)) return false;
|
||||
return !isChevronDown(column);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TableHeading>
|
||||
<SortableTableHeaderCell
|
||||
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12"
|
||||
column="name"
|
||||
v-bind="props"
|
||||
@sort="$emit('sort', $event)">
|
||||
<div
|
||||
class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12 cursor-pointer hover:bg-secondary hover:text-text-primary transition-colors select-none flex items-center gap-1"
|
||||
@click="handleSort('name')">
|
||||
Name
|
||||
</SortableTableHeaderCell>
|
||||
<ChevronDownIcon v-if="isChevronDown('name')" class="w-4 h-4" />
|
||||
<ChevronUpIcon v-else-if="isChevronUp('name')" class="w-4 h-4" />
|
||||
<span v-else class="w-4 h-4"></span>
|
||||
</div>
|
||||
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
|
||||
<span class="sr-only">Edit</span>
|
||||
</div>
|
||||
|
||||
@@ -8,62 +8,12 @@ import TaskTableHeading from '@/Components/Common/Task/TaskTableHeading.vue';
|
||||
import TaskCreateModal from '@/Components/Common/Task/TaskCreateModal.vue';
|
||||
import { canCreateTasks } from '@/utils/permissions';
|
||||
import type { Task } from '@/packages/api/src';
|
||||
import {
|
||||
useSortableTable,
|
||||
type SortableColumnDef,
|
||||
type SortDirection,
|
||||
} from '@/utils/useSortableTable';
|
||||
|
||||
export type SortColumn = 'name' | 'spent_time' | 'progress';
|
||||
export type { SortDirection } from '@/utils/useSortableTable';
|
||||
|
||||
const props = defineProps<{
|
||||
projectId: string;
|
||||
tasks: Task[];
|
||||
sortColumn: SortColumn;
|
||||
sortDirection: SortDirection;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
sort: [column: SortColumn, direction: SortDirection];
|
||||
}>();
|
||||
|
||||
const columns: SortableColumnDef<Task, SortColumn>[] = [
|
||||
{
|
||||
id: 'name',
|
||||
accessorFn: (row: Task) => row.name.toLowerCase(),
|
||||
},
|
||||
{
|
||||
id: 'spent_time',
|
||||
sortDescFirst: true,
|
||||
accessorFn: (row: Task) => row.spent_time,
|
||||
},
|
||||
{
|
||||
id: 'progress',
|
||||
sortDescFirst: true,
|
||||
accessorFn: (row: Task) => {
|
||||
if (!row.estimated_time) return undefined;
|
||||
return (row.spent_time / row.estimated_time) * 100;
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const {
|
||||
sortedRows: sortedTasks,
|
||||
descFirstColumns,
|
||||
nextDirection,
|
||||
} = useSortableTable({
|
||||
data: () => props.tasks,
|
||||
columns: () => columns,
|
||||
sortColumn: () => props.sortColumn,
|
||||
sortDirection: () => props.sortDirection,
|
||||
tieBreakColumn: 'name',
|
||||
});
|
||||
|
||||
function handleSort(column: SortColumn) {
|
||||
emit('sort', column, nextDirection(column));
|
||||
}
|
||||
|
||||
const createTask = ref(false);
|
||||
</script>
|
||||
|
||||
@@ -80,12 +30,8 @@ const createTask = ref(false);
|
||||
1fr minmax(80px, auto) minmax(120px, auto) minmax(50px, auto)
|
||||
80px;
|
||||
">
|
||||
<TaskTableHeading
|
||||
:sort-column="sortColumn"
|
||||
:sort-direction="sortDirection"
|
||||
:desc-first-columns="descFirstColumns"
|
||||
@sort="handleSort"></TaskTableHeading>
|
||||
<div v-if="sortedTasks.length === 0" class="col-span-5 py-24 text-center">
|
||||
<TaskTableHeading></TaskTableHeading>
|
||||
<div v-if="tasks.length === 0" class="col-span-5 py-24 text-center">
|
||||
<PlusCircleIcon class="w-8 text-icon-default inline pb-2"></PlusCircleIcon>
|
||||
<h3 class="text-text-primary font-semibold">No tasks found</h3>
|
||||
<p v-if="canCreateTasks()" class="pb-5">Create your first task now!</p>
|
||||
@@ -96,7 +42,7 @@ const createTask = ref(false);
|
||||
>Create your First Task
|
||||
</SecondaryButton>
|
||||
</div>
|
||||
<template v-for="task in sortedTasks" :key="task.id">
|
||||
<template v-for="task in tasks" :key="task.id">
|
||||
<TaskTableRow :task="task"></TaskTableRow>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -1,37 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import TableHeading from '@/Components/Common/TableHeading.vue';
|
||||
import SortableTableHeaderCell from '@/Components/Common/SortableTableHeaderCell.vue';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Task/TaskTable.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
sortColumn: SortColumn;
|
||||
sortDirection: SortDirection;
|
||||
descFirstColumns: ReadonlySet<SortColumn>;
|
||||
}>();
|
||||
|
||||
defineEmits<{
|
||||
sort: [column: SortColumn];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TableHeading>
|
||||
<SortableTableHeaderCell
|
||||
class="pr-3 pl-4 sm:pl-6 lg:pl-8 3xl:pl-12"
|
||||
column="name"
|
||||
v-bind="props"
|
||||
@sort="$emit('sort', $event)">
|
||||
<div class="py-1.5 pr-3 text-left text-text-tertiary pl-4 sm:pl-6 lg:pl-8 3xl:pl-12">
|
||||
Task Name
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="spent_time" v-bind="props" @sort="$emit('sort', $event)">
|
||||
Total Time
|
||||
</SortableTableHeaderCell>
|
||||
<SortableTableHeaderCell column="progress" v-bind="props" @sort="$emit('sort', $event)">
|
||||
Progress
|
||||
</SortableTableHeaderCell>
|
||||
</div>
|
||||
<div class="px-3 py-1.5 text-left text-text-tertiary">Total Time</div>
|
||||
<div class="px-3 py-1.5 text-left text-text-tertiary">Progress</div>
|
||||
<div class="px-3 py-1.5 text-left text-text-tertiary">Status</div>
|
||||
<div class="relative py-1.5 pl-3 pr-4 sm:pr-6 lg:pr-8 3xl:pr-12">
|
||||
<span class="sr-only">Edit</span>
|
||||
</div>
|
||||
</TableHeading>
|
||||
</template>
|
||||
|
||||
<style scoped></style>
|
||||
|
||||
@@ -95,24 +95,20 @@ const tableData = computed(() => {
|
||||
return (
|
||||
aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
|
||||
return {
|
||||
key: entry.key,
|
||||
seconds: entry.seconds,
|
||||
cost: entry.cost,
|
||||
description: getNameForReportingRowEntry(
|
||||
entry.key,
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? null,
|
||||
organization?.value?.date_format
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? null
|
||||
),
|
||||
grouped_data:
|
||||
entry.grouped_data?.map((el) => {
|
||||
return {
|
||||
key: el.key,
|
||||
seconds: el.seconds,
|
||||
cost: el.cost,
|
||||
description: getNameForReportingRowEntry(
|
||||
el.key,
|
||||
entry.grouped_type ?? null,
|
||||
organization?.value?.date_format
|
||||
entry.grouped_type ?? null
|
||||
),
|
||||
};
|
||||
}) ?? [],
|
||||
@@ -168,7 +164,7 @@ const showBillableRate = computed(() => {
|
||||
">
|
||||
<ReportingRow
|
||||
v-for="entry in tableData"
|
||||
:key="entry.key ?? 'none'"
|
||||
:key="entry.description ?? 'none'"
|
||||
:currency="getOrganizationCurrencyString()"
|
||||
:show-cost="showBillableRate"
|
||||
:entry="entry"></ReportingRow>
|
||||
|
||||
@@ -13,14 +13,12 @@ import {
|
||||
planMoveInsert,
|
||||
planSplitEntry,
|
||||
type BreakPlacementRequest,
|
||||
type Interval,
|
||||
} from '@/utils/timesheet/breakPlacementMath';
|
||||
import { BREAK_GAP_TOLERANCE_MINUTES } from '@/packages/ui/src/utils/breakPlacement';
|
||||
|
||||
const props = defineProps<{
|
||||
request: BreakPlacementRequest | null;
|
||||
apply: (breakStart: string, durationSeconds: number) => Promise<void>;
|
||||
entryLabel: (id: string) => string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ cancel: [] }>();
|
||||
@@ -56,11 +54,7 @@ const durationSeconds = computed(() =>
|
||||
|
||||
const splitPlan = computed(() => {
|
||||
if (!props.request || mode.value !== 'split' || durationSeconds.value <= 0) return null;
|
||||
return planSplitEntry(props.request.workEntries[0]!, durationSeconds.value, utcStart.value, {
|
||||
dayStart: props.request.dayStart,
|
||||
dayEnd: props.request.dayEnd,
|
||||
otherEntries: props.request.otherEntries,
|
||||
});
|
||||
return planSplitEntry(props.request.workEntries[0]!, durationSeconds.value, utcStart.value);
|
||||
});
|
||||
|
||||
const movePlan = computed(() => {
|
||||
@@ -122,43 +116,31 @@ function fmt(iso: string): string {
|
||||
const explanation = computed(() => {
|
||||
if (!props.request) return '';
|
||||
return mode.value === 'split'
|
||||
? "There's no free gap that fits this break, so the work entry will be split around it. The work moves to make room and keeps its full length."
|
||||
? "There's no free gap that fits this break, so the work entry will be split and the break placed inside it."
|
||||
: "There's no free gap that fits this break, so the surrounding entries will be shifted to make room.";
|
||||
});
|
||||
|
||||
interface PlanLine {
|
||||
times: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
const changeSummary = computed<PlanLine[]>(() => {
|
||||
const req = props.request;
|
||||
if (!req) return [];
|
||||
const range = (interval: Interval) => `${fmt(interval.start)}–${fmt(interval.end)}`;
|
||||
const moved = (from: Interval, to: Interval) => `${range(from)} → ${range(to)}`;
|
||||
|
||||
// Human-readable summary of what will change, so the user can confirm the edit.
|
||||
const changeSummary = computed<string[]>(() => {
|
||||
if (mode.value === 'split') {
|
||||
const plan = splitPlan.value;
|
||||
if (!plan) return [];
|
||||
const workLabel = props.entryLabel(req.workEntries[0]!.id);
|
||||
return [
|
||||
{ times: range(plan.firstHalf), label: workLabel },
|
||||
{ times: range(plan.breakSlot), label: 'Break' },
|
||||
{ times: range(plan.secondHalf), label: workLabel },
|
||||
...plan.shifted.map((shift) => ({
|
||||
times: moved(req.otherEntries.find((e) => e.id === shift.id)!, shift),
|
||||
label: props.entryLabel(shift.id),
|
||||
})),
|
||||
`${fmt(plan.firstHalf.start)}–${fmt(plan.firstHalf.end)} (work)`,
|
||||
`${fmt(plan.breakSlot.start)}–${fmt(plan.breakSlot.end)} (break)`,
|
||||
`${fmt(plan.secondHalf.start)}–${fmt(plan.secondHalf.end)} (work)`,
|
||||
];
|
||||
}
|
||||
const plan = movePlan.value;
|
||||
if (!plan) return [];
|
||||
if (plan.shifted.length === 0) return [{ times: 'No entries need to move.', label: '' }];
|
||||
if (plan.shifted.length === 0) return ['No entries need to move.'];
|
||||
return plan.shifted.map((shift) => {
|
||||
const isBreak = props.request!.otherEntries.some((e) => e.id === shift.id);
|
||||
const original =
|
||||
req.workEntries.find((e) => e.id === shift.id) ??
|
||||
req.otherEntries.find((e) => e.id === shift.id)!;
|
||||
return { times: moved(original, shift), label: props.entryLabel(shift.id) };
|
||||
props.request!.workEntries.find((e) => e.id === shift.id) ??
|
||||
props.request!.otherEntries.find((e) => e.id === shift.id)!;
|
||||
const label = `${fmt(original.start)}–${fmt(original.end)} → ${fmt(shift.start)}–${fmt(shift.end)}`;
|
||||
return isBreak ? `${label} (break)` : label;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -200,14 +182,8 @@ async function submit() {
|
||||
<div class="text-xs uppercase tracking-wide text-text-tertiary">
|
||||
{{ mode === 'split' ? 'Result' : 'Entries that move' }}
|
||||
</div>
|
||||
<div
|
||||
v-for="(line, index) in changeSummary"
|
||||
:key="index"
|
||||
class="flex items-baseline gap-2">
|
||||
<span class="tabular-nums whitespace-nowrap">{{ line.times }}</span>
|
||||
<span v-if="line.label" class="text-text-tertiary truncate">
|
||||
{{ line.label }}
|
||||
</span>
|
||||
<div v-for="(line, index) in changeSummary" :key="index" class="tabular-nums">
|
||||
{{ line }}
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
@@ -226,7 +202,7 @@ async function submit() {
|
||||
class="rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-600 dark:text-red-400">
|
||||
{{
|
||||
mode === 'split'
|
||||
? "This break doesn't fit there. It has to sit inside the work, leaving at least a minute of work on each side, and the work around it has to stay inside the day."
|
||||
? "This break doesn't fit there — it must lie inside the work entry, leaving at least a minute of work on each side."
|
||||
: "This break doesn't fit at that time without pushing an entry outside the day. Try a shorter break or a different time."
|
||||
}}
|
||||
</div>
|
||||
|
||||
@@ -11,8 +11,8 @@ import ClientCreateModal from '@/Components/Common/Client/ClientCreateModal.vue'
|
||||
import PageTitle from '@/Components/Common/PageTitle.vue';
|
||||
import { canCreateClients } from '@/utils/permissions';
|
||||
import { TabBar, TabBarItem } from '@/packages/ui/src';
|
||||
import { useTableSortState } from '@/utils/useTableSortState';
|
||||
import type { SortColumn } from '@/Components/Common/Client/ClientTable.vue';
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Client/ClientTable.vue';
|
||||
|
||||
const { clients } = useClientsQuery();
|
||||
|
||||
@@ -20,10 +20,25 @@ const activeTab = ref<'active' | 'archived'>('active');
|
||||
|
||||
const createClient = ref(false);
|
||||
|
||||
const { tableState, handleSort } = useTableSortState<SortColumn>('client-table-state', {
|
||||
sortColumn: 'name',
|
||||
sortDirection: 'asc',
|
||||
});
|
||||
interface ClientTableState {
|
||||
sortColumn: SortColumn;
|
||||
sortDirection: SortDirection;
|
||||
}
|
||||
|
||||
const tableState = useStorage<ClientTableState>(
|
||||
'client-table-state',
|
||||
{
|
||||
sortColumn: 'name',
|
||||
sortDirection: 'asc',
|
||||
},
|
||||
undefined,
|
||||
{ mergeDefaults: true }
|
||||
);
|
||||
|
||||
function handleSort(column: SortColumn, direction: SortDirection) {
|
||||
tableState.value.sortColumn = column;
|
||||
tableState.value.sortDirection = direction;
|
||||
}
|
||||
|
||||
const shownClients = computed(() => {
|
||||
return clients.value.filter((client) => {
|
||||
|
||||
@@ -12,8 +12,8 @@ import type { Role } from '@/types/jetstream';
|
||||
import PageTitle from '@/Components/Common/PageTitle.vue';
|
||||
import InvitationTable from '@/Components/Common/Invitation/InvitationTable.vue';
|
||||
import { canCreateInvitations } from '@/utils/permissions';
|
||||
import { useTableSortState } from '@/utils/useTableSortState';
|
||||
import type { SortColumn } from '@/Components/Common/Member/MemberTable.vue';
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Member/MemberTable.vue';
|
||||
|
||||
const inviteMember = ref(false);
|
||||
|
||||
@@ -23,10 +23,25 @@ defineProps<{
|
||||
|
||||
const activeTab = ref<'all' | 'invitations'>('all');
|
||||
|
||||
const { tableState, handleSort } = useTableSortState<SortColumn>('member-table-state', {
|
||||
sortColumn: 'name',
|
||||
sortDirection: 'asc',
|
||||
});
|
||||
interface MemberTableState {
|
||||
sortColumn: SortColumn;
|
||||
sortDirection: SortDirection;
|
||||
}
|
||||
|
||||
const tableState = useStorage<MemberTableState>(
|
||||
'member-table-state',
|
||||
{
|
||||
sortColumn: 'name',
|
||||
sortDirection: 'asc',
|
||||
},
|
||||
undefined,
|
||||
{ mergeDefaults: true }
|
||||
);
|
||||
|
||||
function handleSort(column: SortColumn, direction: SortDirection) {
|
||||
tableState.value.sortColumn = column;
|
||||
tableState.value.sortDirection = direction;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import TaskCreateModal from '@/Components/Common/Task/TaskCreateModal.vue';
|
||||
import TaskTable from '@/Components/Common/Task/TaskTable.vue';
|
||||
import type { SortColumn } from '@/Components/Common/Task/TaskTable.vue';
|
||||
import CardTitle from '@/packages/ui/src/CardTitle.vue';
|
||||
import Card from '@/Components/Common/Card.vue';
|
||||
import ProjectMemberTable from '@/Components/Common/ProjectMember/ProjectMemberTable.vue';
|
||||
@@ -30,7 +29,6 @@ import { formatCents } from '../packages/ui/src/utils/money';
|
||||
import { getOrganizationCurrencyString } from '../utils/money';
|
||||
import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
|
||||
import { getCurrentOrganizationId } from '@/utils/useUser';
|
||||
import { useTableSortState } from '@/utils/useTableSortState';
|
||||
|
||||
const { projects } = useProjectsQuery();
|
||||
|
||||
@@ -67,11 +65,6 @@ const activeTab = ref<'active' | 'done'>('active');
|
||||
|
||||
const { tasks } = useTasksQuery();
|
||||
|
||||
const { tableState, handleSort } = useTableSortState<SortColumn>('task-table-state', {
|
||||
sortColumn: 'name',
|
||||
sortDirection: 'asc',
|
||||
});
|
||||
|
||||
const shownTasks = computed(() => {
|
||||
return tasks.value.filter((task) => {
|
||||
if (activeTab.value === 'active') {
|
||||
@@ -166,12 +159,7 @@ const shownTasks = computed(() => {
|
||||
</template>
|
||||
</CardTitle>
|
||||
<Card>
|
||||
<TaskTable
|
||||
:tasks="shownTasks"
|
||||
:project-id="projectId"
|
||||
:sort-column="tableState.sortColumn"
|
||||
:sort-direction="tableState.sortDirection"
|
||||
@sort="handleSort"></TaskTable>
|
||||
<TaskTable :tasks="shownTasks" :project-id="projectId"></TaskTable>
|
||||
</Card>
|
||||
</div>
|
||||
<div v-if="canViewProjectMembers()">
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import AppLayout from '@/Layouts/AppLayout.vue';
|
||||
import MainContainer from '@/packages/ui/src/MainContainer.vue';
|
||||
import AppLayout from '@/Layouts/AppLayout.vue';
|
||||
import { FolderIcon, PlusIcon } from '@heroicons/vue/20/solid';
|
||||
import { Search } from '@lucide/vue';
|
||||
import SecondaryButton from '@/packages/ui/src/Buttons/SecondaryButton.vue';
|
||||
import ProjectTable from '@/Components/Common/Project/ProjectTable.vue';
|
||||
import TextInput from '@/packages/ui/src/Input/TextInput.vue';
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed } from 'vue';
|
||||
import { useProjectsQuery } from '@/utils/useProjectsQuery';
|
||||
import { useProjectsStore } from '@/utils/useProjects';
|
||||
import ProjectCreateModal from '@/packages/ui/src/Project/ProjectCreateModal.vue';
|
||||
@@ -20,7 +18,6 @@ import { getCurrentOrganizationId, getCurrentRole } from '@/utils/useUser';
|
||||
import { useOrganizationQuery } from '@/utils/useOrganizationQuery';
|
||||
import { isAllowedToPerformPremiumAction } from '@/utils/billing';
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import { useTableSortState } from '@/utils/useTableSortState';
|
||||
import ProjectsFilterDropdown from '@/Components/Common/Project/ProjectsFilterDropdown.vue';
|
||||
import ProjectStatusFilterBadge from '@/Components/Common/Project/ProjectStatusFilterBadge.vue';
|
||||
import ProjectVisibilityFilterBadge from '@/Components/Common/Project/ProjectVisibilityFilterBadge.vue';
|
||||
@@ -29,7 +26,7 @@ import { NO_CLIENT_ID } from '@/Components/Common/Project/constants';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Project/ProjectTable.vue';
|
||||
|
||||
// Fetch data using TanStack Query
|
||||
const { projects, isLoading: projectsLoading } = useProjectsQuery();
|
||||
const { projects } = useProjectsQuery();
|
||||
const { clients } = useClientsQuery();
|
||||
const { organization } = useOrganizationQuery(getCurrentOrganizationId()!);
|
||||
|
||||
@@ -44,7 +41,7 @@ interface ProjectTableState {
|
||||
};
|
||||
}
|
||||
|
||||
const { tableState, handleSort } = useTableSortState<SortColumn, ProjectTableState>(
|
||||
const tableState = useStorage<ProjectTableState>(
|
||||
'project-table-state',
|
||||
{
|
||||
sortColumn: 'name',
|
||||
@@ -55,28 +52,24 @@ const { tableState, handleSort } = useTableSortState<SortColumn, ProjectTableSta
|
||||
visibility: 'all',
|
||||
},
|
||||
},
|
||||
// The filters are merged key by key so a stored value missing a newer filter still
|
||||
// picks up its default instead of the whole object falling back.
|
||||
(storage, defaults) => ({
|
||||
...defaults,
|
||||
...storage,
|
||||
filters: { ...defaults.filters, ...storage.filters },
|
||||
})
|
||||
undefined,
|
||||
{
|
||||
mergeDefaults: (storage, defaults) => ({
|
||||
...defaults,
|
||||
...storage,
|
||||
filters: { ...defaults.filters, ...storage.filters },
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
// Not persisted, so a reload never starts silently filtered
|
||||
const search = ref('');
|
||||
function handleSort(column: SortColumn, direction: SortDirection) {
|
||||
tableState.value.sortColumn = column;
|
||||
tableState.value.sortDirection = direction;
|
||||
}
|
||||
|
||||
// Filter projects based on current filters
|
||||
const filteredProjects = computed(() => {
|
||||
const searchTerm = search.value.trim().toLowerCase();
|
||||
|
||||
return projects.value.filter((project) => {
|
||||
// Name search
|
||||
if (searchTerm && !project.name.toLowerCase().includes(searchTerm)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Status filter
|
||||
if (tableState.value.filters.status === 'active' && project.is_archived) {
|
||||
return false;
|
||||
@@ -110,15 +103,6 @@ const filteredProjects = computed(() => {
|
||||
});
|
||||
});
|
||||
|
||||
const hasActiveFilters = computed(() => {
|
||||
return (
|
||||
search.value.trim() !== '' ||
|
||||
tableState.value.filters.status !== 'all' ||
|
||||
tableState.value.filters.visibility !== 'all' ||
|
||||
tableState.value.filters.clientIds.length > 0
|
||||
);
|
||||
});
|
||||
|
||||
// Helper functions for active filters
|
||||
function removeStatusFilter() {
|
||||
tableState.value.filters.status = 'all';
|
||||
@@ -151,7 +135,8 @@ const showBillableRate = computed(() => {
|
||||
|
||||
<template>
|
||||
<AppLayout title="Projects" data-testid="projects_view">
|
||||
<MainContainer class="py-3 sm:pt-5 flex justify-between items-center">
|
||||
<MainContainer
|
||||
class="py-3 sm:pt-5 border-b border-default-background-separator flex justify-between items-center">
|
||||
<div class="flex items-center space-x-3 sm:space-x-6">
|
||||
<PageTitle :icon="FolderIcon" title="Projects"></PageTitle>
|
||||
</div>
|
||||
@@ -204,25 +189,11 @@ const showBillableRate = computed(() => {
|
||||
:clients="clients"
|
||||
@remove="removeClientFilter"
|
||||
@update:value="tableState.filters.clientIds = $event as string[]" />
|
||||
|
||||
<div class="relative">
|
||||
<Search
|
||||
class="pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-icon-default" />
|
||||
<TextInput
|
||||
v-model="search"
|
||||
size="sm"
|
||||
type="search"
|
||||
aria-label="Search projects"
|
||||
placeholder="Search projects..."
|
||||
class="w-60 border-transparent bg-transparent pl-7 shadow-none placeholder:text-text-tertiary hover:bg-black/5 focus-visible:bg-input-background dark:hover:bg-white/5 [&::-webkit-search-cancel-button]:hidden" />
|
||||
</div>
|
||||
</div>
|
||||
</MainContainer>
|
||||
|
||||
<ProjectTable
|
||||
:show-billable-rate="showBillableRate"
|
||||
:is-filtered="hasActiveFilters"
|
||||
:is-loading="projectsLoading"
|
||||
:projects="filteredProjects"
|
||||
:sort-column="tableState.sortColumn"
|
||||
:sort-direction="tableState.sortDirection"
|
||||
|
||||
@@ -116,43 +116,25 @@ const subGroup = computed(() => {
|
||||
}
|
||||
return 'project';
|
||||
});
|
||||
const { emptyPlaceholder, getNameForReportingRowEntry } = useReportingStore();
|
||||
|
||||
/**
|
||||
* The public report endpoint has no descriptor for time group types, so their labels are
|
||||
* derived from the raw group key.
|
||||
*/
|
||||
function resolveLabel(
|
||||
description: string | null | undefined,
|
||||
key: string | null | undefined,
|
||||
groupedType: string
|
||||
) {
|
||||
if (description !== null && description !== undefined) {
|
||||
return description;
|
||||
}
|
||||
return (
|
||||
getNameForReportingRowEntry(key ?? null, groupedType, reportDateFormat.value) ??
|
||||
emptyPlaceholder[groupedType] ??
|
||||
''
|
||||
);
|
||||
}
|
||||
const { emptyPlaceholder } = useReportingStore();
|
||||
|
||||
const groupedPieChartData = computed(() => {
|
||||
return (
|
||||
aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
|
||||
const groupedType = aggregatedTableTimeEntries.value?.grouped_type ?? 'project';
|
||||
const name = resolveLabel(entry.description, entry.key, groupedType);
|
||||
if (name === emptyPlaceholder[groupedType]) {
|
||||
if (entry.description === null) {
|
||||
return {
|
||||
value: entry.seconds,
|
||||
name: name,
|
||||
name:
|
||||
emptyPlaceholder[
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? 'project'
|
||||
] ?? '',
|
||||
color: '#CCCCCC',
|
||||
};
|
||||
}
|
||||
return {
|
||||
value: entry.seconds,
|
||||
name: name,
|
||||
color: entry.color ?? getRandomColorWithSeed(name),
|
||||
name: entry.description,
|
||||
color: entry.color ?? getRandomColorWithSeed(entry.description ?? 'none'),
|
||||
};
|
||||
}) ?? []
|
||||
);
|
||||
@@ -161,25 +143,21 @@ const groupedPieChartData = computed(() => {
|
||||
const tableData = computed(() => {
|
||||
return aggregatedTableTimeEntries.value?.grouped_data?.map((entry) => {
|
||||
return {
|
||||
key: entry.key,
|
||||
seconds: entry.seconds,
|
||||
cost: entry.cost,
|
||||
description: resolveLabel(
|
||||
entry.description,
|
||||
entry.key,
|
||||
aggregatedTableTimeEntries.value?.grouped_type ?? 'project'
|
||||
),
|
||||
description:
|
||||
entry.description ??
|
||||
emptyPlaceholder[aggregatedTableTimeEntries.value?.grouped_type ?? 'project'] ??
|
||||
'',
|
||||
grouped_data:
|
||||
entry.grouped_data?.map((el) => {
|
||||
return {
|
||||
key: el.key,
|
||||
seconds: el.seconds,
|
||||
cost: el.cost,
|
||||
description: resolveLabel(
|
||||
el.description,
|
||||
el.key,
|
||||
entry.grouped_type ?? 'project'
|
||||
),
|
||||
description:
|
||||
el.description ??
|
||||
emptyPlaceholder[entry.grouped_type ?? 'project'] ??
|
||||
'',
|
||||
};
|
||||
}) ?? [],
|
||||
};
|
||||
@@ -241,7 +219,7 @@ onMounted(async () => {
|
||||
">
|
||||
<ReportingRow
|
||||
v-for="entry in tableData"
|
||||
:key="entry.key ?? 'none'"
|
||||
:key="entry.description ?? 'none'"
|
||||
:currency="reportCurrency"
|
||||
:currency-format="reportCurrencyFormat"
|
||||
:show-cost="true"
|
||||
|
||||
@@ -9,15 +9,30 @@ import TagCreateModal from '@/packages/ui/src/Tag/TagCreateModal.vue';
|
||||
import PageTitle from '@/Components/Common/PageTitle.vue';
|
||||
import { canCreateTags } from '@/utils/permissions';
|
||||
import { useTagsStore } from '@/utils/useTags';
|
||||
import { useTableSortState } from '@/utils/useTableSortState';
|
||||
import type { SortColumn } from '@/Components/Common/Tag/TagTable.vue';
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import type { SortColumn, SortDirection } from '@/Components/Common/Tag/TagTable.vue';
|
||||
|
||||
const showCreateTagModal = ref(false);
|
||||
|
||||
const { tableState, handleSort } = useTableSortState<SortColumn>('tag-table-state', {
|
||||
sortColumn: 'name',
|
||||
sortDirection: 'asc',
|
||||
});
|
||||
interface TagTableState {
|
||||
sortColumn: SortColumn;
|
||||
sortDirection: SortDirection;
|
||||
}
|
||||
|
||||
const tableState = useStorage<TagTableState>(
|
||||
'tag-table-state',
|
||||
{
|
||||
sortColumn: 'name',
|
||||
sortDirection: 'asc',
|
||||
},
|
||||
undefined,
|
||||
{ mergeDefaults: true }
|
||||
);
|
||||
|
||||
function handleSort(column: SortColumn, direction: SortDirection) {
|
||||
tableState.value.sortColumn = column;
|
||||
tableState.value.sortDirection = direction;
|
||||
}
|
||||
|
||||
async function createTag(tag: string) {
|
||||
return await useTagsStore().createTag(tag);
|
||||
|
||||
@@ -198,7 +198,7 @@ const showResultModal = ref(false);
|
||||
for="file-upload"
|
||||
class="relative cursor-pointer rounded-md font-semibold text-text-primary focus-within:outline-none focus-within:ring-2 focus-within:ring-indigo-600 focus-within:ring-offset-2 focus-within:ring-offset-gray-900 hover:text-indigo-500">
|
||||
<span v-if="files">{{ filenames }}</span>
|
||||
<span v-else>Upload the Export file</span>
|
||||
<span v-else>Upload a Toggl/Clockify Export</span>
|
||||
<input
|
||||
id="file-upload"
|
||||
ref="importFile"
|
||||
|
||||
@@ -125,24 +125,7 @@ const {
|
||||
breakPlacementRequest,
|
||||
applyBreakPlacement,
|
||||
dismissBreakPlacement,
|
||||
} = useTimesheetCellMutations(
|
||||
weekDays,
|
||||
allTimeEntries,
|
||||
rows,
|
||||
removeSlot,
|
||||
() => organization.value?.prevent_overlapping_time_entries ?? false
|
||||
);
|
||||
|
||||
function breakPlanEntryLabel(id: string): string {
|
||||
const entry = allTimeEntries.value.find((e) => e.id === id);
|
||||
if (!entry) return '';
|
||||
if (entry.type === 'break') return 'Break';
|
||||
const project = projects.value.find((p) => p.id === entry.project_id);
|
||||
const task = tasks.value.find((t) => t.id === entry.task_id);
|
||||
return [project?.name ?? 'No Project', task?.name, entry.description]
|
||||
.filter((part): part is string => !!part)
|
||||
.join(' · ');
|
||||
}
|
||||
} = useTimesheetCellMutations(weekDays, allTimeEntries, rows, removeSlot);
|
||||
|
||||
// Local dates (YYYY-MM-DD) that have a misplaced break. There is only one break
|
||||
// row, so a flat set is enough — its cells show a warning for dates in the set.
|
||||
@@ -268,7 +251,6 @@ async function createTag(name: string): Promise<Tag | undefined> {
|
||||
<BreakPlacementModal
|
||||
:request="breakPlacementRequest"
|
||||
:apply="applyBreakPlacement"
|
||||
:entry-label="breakPlanEntryLabel"
|
||||
@cancel="dismissBreakPlacement" />
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
||||
@@ -25,21 +25,25 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
<template>
|
||||
<DialogPortal>
|
||||
<DialogOverlay
|
||||
class="fixed top-0 left-0 z-50 w-screen h-screen [height:100dvh] backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0">
|
||||
class="fixed inset-0 z-50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0">
|
||||
<div class="absolute inset-0 bg-default-background opacity-30" />
|
||||
<div
|
||||
class="absolute inset-0 overflow-y-auto overscroll-contain flex items-start justify-center px-2">
|
||||
<DialogContent
|
||||
v-bind="forwarded"
|
||||
:class="
|
||||
cn(
|
||||
'my-3 md:my-14 xl:my-24 bg-default-background grid w-full max-w-lg border border-border-tertiary shadow-lg duration-200 rounded-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
props.class
|
||||
)
|
||||
">
|
||||
<slot />
|
||||
</DialogContent>
|
||||
</div>
|
||||
</DialogOverlay>
|
||||
<div
|
||||
:class="
|
||||
cn(
|
||||
'fixed top-0 left-0 z-50 pointer-events-none w-screen h-screen flex items-start px-2 pt-3 md:pt-14 xl:pt-24 justify-center overflow-auto'
|
||||
)
|
||||
">
|
||||
<DialogContent
|
||||
v-bind="forwarded"
|
||||
:class="
|
||||
cn(
|
||||
'pointer-events-auto bg-default-background grid w-full max-w-lg border border-border-tertiary shadow-lg duration-200 rounded-lg outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95',
|
||||
props.class
|
||||
)
|
||||
">
|
||||
<slot />
|
||||
</DialogContent>
|
||||
</div>
|
||||
</DialogPortal>
|
||||
</template>
|
||||
|
||||
@@ -2,31 +2,14 @@ import { describe, expect, it } from 'vitest';
|
||||
import type { TimeEntry } from '@/packages/api/src';
|
||||
import {
|
||||
findMisplacedBreak,
|
||||
getBreakPlacementHint,
|
||||
type BreakPlacementHint,
|
||||
} from '@/packages/ui/src/utils/breakPlacement';
|
||||
|
||||
function entry(
|
||||
id: string,
|
||||
start: string,
|
||||
end: string | null,
|
||||
type: 'work' | 'break' = 'work'
|
||||
): TimeEntry {
|
||||
return {
|
||||
id,
|
||||
type,
|
||||
start,
|
||||
end,
|
||||
duration: end ? (Date.parse(end) - Date.parse(start)) / 1000 : null,
|
||||
organization_id: 'organization-1',
|
||||
user_id: 'user-1',
|
||||
member_id: 'member-1',
|
||||
project_id: type === 'break' ? null : 'project-1',
|
||||
task_id: null,
|
||||
billable: false,
|
||||
description: null,
|
||||
tags: [],
|
||||
};
|
||||
// Decision logic behind the aggregate (collapsed grouped-break) row's placement
|
||||
// warning: the row shows the hint — and navigates the calendar — based on the
|
||||
// first misplaced break in the group.
|
||||
function breakEntry(id: string): TimeEntry {
|
||||
return { id, type: 'break', start: '2026-07-14T10:00:00Z' } as TimeEntry;
|
||||
}
|
||||
|
||||
function hint(misplaced: boolean): BreakPlacementHint {
|
||||
@@ -41,99 +24,34 @@ function hint(misplaced: boolean): BreakPlacementHint {
|
||||
|
||||
describe('findMisplacedBreak', () => {
|
||||
it('returns the first misplaced break in a group', () => {
|
||||
const entries = [
|
||||
entry('break-a', '2026-07-14T10:00:00Z', '2026-07-14T10:30:00Z', 'break'),
|
||||
entry('break-b', '2026-07-14T12:00:00Z', '2026-07-14T12:30:00Z', 'break'),
|
||||
];
|
||||
const entries = [breakEntry('break-a'), breakEntry('break-b')];
|
||||
const result = findMisplacedBreak(entries, {
|
||||
'break-a': hint(false),
|
||||
'break-b': hint(true),
|
||||
});
|
||||
expect(result?.id).toBe('break-b');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBreakPlacementHint', () => {
|
||||
const breakEntry = entry('break', '2026-07-14T12:00:00Z', '2026-07-14T12:30:00Z', 'break');
|
||||
|
||||
it('accepts work touching both sides of the break', () => {
|
||||
const result = getBreakPlacementHint(breakEntry, [
|
||||
entry('morning', '2026-07-14T09:00:00Z', '2026-07-14T12:00:00Z'),
|
||||
entry('afternoon', '2026-07-14T12:30:00Z', '2026-07-14T17:00:00Z'),
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
misplaced: false,
|
||||
gapBeforeSeconds: 0,
|
||||
gapAfterSeconds: 0,
|
||||
})
|
||||
);
|
||||
it('returns null when no break in the group is misplaced', () => {
|
||||
const entries = [breakEntry('break-a'), breakEntry('break-b')];
|
||||
const result = findMisplacedBreak(entries, {
|
||||
'break-a': hint(false),
|
||||
'break-b': hint(false),
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('accepts gaps exactly at the placement tolerance', () => {
|
||||
const result = getBreakPlacementHint(breakEntry, [
|
||||
entry('morning', '2026-07-14T09:00:00Z', '2026-07-14T11:30:00Z'),
|
||||
entry('afternoon', '2026-07-14T13:00:00Z', '2026-07-14T17:00:00Z'),
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
misplaced: false,
|
||||
gapBeforeSeconds: 30 * 60,
|
||||
gapAfterSeconds: 30 * 60,
|
||||
})
|
||||
);
|
||||
it('returns null when the group has no placement hints', () => {
|
||||
const entries = [breakEntry('break-a'), breakEntry('break-b')];
|
||||
expect(findMisplacedBreak(entries, {})).toBeNull();
|
||||
});
|
||||
|
||||
it('flags a completed break when work is missing on either side', () => {
|
||||
const noPreviousWork = getBreakPlacementHint(breakEntry, [
|
||||
entry('afternoon', '2026-07-14T12:30:00Z', '2026-07-14T17:00:00Z'),
|
||||
]);
|
||||
const noNextWork = getBreakPlacementHint(breakEntry, [
|
||||
entry('morning', '2026-07-14T09:00:00Z', '2026-07-14T12:00:00Z'),
|
||||
]);
|
||||
|
||||
expect(noPreviousWork).toEqual(
|
||||
expect.objectContaining({ misplaced: true, gapBeforeSeconds: null })
|
||||
);
|
||||
expect(noNextWork).toEqual(
|
||||
expect.objectContaining({ misplaced: true, gapAfterSeconds: null })
|
||||
);
|
||||
});
|
||||
|
||||
it('does not require work after a running break', () => {
|
||||
const runningBreak = entry('break', '2026-07-14T12:00:00Z', null, 'break');
|
||||
const result = getBreakPlacementHint(runningBreak, [
|
||||
entry('morning', '2026-07-14T09:00:00Z', '2026-07-14T12:00:00Z'),
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
misplaced: false,
|
||||
gapBeforeSeconds: 0,
|
||||
gapAfterSeconds: null,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('treats work overlapping the break as touching both sides', () => {
|
||||
const result = getBreakPlacementHint(breakEntry, [
|
||||
entry('overlapping', '2026-07-14T11:45:00Z', '2026-07-14T12:15:00Z'),
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
expect.objectContaining({
|
||||
misplaced: false,
|
||||
gapBeforeSeconds: 0,
|
||||
gapAfterSeconds: 0,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('returns null for work entries', () => {
|
||||
expect(
|
||||
getBreakPlacementHint(entry('work', '2026-07-14T09:00:00Z', '2026-07-14T10:00:00Z'), [])
|
||||
).toBeNull();
|
||||
it('ignores hints for entries that are not in the group', () => {
|
||||
const entries = [breakEntry('break-a')];
|
||||
const result = findMisplacedBreak(entries, {
|
||||
'break-a': hint(false),
|
||||
'break-elsewhere': hint(true),
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import {
|
||||
formatHumanReadableDuration,
|
||||
formatMonth,
|
||||
formatReportingDuration,
|
||||
formatWeekRange,
|
||||
} from './time';
|
||||
import { formatHumanReadableDuration, formatReportingDuration } from './time';
|
||||
|
||||
const seconds = 14 * 3600 + 45 * 60 + 6; // 14h 45m 06s
|
||||
|
||||
@@ -47,27 +42,3 @@ describe('formatReportingDuration', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatWeekRange', () => {
|
||||
test('renders the six days following the given first day of the week', () => {
|
||||
expect(formatWeekRange('2026-07-27', 'slash-separated-dd-mm-yyyy')).toBe(
|
||||
'27/07/2026 - 02/08/2026'
|
||||
);
|
||||
});
|
||||
|
||||
test('spans a month boundary', () => {
|
||||
expect(formatWeekRange('2026-07-27')).toBe('27.7.2026 - 2.8.2026');
|
||||
});
|
||||
|
||||
test('spans a year boundary', () => {
|
||||
expect(formatWeekRange('2025-12-29', 'slash-separated-dd-mm-yyyy')).toBe(
|
||||
'29/12/2025 - 04/01/2026'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatMonth', () => {
|
||||
test('renders the name of the month that the key covers', () => {
|
||||
expect(formatMonth('2001-02')).toBe('February 2001');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -236,24 +236,6 @@ export function formatWeek(date: string | null): string {
|
||||
return 'Week ' + getDayJsInstance()(date).week();
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns the range covered by the week starting on the given day.
|
||||
* @param date - first day of a week, in the format of 'YYYY-MM-DD'
|
||||
*/
|
||||
export function formatWeekRange(date: string, format?: DateFormat): string {
|
||||
const end = getDayJsInstance()(date).add(6, 'day').format('YYYY-MM-DD');
|
||||
return `${formatDate(date, format)} - ${formatDate(end, format)}`;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns the month that the given key falls in. There is no `DateFormat` variant for a
|
||||
* month, so this is not affected by the organization date format.
|
||||
* @param date - a month, in the format of 'YYYY-MM'
|
||||
*/
|
||||
export function formatMonth(date: string): string {
|
||||
return getDayJsInstance()(date).format('MMMM YYYY');
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns a human readable date format.
|
||||
* @param date - date in the format of 'YYYY-MM-DD'
|
||||
|
||||
@@ -4,9 +4,6 @@ import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
BREAK_GAP_TOLERANCE_SECONDS,
|
||||
buildDayPlacementContext,
|
||||
decideBreakPlacement,
|
||||
findAdjacentBreakSlot,
|
||||
findBreakSlotNearInDay,
|
||||
findValidBreakGap,
|
||||
findValidBreakGapNear,
|
||||
planMoveInsert,
|
||||
@@ -22,7 +19,6 @@ const HOUR = 3600;
|
||||
const DAY = '2026-07-14';
|
||||
const dayStart = `${DAY}T00:00:00Z`;
|
||||
const dayEnd = `${DAY}T24:00:00Z`;
|
||||
const MIDNIGHT = '2026-07-15T00:00:00Z';
|
||||
|
||||
function iv(startH: number, endH: number) {
|
||||
const h = (n: number) => {
|
||||
@@ -34,84 +30,6 @@ function iv(startH: number, endH: number) {
|
||||
return { start: h(startH), end: h(endH) };
|
||||
}
|
||||
|
||||
describe('decideBreakPlacement', () => {
|
||||
const context = (work: MovableInterval[] = []) => ({
|
||||
work,
|
||||
breaks: [],
|
||||
blocked: [],
|
||||
dayStart,
|
||||
dayEnd: MIDNIGHT,
|
||||
});
|
||||
const movable = (id: string, startH: number, endH: number): MovableInterval => ({
|
||||
id,
|
||||
...iv(startH, endH),
|
||||
});
|
||||
|
||||
it('returns a direct save when an existing gap fits', () => {
|
||||
const decision = decideBreakPlacement({
|
||||
date: DAY,
|
||||
durationSeconds: HOUR,
|
||||
context: context([movable('morning', 9, 12), movable('afternoon', 13, 17)]),
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
kind: 'save',
|
||||
slot: { start: `${DAY}T12:00:00Z`, end: `${DAY}T13:00:00Z` },
|
||||
});
|
||||
});
|
||||
|
||||
it('selects generic free-window placement for an empty day', () => {
|
||||
expect(
|
||||
decideBreakPlacement({
|
||||
date: DAY,
|
||||
durationSeconds: HOUR,
|
||||
context: context(),
|
||||
})
|
||||
).toEqual({ kind: 'place-in-free-window' });
|
||||
});
|
||||
|
||||
it('returns a modal request when work must be rearranged', () => {
|
||||
const decision = decideBreakPlacement({
|
||||
date: DAY,
|
||||
durationSeconds: HOUR,
|
||||
context: context([movable('work', 9, 17)]),
|
||||
});
|
||||
|
||||
expect(decision).toEqual(
|
||||
expect.objectContaining({
|
||||
kind: 'needs-input',
|
||||
request: expect.objectContaining({
|
||||
date: DAY,
|
||||
defaultBreakStart: `${DAY}T13:00:00Z`,
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('saves the break next to work too short to split', () => {
|
||||
const decision = decideBreakPlacement({
|
||||
date: DAY,
|
||||
durationSeconds: HALF_HOUR,
|
||||
context: context([movable('quick', 9, 9 + 1 / 60)]),
|
||||
});
|
||||
|
||||
expect(decision).toEqual({
|
||||
kind: 'save',
|
||||
slot: { start: `${DAY}T09:01:00Z`, end: `${DAY}T09:31:00Z` },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a day that cannot fit or rearrange the break', () => {
|
||||
expect(
|
||||
decideBreakPlacement({
|
||||
date: DAY,
|
||||
durationSeconds: HOUR,
|
||||
context: context([movable('all-day', 0, 24)]),
|
||||
})
|
||||
).toEqual({ kind: 'reject' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('findValidBreakGap', () => {
|
||||
it('centers the break in a gap that fits within tolerance', () => {
|
||||
// 09-12 and 13-17 → 1h gap, 30m break → centered at 12:15-12:45
|
||||
@@ -188,197 +106,53 @@ describe('findValidBreakGap', () => {
|
||||
});
|
||||
|
||||
describe('planSplitEntry', () => {
|
||||
const workSeconds = (plan: NonNullable<ReturnType<typeof planSplitEntry>>) =>
|
||||
dayjs.utc(plan.firstHalf.end).diff(dayjs.utc(plan.firstHalf.start), 'second') +
|
||||
dayjs.utc(plan.secondHalf.end).diff(dayjs.utc(plan.secondHalf.start), 'second');
|
||||
|
||||
it('splits a single entry in the middle and keeps the work length', () => {
|
||||
it('splits a single entry and centers the break', () => {
|
||||
const plan = planSplitEntry(iv(9, 17), HALF_HOUR);
|
||||
expect(plan).not.toBeNull();
|
||||
expect(plan!.firstHalf.start).toBe(`${DAY}T09:00:00Z`);
|
||||
expect(plan!.breakSlot.start).toBe(plan!.firstHalf.end);
|
||||
expect(plan!.secondHalf.start).toBe(plan!.breakSlot.end);
|
||||
expect(plan!.breakSlot).toEqual({ start: `${DAY}T13:00:00Z`, end: `${DAY}T13:30:00Z` });
|
||||
expect(plan!.secondHalf.end).toBe(`${DAY}T17:30:00Z`);
|
||||
expect(workSeconds(plan!)).toBe(8 * HOUR);
|
||||
});
|
||||
|
||||
it('accepts a break far longer than the work entry', () => {
|
||||
const plan = planSplitEntry(iv(9, 9.5), 4 * HOUR);
|
||||
expect(plan).not.toBeNull();
|
||||
expect(plan!.firstHalf).toEqual({ start: `${DAY}T09:00:00Z`, end: `${DAY}T09:15:00Z` });
|
||||
expect(plan!.breakSlot).toEqual({ start: `${DAY}T09:15:00Z`, end: `${DAY}T13:15:00Z` });
|
||||
expect(plan!.secondHalf).toEqual({ start: `${DAY}T13:15:00Z`, end: `${DAY}T13:30:00Z` });
|
||||
expect(workSeconds(plan!)).toBe(HALF_HOUR);
|
||||
expect(plan!.secondHalf.end).toBe(`${DAY}T17:00:00Z`);
|
||||
// break is 30m and centered → 12:45-13:15
|
||||
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:45:00Z`, end: `${DAY}T13:15:00Z` });
|
||||
});
|
||||
|
||||
it('honors an explicit break start', () => {
|
||||
const plan = planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T10:00:00Z`);
|
||||
expect(plan!.firstHalf).toEqual({ start: `${DAY}T09:00:00Z`, end: `${DAY}T10:00:00Z` });
|
||||
expect(plan!.breakSlot).toEqual({ start: `${DAY}T10:00:00Z`, end: `${DAY}T10:30:00Z` });
|
||||
expect(plan!.secondHalf).toEqual({ start: `${DAY}T10:30:00Z`, end: `${DAY}T17:30:00Z` });
|
||||
expect(workSeconds(plan!)).toBe(8 * HOUR);
|
||||
expect(plan!.secondHalf.start).toBe(`${DAY}T10:30:00Z`);
|
||||
});
|
||||
|
||||
it('returns null when the entry is too short to leave work on both sides', () => {
|
||||
expect(
|
||||
planSplitEntry({ start: `${DAY}T09:00:00Z`, end: `${DAY}T09:01:30Z` }, HALF_HOUR)
|
||||
).toBeNull();
|
||||
expect(planSplitEntry(iv(9, 9.25), HALF_HOUR)).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects an explicit break start before the entry instead of clamping it', () => {
|
||||
// 07:00 lies before the 09:00-17:00 entry — relocating it silently would
|
||||
// leave a hair-thin first fragment at a time the user never picked.
|
||||
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T07:00:00Z`)).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects an explicit break start at or after the end of the entry', () => {
|
||||
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T17:00:00Z`)).toBeNull();
|
||||
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T18:00:00Z`)).toBeNull();
|
||||
it('rejects an explicit break start whose break would reach past the entry end', () => {
|
||||
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T16:45:00Z`)).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects an explicit break start that leaves less than the minimum fragment', () => {
|
||||
// 09:00:30 would leave only 30s of work before the break.
|
||||
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T09:00:30Z`)).toBeNull();
|
||||
expect(planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T16:59:30Z`)).toBeNull();
|
||||
});
|
||||
|
||||
it('accepts an explicit break start leaving exactly the minimum fragment on each side', () => {
|
||||
const plan = planSplitEntry(iv(9, 9 + 2 / 60), HALF_HOUR, `${DAY}T09:01:00Z`);
|
||||
// 09:01 leaves 60s before; on a 09:00-09:32 entry a 30m break also leaves 60s after.
|
||||
const plan = planSplitEntry(iv(9, 9 + 32 / 60), HALF_HOUR, `${DAY}T09:01:00Z`);
|
||||
expect(plan).not.toBeNull();
|
||||
expect(plan!.firstHalf).toEqual({ start: `${DAY}T09:00:00Z`, end: `${DAY}T09:01:00Z` });
|
||||
expect(plan!.secondHalf).toEqual({ start: `${DAY}T09:31:00Z`, end: `${DAY}T09:32:00Z` });
|
||||
});
|
||||
|
||||
it('leaves later entries alone when the extended work does not reach them', () => {
|
||||
const plan = planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T12:00:00Z`, {
|
||||
otherEntries: [
|
||||
{ id: 'early', ...iv(8, 8.5) },
|
||||
{ id: 'later', ...iv(18, 19) },
|
||||
],
|
||||
});
|
||||
expect(plan!.secondHalf).toEqual({ start: `${DAY}T12:30:00Z`, end: `${DAY}T17:30:00Z` });
|
||||
expect(plan!.shifted).toEqual([]);
|
||||
});
|
||||
|
||||
it('pushes only the collision chain and preserves later entry times', () => {
|
||||
const plan = planSplitEntry(iv(9, 17), HALF_HOUR, `${DAY}T12:00:00Z`, {
|
||||
otherEntries: [
|
||||
{ id: 'first', ...iv(17.25, 17.5) },
|
||||
{ id: 'second', ...iv(17.6, 17.9) },
|
||||
{ id: 'distant', ...iv(20, 21) },
|
||||
],
|
||||
});
|
||||
|
||||
// Moving the first break also collides with the second.
|
||||
expect(plan!.shifted).toEqual([
|
||||
{ id: 'first', ...iv(17.5, 17.75) },
|
||||
{ id: 'second', ...iv(17.75, 18.05) },
|
||||
]);
|
||||
});
|
||||
|
||||
it('starts the work earlier when pushing it later would leave the day', () => {
|
||||
const plan = planSplitEntry(iv(22, 23.5), HOUR, undefined, { dayStart, dayEnd });
|
||||
expect(plan).not.toBeNull();
|
||||
expect(plan!.firstHalf).toEqual({ start: `${DAY}T21:30:00Z`, end: `${DAY}T22:15:00Z` });
|
||||
expect(plan!.breakSlot).toEqual({ start: `${DAY}T22:15:00Z`, end: `${DAY}T23:15:00Z` });
|
||||
expect(plan!.secondHalf).toEqual({ start: `${DAY}T23:15:00Z`, end: MIDNIGHT });
|
||||
expect(workSeconds(plan!)).toBe(1.5 * HOUR);
|
||||
});
|
||||
|
||||
it('reproduces its own plan when re-planned from the break start it chose', () => {
|
||||
const options = { dayStart, dayEnd };
|
||||
const suggested = planSplitEntry(iv(22, 23.5), HOUR, undefined, options);
|
||||
const replanned = planSplitEntry(iv(22, 23.5), HOUR, suggested!.breakSlot.start, options);
|
||||
expect(replanned).toEqual(suggested);
|
||||
});
|
||||
|
||||
it('returns null when the block cannot fit in the day at all', () => {
|
||||
expect(planSplitEntry(iv(0, 23), 2 * HOUR, undefined, { dayStart, dayEnd })).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when starting earlier would run into an entry that stays put', () => {
|
||||
expect(
|
||||
planSplitEntry(iv(22, 23.75), HOUR, undefined, {
|
||||
dayStart,
|
||||
dayEnd,
|
||||
otherEntries: [{ id: 'earlier', ...iv(21, 21.5) }],
|
||||
})
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when the actual collision chain would leave the day', () => {
|
||||
expect(
|
||||
planSplitEntry(iv(22, 23.5), HOUR, undefined, {
|
||||
dayStart,
|
||||
dayEnd,
|
||||
otherEntries: [{ id: 'late', ...iv(23.75, 24) }],
|
||||
})
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('does not reject a valid split because of an unrelated late entry', () => {
|
||||
const plan = planSplitEntry(iv(9, 10), HOUR, `${DAY}T09:30:00Z`, {
|
||||
dayStart,
|
||||
dayEnd,
|
||||
otherEntries: [{ id: 'late', ...iv(23.5, 24) }],
|
||||
});
|
||||
|
||||
expect(plan).not.toBeNull();
|
||||
expect(plan!.secondHalf.end).toBe(`${DAY}T11:00:00Z`);
|
||||
expect(plan!.shifted).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findBreakSlotNearInDay', () => {
|
||||
const anchor = `${DAY}T23:00:00Z`;
|
||||
|
||||
it('keeps the break where it is when the new duration still fits', () => {
|
||||
expect(findBreakSlotNearInDay(dayStart, dayEnd, HALF_HOUR, anchor)).toEqual({
|
||||
start: anchor,
|
||||
end: `${DAY}T23:30:00Z`,
|
||||
});
|
||||
});
|
||||
|
||||
it('slides the break earlier instead of growing past midnight', () => {
|
||||
expect(findBreakSlotNearInDay(dayStart, dayEnd, 2 * HOUR, anchor)).toEqual({
|
||||
start: `${DAY}T22:00:00Z`,
|
||||
end: MIDNIGHT,
|
||||
});
|
||||
});
|
||||
|
||||
it('respects a day window shortened by a running entry', () => {
|
||||
expect(findBreakSlotNearInDay(dayStart, `${DAY}T12:00:00Z`, HOUR, anchor)).toEqual({
|
||||
start: `${DAY}T11:00:00Z`,
|
||||
end: `${DAY}T12:00:00Z`,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when the day has no free window big enough', () => {
|
||||
expect(findBreakSlotNearInDay(dayStart, dayEnd, 20 * HOUR, anchor, [iv(6, 18)])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('findAdjacentBreakSlot', () => {
|
||||
it('parks the break flush after the last work entry', () => {
|
||||
expect(findAdjacentBreakSlot([iv(9, 9.5)], dayStart, dayEnd, HALF_HOUR)).toEqual({
|
||||
start: `${DAY}T09:30:00Z`,
|
||||
end: `${DAY}T10:00:00Z`,
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to flush before the first work entry', () => {
|
||||
expect(findAdjacentBreakSlot([iv(9, 24)], dayStart, dayEnd, HALF_HOUR)).toEqual({
|
||||
start: `${DAY}T08:30:00Z`,
|
||||
end: `${DAY}T09:00:00Z`,
|
||||
});
|
||||
});
|
||||
|
||||
it('skips a candidate blocked by an existing break', () => {
|
||||
expect(
|
||||
findAdjacentBreakSlot([iv(9, 24)], dayStart, dayEnd, HALF_HOUR, [iv(8.75, 9)])
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when neither side fits inside the day', () => {
|
||||
expect(findAdjacentBreakSlot([iv(0, 24)], dayStart, dayEnd, HALF_HOUR)).toBeNull();
|
||||
it('returns null when the entry cannot hold the break plus a minimum fragment per side', () => {
|
||||
// 31 minutes of work cannot hold a 30m break with 60s of work on each side.
|
||||
expect(planSplitEntry(iv(9, 9 + 31 / 60), HALF_HOUR)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -405,6 +179,32 @@ describe('planMoveInsert', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('leaves an oversized gap alone instead of pulling the right block flush', () => {
|
||||
// 09-12 and 15-17 (3h gap). Break flush after first at 12:00 fits in the gap
|
||||
// → nothing moves; the user's gap is preserved.
|
||||
const plan = planMoveInsert(
|
||||
[movable('a', 9, 12), movable('b', 15, 17)],
|
||||
dayStart,
|
||||
dayEnd,
|
||||
`${DAY}T12:00:00Z`,
|
||||
HALF_HOUR
|
||||
);
|
||||
expect(plan!.breakSlot).toEqual({ start: `${DAY}T12:00:00Z`, end: `${DAY}T12:30:00Z` });
|
||||
expect(plan!.shifted).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not drag entries flush when the break sits mid-gap', () => {
|
||||
// Break at 13:00 in the middle of the 12:00-15:00 gap → neither side moves.
|
||||
const plan = planMoveInsert(
|
||||
[movable('a', 9, 12), movable('b', 15, 17)],
|
||||
dayStart,
|
||||
dayEnd,
|
||||
`${DAY}T13:00:00Z`,
|
||||
HALF_HOUR
|
||||
);
|
||||
expect(plan!.shifted).toEqual([]);
|
||||
});
|
||||
|
||||
it('shifts each side only as much as needed to clear the slot', () => {
|
||||
// Break 14:45-15:15 overlaps only the start of 'b' → 'b' pushed 15m later,
|
||||
// 'a' untouched.
|
||||
@@ -620,6 +420,12 @@ describe('findValidBreakGapNear', () => {
|
||||
expect(gap).toEqual({ start: `${DAY}T10:00:00Z`, end: `${DAY}T11:00:00Z` });
|
||||
});
|
||||
|
||||
it('clamps the anchor into the tolerance window when it sits too late', () => {
|
||||
// Anchored at 11:00 (beyond the window) → clamped back to 10:30.
|
||||
const gap = findValidBreakGapNear(work, HOUR, `${DAY}T11:00:00Z`);
|
||||
expect(gap).toEqual({ start: `${DAY}T10:30:00Z`, end: `${DAY}T11:30:00Z` });
|
||||
});
|
||||
|
||||
it('keeps the break in place inside an oversized gap', () => {
|
||||
// 09-10 and 14-15 → 4h gap. The break stays exactly where the user left it;
|
||||
// its distance from work is a soft hint, not a reason to move it.
|
||||
|
||||
@@ -40,8 +40,6 @@ export interface SplitPlan {
|
||||
firstHalf: Interval;
|
||||
breakSlot: Interval;
|
||||
secondHalf: Interval;
|
||||
// Entries pushed later to clear the extended second half.
|
||||
shifted: MovableInterval[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,79 +96,6 @@ export interface DayPlacementContext {
|
||||
dayEnd: string;
|
||||
}
|
||||
|
||||
export type BreakPlacementDecision =
|
||||
| { kind: 'save'; slot: Interval }
|
||||
| { kind: 'place-in-free-window' }
|
||||
| { kind: 'needs-input'; request: BreakPlacementRequest }
|
||||
| { kind: 'reject' };
|
||||
|
||||
/**
|
||||
* Decide how a requested break should be placed without performing any writes.
|
||||
* Keeping this policy pure lets the composable focus on UI state and persistence.
|
||||
*/
|
||||
export function decideBreakPlacement({
|
||||
date,
|
||||
durationSeconds,
|
||||
context,
|
||||
anchorStart = null,
|
||||
replaceBreakId = null,
|
||||
}: {
|
||||
date: string;
|
||||
durationSeconds: number;
|
||||
context: DayPlacementContext;
|
||||
anchorStart?: string | null;
|
||||
replaceBreakId?: string | null;
|
||||
}): BreakPlacementDecision {
|
||||
const { work, breaks, blocked, dayStart, dayEnd } = context;
|
||||
const obstacles = [...breaks, ...blocked];
|
||||
const gap =
|
||||
(anchorStart !== null
|
||||
? findValidBreakGapNear(work, durationSeconds, anchorStart, obstacles)
|
||||
: null) ?? findValidBreakGap(work, durationSeconds, obstacles);
|
||||
|
||||
if (gap) return { kind: 'save', slot: gap };
|
||||
|
||||
if (work.length === 0) {
|
||||
if (anchorStart === null) return { kind: 'place-in-free-window' };
|
||||
const slot = findBreakSlotNearInDay(
|
||||
dayStart,
|
||||
dayEnd,
|
||||
durationSeconds,
|
||||
anchorStart,
|
||||
obstacles
|
||||
);
|
||||
return slot ? { kind: 'save', slot } : { kind: 'reject' };
|
||||
}
|
||||
|
||||
const defaultPlan =
|
||||
work.length === 1
|
||||
? planSplitEntry(work[0]!, durationSeconds, undefined, {
|
||||
dayStart,
|
||||
dayEnd,
|
||||
otherEntries: breaks,
|
||||
})
|
||||
: suggestMovePlan(work, dayStart, dayEnd, durationSeconds, breaks);
|
||||
|
||||
if (!defaultPlan) {
|
||||
const adjacent = findAdjacentBreakSlot(work, dayStart, dayEnd, durationSeconds, obstacles);
|
||||
return adjacent ? { kind: 'save', slot: adjacent } : { kind: 'reject' };
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'needs-input',
|
||||
request: {
|
||||
date,
|
||||
durationSeconds,
|
||||
dayStart,
|
||||
dayEnd,
|
||||
workEntries: work,
|
||||
otherEntries: breaks,
|
||||
defaultBreakStart: defaultPlan.breakSlot.start,
|
||||
replaceBreakId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildDayPlacementContext(
|
||||
entries: DayEntryLike[],
|
||||
dayStart: string,
|
||||
@@ -244,14 +169,6 @@ function toIntervalMs(interval: Interval): IntervalMs {
|
||||
};
|
||||
}
|
||||
|
||||
function slotAt(startMs: number, durationMs: number): Interval {
|
||||
const dayjs = getDayJsInstance();
|
||||
return {
|
||||
start: dayjs.utc(startMs).format(),
|
||||
end: dayjs.utc(startMs + durationMs).format(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge overlapping/touching work intervals so the space between two
|
||||
* consecutive merged intervals is genuinely work-free. Without this, an entry
|
||||
@@ -301,12 +218,17 @@ export function findValidBreakGap(
|
||||
toleranceSeconds: number = BREAK_GAP_TOLERANCE_SECONDS
|
||||
): Interval | null {
|
||||
if (durationSeconds <= 0) return null;
|
||||
const dayjs = getDayJsInstance();
|
||||
const durationMs = durationSeconds * 1000;
|
||||
const gaps = workFreeGapsMs(work);
|
||||
const obstaclesMs = obstacles.map(toIntervalMs);
|
||||
|
||||
const blockers = (startMs: number): IntervalMs[] =>
|
||||
obstaclesMs.filter((o) => startMs < o.endMs && o.startMs < startMs + durationMs);
|
||||
const slot = (startMs: number): Interval => ({
|
||||
start: dayjs.utc(startMs).format(),
|
||||
end: dayjs.utc(startMs + durationMs).format(),
|
||||
});
|
||||
|
||||
// Pass 1: a gap where the centered break keeps both sides within tolerance.
|
||||
for (const gap of gaps) {
|
||||
@@ -314,7 +236,7 @@ export function findValidBreakGap(
|
||||
if (gapMs < durationMs || gapMs > durationMs + 2 * toleranceSeconds * 1000) continue;
|
||||
const startMs = gap.startMs + Math.floor((gapMs - durationMs) / 2000) * 1000;
|
||||
if (blockers(startMs).length > 0) continue;
|
||||
return slotAt(startMs, durationMs);
|
||||
return slot(startMs);
|
||||
}
|
||||
|
||||
// Pass 2: any gap that can physically hold the break. Start flush after the
|
||||
@@ -323,7 +245,7 @@ export function findValidBreakGap(
|
||||
let startMs = gap.startMs;
|
||||
while (startMs + durationMs <= gap.endMs) {
|
||||
const blocking = blockers(startMs);
|
||||
if (blocking.length === 0) return slotAt(startMs, durationMs);
|
||||
if (blocking.length === 0) return slot(startMs);
|
||||
startMs = Math.max(...blocking.map((o) => o.endMs));
|
||||
}
|
||||
}
|
||||
@@ -352,198 +274,98 @@ export function findValidBreakGapNear(
|
||||
const dayjs = getDayJsInstance();
|
||||
const durationMs = durationSeconds * 1000;
|
||||
const anchorMs = dayjs.utc(anchorStart).valueOf();
|
||||
const obstaclesMs = obstacles.map(toIntervalMs);
|
||||
|
||||
for (const gap of workFreeGapsMs(work)) {
|
||||
// The anchor must fall inside this gap for it to be "where the break is".
|
||||
if (anchorMs < gap.startMs || anchorMs >= gap.endMs) continue;
|
||||
const best = closestFreeStartMs(gap, durationMs, anchorMs, obstaclesMs);
|
||||
if (gap.endMs - gap.startMs < durationMs) return null;
|
||||
|
||||
// Walk the gap's free windows around obstacles and pick the start
|
||||
// closest to the anchor, so the break moves as little as possible
|
||||
// from where the user left it.
|
||||
const blockers = obstacles
|
||||
.map(toIntervalMs)
|
||||
.filter((o) => o.startMs < gap.endMs && o.endMs > gap.startMs)
|
||||
.sort((a, b) => a.startMs - b.startMs);
|
||||
let best: number | null = null;
|
||||
const consider = (winStartMs: number, winEndMs: number) => {
|
||||
if (winEndMs - winStartMs < durationMs) return;
|
||||
const candidate = Math.min(Math.max(anchorMs, winStartMs), winEndMs - durationMs);
|
||||
if (best === null || Math.abs(candidate - anchorMs) < Math.abs(best - anchorMs)) {
|
||||
best = candidate;
|
||||
}
|
||||
};
|
||||
let cursor = gap.startMs;
|
||||
for (const blocker of blockers) {
|
||||
consider(cursor, blocker.startMs);
|
||||
cursor = Math.max(cursor, blocker.endMs);
|
||||
}
|
||||
consider(cursor, gap.endMs);
|
||||
|
||||
if (best === null) return null;
|
||||
return slotAt(best, durationMs);
|
||||
return { start: dayjs.utc(best).format(), end: dayjs.utc(best + durationMs).format() };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Closest obstacle-free start to `anchorMs` that fits inside `range`. */
|
||||
function closestFreeStartMs(
|
||||
range: IntervalMs,
|
||||
durationMs: number,
|
||||
anchorMs: number,
|
||||
obstaclesMs: IntervalMs[]
|
||||
): number | null {
|
||||
if (range.endMs - range.startMs < durationMs) return null;
|
||||
const blockers = obstaclesMs
|
||||
.filter((o) => o.startMs < range.endMs && o.endMs > range.startMs)
|
||||
.sort((a, b) => a.startMs - b.startMs);
|
||||
|
||||
let best: number | null = null;
|
||||
const consider = (winStartMs: number, winEndMs: number) => {
|
||||
if (winEndMs - winStartMs < durationMs) return;
|
||||
const candidate = Math.min(Math.max(anchorMs, winStartMs), winEndMs - durationMs);
|
||||
if (best === null || Math.abs(candidate - anchorMs) < Math.abs(best - anchorMs)) {
|
||||
best = candidate;
|
||||
}
|
||||
};
|
||||
let cursor = range.startMs;
|
||||
for (const blocker of blockers) {
|
||||
consider(cursor, blocker.startMs);
|
||||
cursor = Math.max(cursor, blocker.endMs);
|
||||
}
|
||||
consider(cursor, range.endMs);
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Keep a workless-day break near its current start without leaving the day. */
|
||||
export function findBreakSlotNearInDay(
|
||||
dayStart: string,
|
||||
dayEnd: string,
|
||||
durationSeconds: number,
|
||||
anchorStart: string,
|
||||
obstacles: Interval[] = []
|
||||
): Interval | null {
|
||||
if (durationSeconds <= 0) return null;
|
||||
const dayjs = getDayJsInstance();
|
||||
const durationMs = durationSeconds * 1000;
|
||||
const range = {
|
||||
startMs: dayjs.utc(dayStart).valueOf(),
|
||||
endMs: dayjs.utc(dayEnd).valueOf(),
|
||||
};
|
||||
const best = closestFreeStartMs(
|
||||
range,
|
||||
durationMs,
|
||||
dayjs.utc(anchorStart).valueOf(),
|
||||
obstacles.map(toIntervalMs)
|
||||
);
|
||||
if (best === null) return null;
|
||||
return slotAt(best, durationMs);
|
||||
}
|
||||
|
||||
// A split must leave a meaningful chunk of work on each side of the break;
|
||||
// hair-thin fragments would only exist to make a bad placement "fit".
|
||||
export const MIN_SPLIT_FRAGMENT_SECONDS = 60;
|
||||
|
||||
export interface SplitOptions {
|
||||
// Omitted bounds are unbounded.
|
||||
dayStart?: string;
|
||||
dayEnd?: string;
|
||||
// Existing breaks that may block or move with the split.
|
||||
otherEntries?: MovableInterval[];
|
||||
}
|
||||
|
||||
/** Insert a break while preserving work duration and respecting the supplied bounds. */
|
||||
/**
|
||||
* Split a single work entry to insert a break. `breakStart` (UTC ISO) lets the
|
||||
* caller position it; without one the break is centered. Returns null when the
|
||||
* entry is too short to leave at least MIN_SPLIT_FRAGMENT_SECONDS of work on
|
||||
* both sides of the break, or when an explicit `breakStart` would not — an
|
||||
* out-of-range request is rejected rather than clamped, because silently
|
||||
* relocating the break would contradict the time the user picked.
|
||||
*/
|
||||
export function planSplitEntry(
|
||||
entry: Interval,
|
||||
durationSeconds: number,
|
||||
breakStart?: string,
|
||||
options: SplitOptions = {}
|
||||
breakStart?: string
|
||||
): SplitPlan | null {
|
||||
if (durationSeconds <= 0) return null;
|
||||
const dayjs = getDayJsInstance();
|
||||
const toMs = (iso: string) => dayjs.utc(iso).valueOf();
|
||||
const iso = (ms: number) => dayjs.utc(ms).format();
|
||||
const entryStart = dayjs.utc(entry.start);
|
||||
const entryEnd = dayjs.utc(entry.end);
|
||||
const total = entryEnd.diff(entryStart, 'second');
|
||||
if (total < durationSeconds + 2 * MIN_SPLIT_FRAGMENT_SECONDS) return null;
|
||||
|
||||
const entryStartMs = toMs(entry.start);
|
||||
const totalMs = toMs(entry.end) - entryStartMs;
|
||||
const minMs = MIN_SPLIT_FRAGMENT_SECONDS * 1000;
|
||||
if (totalMs < 2 * minMs) return null;
|
||||
const durationMs = durationSeconds * 1000;
|
||||
const dayEndMs = options.dayEnd !== undefined ? toMs(options.dayEnd) : Infinity;
|
||||
const earliest = entryStart.add(MIN_SPLIT_FRAGMENT_SECONDS, 'second');
|
||||
const latest = entryEnd.subtract(durationSeconds + MIN_SPLIT_FRAGMENT_SECONDS, 'second');
|
||||
|
||||
// Pull the block earlier only enough to keep it inside the day.
|
||||
const blockStartMs = Math.min(entryStartMs, dayEndMs - totalMs - durationMs);
|
||||
let bStart = breakStart
|
||||
? dayjs.utc(breakStart)
|
||||
: entryStart.add(Math.floor((total - durationSeconds) / 2), 'second');
|
||||
|
||||
let bStartMs = breakStart ? toMs(breakStart) : blockStartMs + Math.floor(totalMs / 2000) * 1000;
|
||||
if (breakStart) {
|
||||
if (bStartMs < blockStartMs + minMs || bStartMs > blockStartMs + totalMs - minMs) {
|
||||
return null;
|
||||
}
|
||||
if (bStart.isBefore(earliest) || bStart.isAfter(latest)) return null;
|
||||
} else {
|
||||
// Safety net for rounding of the centered position only.
|
||||
bStartMs = Math.min(
|
||||
Math.max(bStartMs, blockStartMs + minMs),
|
||||
blockStartMs + totalMs - minMs
|
||||
);
|
||||
}
|
||||
const bEndMs = bStartMs + durationMs;
|
||||
const firstHalfMs = bStartMs - blockStartMs;
|
||||
|
||||
const secondHalfEndMs = bEndMs + totalMs - firstHalfMs;
|
||||
|
||||
// Carry the occupied end through the collision chain; stop at the first gap.
|
||||
const others = options.otherEntries ?? [];
|
||||
const later = others
|
||||
.filter((other) => toMs(other.start) >= bStartMs)
|
||||
.sort((a, b) => toMs(a.start) - toMs(b.start));
|
||||
const shifted: MovableInterval[] = [];
|
||||
let occupiedEndMs = secondHalfEndMs;
|
||||
for (const other of later) {
|
||||
const otherStartMs = toMs(other.start);
|
||||
if (otherStartMs >= occupiedEndMs) break;
|
||||
|
||||
const otherEndMs = toMs(other.end);
|
||||
const shiftMs = occupiedEndMs - otherStartMs;
|
||||
const shiftedEndMs = otherEndMs + shiftMs;
|
||||
if (shiftedEndMs > dayEndMs) return null;
|
||||
shifted.push({
|
||||
id: other.id,
|
||||
start: iso(otherStartMs + shiftMs),
|
||||
end: iso(shiftedEndMs),
|
||||
});
|
||||
occupiedEndMs = shiftedEndMs;
|
||||
if (bStart.isBefore(earliest)) bStart = earliest;
|
||||
if (bStart.isAfter(latest)) bStart = latest;
|
||||
}
|
||||
|
||||
// Earlier breaks constrain how far the block may move back.
|
||||
let earliestStartMs = options.dayStart !== undefined ? toMs(options.dayStart) : -Infinity;
|
||||
for (const other of others) {
|
||||
const otherEndMs = toMs(other.end);
|
||||
if (
|
||||
toMs(other.start) < bStartMs &&
|
||||
otherEndMs <= bStartMs &&
|
||||
otherEndMs > earliestStartMs
|
||||
) {
|
||||
earliestStartMs = otherEndMs;
|
||||
}
|
||||
}
|
||||
if (blockStartMs < earliestStartMs) return null;
|
||||
const bEnd = bStart.add(durationSeconds, 'second');
|
||||
if (!bStart.isAfter(entryStart) || !bEnd.isBefore(entryEnd)) return null;
|
||||
|
||||
return {
|
||||
firstHalf: { start: iso(blockStartMs), end: iso(bStartMs) },
|
||||
breakSlot: { start: iso(bStartMs), end: iso(bEndMs) },
|
||||
secondHalf: { start: iso(bEndMs), end: iso(secondHalfEndMs) },
|
||||
shifted,
|
||||
firstHalf: { start: entryStart.format(), end: bStart.format() },
|
||||
breakSlot: { start: bStart.format(), end: bEnd.format() },
|
||||
secondHalf: { start: bEnd.format(), end: entryEnd.format() },
|
||||
};
|
||||
}
|
||||
|
||||
/** Last resort: place the break after the last work entry or before the first. */
|
||||
export function findAdjacentBreakSlot(
|
||||
work: Interval[],
|
||||
dayStart: string,
|
||||
dayEnd: string,
|
||||
durationSeconds: number,
|
||||
obstacles: Interval[] = []
|
||||
): Interval | null {
|
||||
if (durationSeconds <= 0 || work.length === 0) return null;
|
||||
const dayjs = getDayJsInstance();
|
||||
const durationMs = durationSeconds * 1000;
|
||||
const dayStartMs = dayjs.utc(dayStart).valueOf();
|
||||
const dayEndMs = dayjs.utc(dayEnd).valueOf();
|
||||
|
||||
const merged = mergedWorkMs(work);
|
||||
const blockers = [...merged, ...obstacles.map(toIntervalMs)];
|
||||
const candidates = [merged[merged.length - 1]!.endMs, merged[0]!.startMs - durationMs];
|
||||
|
||||
for (const startMs of candidates) {
|
||||
if (startMs < dayStartMs || startMs + durationMs > dayEndMs) continue;
|
||||
const clear = blockers.every(
|
||||
(blocker) => blocker.endMs <= startMs || blocker.startMs >= startMs + durationMs
|
||||
);
|
||||
if (clear) return slotAt(startMs, durationMs);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a break by translating overlapping entries on either side just enough
|
||||
* to clear it. Existing gaps remain unchanged. Returns null if a shift would
|
||||
* leave the day.
|
||||
* Insert a break at `breakStart`, shifting the surrounding entries only as much
|
||||
* as needed to clear the slot. Entries starting before the break form the left
|
||||
* block: when it reaches into the slot it is translated earlier so its latest
|
||||
* end meets the break start. The rest form the right block: when the slot
|
||||
* reaches into it, it is translated later so its earliest start meets the break
|
||||
* end. Blocks that already clear the slot are left untouched — existing gaps
|
||||
* are preserved, never tightened. Returns null if a required shift would push
|
||||
* an entry outside `[dayStart, dayEnd]`.
|
||||
*/
|
||||
export function planMoveInsert(
|
||||
entries: MovableInterval[],
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { ref } from 'vue';
|
||||
import { createPinia, setActivePinia } from 'pinia';
|
||||
import { useBreakPlacement } from './useBreakPlacement';
|
||||
import { NoFreeWindowError } from './cellMath';
|
||||
import { useBreakPlacement, BreakPlacementDeferred } from './useBreakPlacement';
|
||||
import { api } from '@/packages/api/src';
|
||||
import type { TimeEntry } from '@/packages/api/src';
|
||||
import type { TimesheetRow } from '@/utils/useTimesheetGrid';
|
||||
|
||||
const addNotification = vi.fn();
|
||||
const mutationOptionsSpy = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock('@/utils/useUser', () => ({
|
||||
getCurrentOrganizationId: vi.fn(() => 'org-1'),
|
||||
@@ -17,28 +15,6 @@ vi.mock('@/utils/useUser', () => ({
|
||||
|
||||
vi.mock('@tanstack/vue-query', () => ({
|
||||
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
|
||||
useMutation: (options: {
|
||||
mutationFn: (variables: unknown) => Promise<unknown>;
|
||||
onSuccess?: (data: unknown, variables: unknown) => void | Promise<void>;
|
||||
onError?: (error: unknown, variables: unknown) => void | Promise<void>;
|
||||
onSettled?: () => void | Promise<void>;
|
||||
}) => {
|
||||
mutationOptionsSpy(options);
|
||||
return {
|
||||
mutateAsync: async (variables: unknown) => {
|
||||
try {
|
||||
const data = await options.mutationFn(variables);
|
||||
await options.onSuccess?.(data, variables);
|
||||
return data;
|
||||
} catch (error) {
|
||||
await options.onError?.(error, variables);
|
||||
throw error;
|
||||
} finally {
|
||||
await options.onSettled?.();
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/utils/notification', () => ({
|
||||
@@ -85,29 +61,24 @@ const breakRow: TimesheetRow = {
|
||||
totalSeconds: 0,
|
||||
};
|
||||
|
||||
function setup(allEntries: TimeEntry[], preventOverlaps = false) {
|
||||
function setup(allEntries: TimeEntry[]) {
|
||||
const createCell = vi.fn(async () => undefined);
|
||||
const updateEntry = vi.fn(async (_entry: TimeEntry) => undefined);
|
||||
const deleteEntry = vi.fn(async (_id: string) => undefined);
|
||||
const updateEntry = vi.fn(async () => undefined);
|
||||
const bp = useBreakPlacement({
|
||||
weekDays: ref([DATE, '2026-04-11', '2026-04-12']),
|
||||
timeEntries: ref(allEntries),
|
||||
requireOrgId: () => 'org-1',
|
||||
createCell,
|
||||
updateEntry,
|
||||
deleteEntry,
|
||||
preventOverlappingTimeEntries: () => preventOverlaps,
|
||||
});
|
||||
return { bp, createCell, updateEntry, deleteEntry };
|
||||
return { bp, createCell, updateEntry };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia());
|
||||
apiMocks.createTimeEntry.mockClear();
|
||||
apiMocks.updateTimeEntry.mockClear();
|
||||
apiMocks.deleteTimeEntry.mockClear();
|
||||
addNotification.mockClear();
|
||||
mutationOptionsSpy.mockClear();
|
||||
});
|
||||
|
||||
describe('useBreakPlacement.placeBreak', () => {
|
||||
@@ -155,36 +126,13 @@ describe('useBreakPlacement.placeBreak', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('drops a new break into the first free window when the day has no work', async () => {
|
||||
const { bp, createCell } = setup([]);
|
||||
await bp.placeBreak(breakRow, 0, HOUR);
|
||||
expect(createCell).toHaveBeenCalledWith(breakRow, 0, HOUR);
|
||||
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resizes a break on a workless day in place while it still fits', async () => {
|
||||
const brk = entry('2026-04-10T20:00:00Z', '2026-04-10T20:30:00Z', {
|
||||
id: 'b1',
|
||||
type: 'break',
|
||||
});
|
||||
const { bp, updateEntry } = setup([brk]);
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR, 'b1');
|
||||
|
||||
expect(updateEntry).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'b1',
|
||||
start: '2026-04-10T20:00:00Z',
|
||||
end: '2026-04-10T21:00:00Z',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('requests input in the split modal when a single work entry blocks every gap', async () => {
|
||||
it('defers to the split modal when a single work entry blocks every gap', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||
const { bp } = setup([work]);
|
||||
|
||||
await expect(bp.placeBreak(breakRow, 0, HOUR)).resolves.toBe('needs-input');
|
||||
await expect(bp.placeBreak(breakRow, 0, HOUR)).rejects.toBeInstanceOf(
|
||||
BreakPlacementDeferred
|
||||
);
|
||||
expect(bp.breakPlacementRequest.value).toEqual(
|
||||
expect.objectContaining({
|
||||
durationSeconds: HOUR,
|
||||
@@ -197,25 +145,15 @@ describe('useBreakPlacement.placeBreak', () => {
|
||||
});
|
||||
|
||||
describe('useBreakPlacement.applyBreakPlacement (split)', () => {
|
||||
it('configures the logical placement as a serialized, non-retrying mutation', () => {
|
||||
setup([]);
|
||||
|
||||
expect(mutationOptionsSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
mutationKey: ['timesheet', 'break-placement'],
|
||||
scope: { id: 'timesheet-break-placement' },
|
||||
retry: false,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('shrinks the original, pushes the rest of the work out, and saves the break', async () => {
|
||||
it('shrinks the original, creates the second half, and saves the break', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||
const { bp, updateEntry } = setup([work]);
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR);
|
||||
// Open the placement request, then commit the break at noon.
|
||||
await bp.placeBreak(breakRow, 0, HOUR).catch(() => undefined);
|
||||
await bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR);
|
||||
|
||||
// Original work shrunk to its first half.
|
||||
expect(updateEntry).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'w1',
|
||||
@@ -223,13 +161,14 @@ describe('useBreakPlacement.applyBreakPlacement (split)', () => {
|
||||
end: '2026-04-10T12:00:00Z',
|
||||
})
|
||||
);
|
||||
// Second half of work + the break both created.
|
||||
const created = apiMocks.createTimeEntry.mock.calls.map((c) => c[0]);
|
||||
expect(created).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: 'work',
|
||||
start: '2026-04-10T13:00:00Z',
|
||||
end: '2026-04-10T18:00:00Z',
|
||||
end: '2026-04-10T17:00:00Z',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: 'break',
|
||||
@@ -238,208 +177,14 @@ describe('useBreakPlacement.applyBreakPlacement (split)', () => {
|
||||
}),
|
||||
])
|
||||
);
|
||||
// Request cleared and a success toast surfaced.
|
||||
expect(bp.breakPlacementRequest.value).toBeNull();
|
||||
expect(addNotification).toHaveBeenCalledWith('success', 'Break added', expect.any(String));
|
||||
});
|
||||
|
||||
it('moves an existing break out of the way of the pushed-out work', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', { id: 'w1' });
|
||||
const existingBreak = entry('2026-04-10T12:00:00Z', '2026-04-10T12:15:00Z', {
|
||||
id: 'b1',
|
||||
type: 'break',
|
||||
});
|
||||
const { bp, updateEntry } = setup([work, existingBreak]);
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR);
|
||||
await bp.applyBreakPlacement('2026-04-10T10:00:00Z', HOUR);
|
||||
|
||||
expect(updateEntry).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
id: 'w1',
|
||||
start: '2026-04-10T09:00:00Z',
|
||||
end: '2026-04-10T10:00:00Z',
|
||||
})
|
||||
);
|
||||
expect(updateEntry).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
id: 'b1',
|
||||
start: '2026-04-10T13:00:00Z',
|
||||
end: '2026-04-10T13:15:00Z',
|
||||
})
|
||||
);
|
||||
const created = apiMocks.createTimeEntry.mock.calls.map((c) => c[0]);
|
||||
expect(created).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: 'work',
|
||||
start: '2026-04-10T11:00:00Z',
|
||||
end: '2026-04-10T13:00:00Z',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: 'break',
|
||||
start: '2026-04-10T10:00:00Z',
|
||||
end: '2026-04-10T11:00:00Z',
|
||||
}),
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('moves a replacement break before creating work through its old slot', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||
const existingBreak = entry('2026-04-10T17:00:00Z', '2026-04-10T17:30:00Z', {
|
||||
id: 'b1',
|
||||
type: 'break',
|
||||
});
|
||||
const { bp, updateEntry } = setup([work, existingBreak], true);
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR, 'b1');
|
||||
it('does nothing when there is no pending placement request', async () => {
|
||||
const { bp, updateEntry } = setup([]);
|
||||
await bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR);
|
||||
|
||||
expect(updateEntry).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({ id: 'w1', end: '2026-04-10T12:00:00Z' })
|
||||
);
|
||||
expect(updateEntry).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
id: 'b1',
|
||||
start: '2026-04-10T12:00:00Z',
|
||||
end: '2026-04-10T13:00:00Z',
|
||||
})
|
||||
);
|
||||
expect(apiMocks.createTimeEntry).toHaveBeenCalledTimes(1);
|
||||
expect(apiMocks.createTimeEntry.mock.calls[0]![0]).toEqual(
|
||||
expect.objectContaining({
|
||||
type: 'work',
|
||||
start: '2026-04-10T13:00:00Z',
|
||||
end: '2026-04-10T18:00:00Z',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('restores the original entry when creating the second half fails', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||
const { bp, updateEntry } = setup([work]);
|
||||
apiMocks.createTimeEntry.mockRejectedValueOnce(new Error('boom'));
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR);
|
||||
await expect(bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR)).rejects.toThrow('boom');
|
||||
|
||||
expect(updateEntry).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
id: 'w1',
|
||||
start: '2026-04-10T09:00:00Z',
|
||||
end: '2026-04-10T12:00:00Z',
|
||||
})
|
||||
);
|
||||
expect(updateEntry).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
id: 'w1',
|
||||
start: '2026-04-10T09:00:00Z',
|
||||
end: '2026-04-10T17:00:00Z',
|
||||
})
|
||||
);
|
||||
expect(addNotification).toHaveBeenCalledWith(
|
||||
'error',
|
||||
'Failed to add break',
|
||||
expect.any(String)
|
||||
);
|
||||
});
|
||||
|
||||
it('restores shifted breaks as well as the original when creating work fails', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', { id: 'w1' });
|
||||
const existingBreak = entry('2026-04-10T12:00:00Z', '2026-04-10T12:15:00Z', {
|
||||
id: 'b1',
|
||||
type: 'break',
|
||||
});
|
||||
const { bp, updateEntry } = setup([work, existingBreak]);
|
||||
apiMocks.createTimeEntry.mockRejectedValueOnce(new Error('work create failed'));
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR);
|
||||
await expect(bp.applyBreakPlacement('2026-04-10T10:00:00Z', HOUR)).rejects.toThrow(
|
||||
'work create failed'
|
||||
);
|
||||
|
||||
expect(updateEntry.mock.calls.map((call) => call[0])).toEqual([
|
||||
expect.objectContaining({ id: 'w1', end: '2026-04-10T10:00:00Z' }),
|
||||
expect.objectContaining({
|
||||
id: 'b1',
|
||||
start: '2026-04-10T13:00:00Z',
|
||||
end: '2026-04-10T13:15:00Z',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: 'b1',
|
||||
start: '2026-04-10T12:00:00Z',
|
||||
end: '2026-04-10T12:15:00Z',
|
||||
}),
|
||||
expect.objectContaining({ id: 'w1', end: '2026-04-10T12:00:00Z' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('deletes the created second half and restores updates when saving the break fails', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||
const { bp, updateEntry, deleteEntry } = setup([work]);
|
||||
apiMocks.createTimeEntry
|
||||
.mockResolvedValueOnce({ data: { id: 'second-half' } } as never)
|
||||
.mockRejectedValueOnce(new Error('break create failed'));
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR);
|
||||
await expect(bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR)).rejects.toThrow(
|
||||
'break create failed'
|
||||
);
|
||||
|
||||
expect(deleteEntry).toHaveBeenCalledWith('second-half');
|
||||
expect(updateEntry).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ id: 'w1', end: '2026-04-10T17:00:00Z' })
|
||||
);
|
||||
expect(bp.breakPlacementRequest.value).not.toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces incomplete recovery and closes a stale placement request', async () => {
|
||||
const work = entry('2026-04-10T09:00:00Z', '2026-04-10T17:00:00Z', { id: 'w1' });
|
||||
const { bp, updateEntry } = setup([work]);
|
||||
updateEntry
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new Error('restore failed'));
|
||||
apiMocks.createTimeEntry.mockRejectedValueOnce(new Error('create failed'));
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR);
|
||||
await expect(bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR)).rejects.toThrow(
|
||||
'create failed'
|
||||
);
|
||||
|
||||
expect(addNotification).toHaveBeenCalledWith(
|
||||
'error',
|
||||
'Break placement needs attention',
|
||||
expect.any(String)
|
||||
);
|
||||
expect(bp.breakPlacementRequest.value).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useBreakPlacement.applyBreakPlacement (move)', () => {
|
||||
it('rejects a replacement dependency cycle before changing any entry', async () => {
|
||||
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T12:00:00Z', {
|
||||
id: 'morning',
|
||||
});
|
||||
const afternoon = entry('2026-04-10T12:00:00Z', '2026-04-10T17:00:00Z', {
|
||||
id: 'afternoon',
|
||||
});
|
||||
const existingBreak = entry('2026-04-10T17:00:00Z', '2026-04-10T17:30:00Z', {
|
||||
id: 'b1',
|
||||
type: 'break',
|
||||
});
|
||||
const { bp, updateEntry } = setup([morning, afternoon, existingBreak], true);
|
||||
|
||||
await bp.placeBreak(breakRow, 0, HOUR, 'b1');
|
||||
await expect(bp.applyBreakPlacement('2026-04-10T12:00:00Z', HOUR)).rejects.toBeInstanceOf(
|
||||
NoFreeWindowError
|
||||
);
|
||||
|
||||
expect(updateEntry).not.toHaveBeenCalled();
|
||||
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ref, type Ref } from 'vue';
|
||||
import { useMutation, useQueryClient } from '@tanstack/vue-query';
|
||||
import { api, type CreateTimeEntryBody, type TimeEntry } from '@/packages/api/src';
|
||||
import { useQueryClient } from '@tanstack/vue-query';
|
||||
import { api, type TimeEntry } from '@/packages/api/src';
|
||||
import { getDayJsInstance } from '@/packages/ui/src/utils/time';
|
||||
import { getUserTimezone } from '@/packages/ui/src/utils/settings';
|
||||
import { getCurrentMembershipId } from '@/utils/useUser';
|
||||
import type { TimesheetRow } from '@/utils/useTimesheetGrid';
|
||||
@@ -8,15 +9,24 @@ import { useNotificationsStore } from '@/utils/notification';
|
||||
import { localDayBounds, NoFreeWindowError } from './cellMath';
|
||||
import {
|
||||
buildDayPlacementContext,
|
||||
decideBreakPlacement,
|
||||
findValidBreakGap,
|
||||
findValidBreakGapNear,
|
||||
placementMode,
|
||||
planMoveInsert,
|
||||
planSplitEntry,
|
||||
suggestMovePlan,
|
||||
type BreakPlacementRequest,
|
||||
type DayPlacementContext,
|
||||
type MovableInterval,
|
||||
} from './breakPlacementMath';
|
||||
|
||||
/** Signals the caller that a break create/edit is waiting on the placement modal. */
|
||||
export class BreakPlacementDeferred extends Error {
|
||||
constructor() {
|
||||
super('Break placement deferred to modal');
|
||||
this.name = 'BreakPlacementDeferred';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic entry primitives the break subsystem borrows from the cell-mutation
|
||||
* layer. `createCell` drops an entry in the first free window (used when there
|
||||
@@ -35,51 +45,17 @@ export interface BreakPlacementDeps {
|
||||
afterCursor?: string
|
||||
) => Promise<void>;
|
||||
updateEntry: (entry: TimeEntry) => Promise<void>;
|
||||
deleteEntry: (id: string) => Promise<void>;
|
||||
preventOverlappingTimeEntries?: () => boolean;
|
||||
}
|
||||
|
||||
interface EntryChange {
|
||||
original: TimeEntry;
|
||||
next: TimeEntry;
|
||||
}
|
||||
|
||||
interface PlacementCommit {
|
||||
updates: EntryChange[];
|
||||
creates: CreateTimeEntryBody[];
|
||||
entriesAdjusted: boolean;
|
||||
}
|
||||
|
||||
export type PlaceBreakResult = 'committed' | 'needs-input';
|
||||
|
||||
type UndoOperation = () => Promise<void>;
|
||||
|
||||
export class BreakPlacementSagaError extends Error {
|
||||
constructor(
|
||||
public readonly operationError: unknown,
|
||||
public readonly rollbackErrors: unknown[]
|
||||
) {
|
||||
super(operationError instanceof Error ? operationError.message : 'Break placement failed');
|
||||
this.name = 'BreakPlacementSagaError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Break-placement subsystem for the timesheet. Owns the placement-modal request
|
||||
* state and everything that positions a break relative to work — auto-placing it
|
||||
* into a valid gap when one exists, or asking for input in the split/move modal when the
|
||||
* into a valid gap when one exists, or deferring to the split/move modal when the
|
||||
* day has to be rearranged.
|
||||
*/
|
||||
export function useBreakPlacement(deps: BreakPlacementDeps) {
|
||||
const {
|
||||
weekDays,
|
||||
timeEntries,
|
||||
requireOrgId,
|
||||
createCell,
|
||||
updateEntry,
|
||||
deleteEntry,
|
||||
preventOverlappingTimeEntries = () => false,
|
||||
} = deps;
|
||||
const { weekDays, timeEntries, requireOrgId, createCell, updateEntry } = deps;
|
||||
const dayjs = getDayJsInstance();
|
||||
const queryClient = useQueryClient();
|
||||
const notifications = useNotificationsStore();
|
||||
|
||||
@@ -106,35 +82,24 @@ export function useBreakPlacement(deps: BreakPlacementDeps) {
|
||||
);
|
||||
}
|
||||
|
||||
function breakEntryBody(start: string, end: string, memberId?: string): CreateTimeEntryBody {
|
||||
async function createBreakEntry(start: string, end: string, memberId?: string): Promise<void> {
|
||||
const orgId = requireOrgId();
|
||||
const member = memberId ?? getCurrentMembershipId();
|
||||
if (!member) throw new Error('No member context');
|
||||
return {
|
||||
member_id: member,
|
||||
project_id: null,
|
||||
task_id: null,
|
||||
start,
|
||||
end,
|
||||
billable: false,
|
||||
type: 'break',
|
||||
description: null,
|
||||
tags: [],
|
||||
};
|
||||
}
|
||||
|
||||
async function createEntry(body: CreateTimeEntryBody): Promise<string> {
|
||||
const response = await api.createTimeEntry(body, {
|
||||
params: { organization: requireOrgId() },
|
||||
});
|
||||
return response.data.id;
|
||||
}
|
||||
|
||||
async function createBreakEntry(
|
||||
start: string,
|
||||
end: string,
|
||||
memberId?: string
|
||||
): Promise<string> {
|
||||
return createEntry(breakEntryBody(start, end, memberId));
|
||||
await api.createTimeEntry(
|
||||
{
|
||||
member_id: member,
|
||||
project_id: null,
|
||||
task_id: null,
|
||||
start,
|
||||
end,
|
||||
billable: false,
|
||||
type: 'break',
|
||||
description: null,
|
||||
tags: [],
|
||||
},
|
||||
{ params: { organization: orgId } }
|
||||
);
|
||||
}
|
||||
|
||||
async function saveBreakEntry(
|
||||
@@ -154,169 +119,116 @@ export function useBreakPlacement(deps: BreakPlacementDeps) {
|
||||
await createBreakEntry(start, end, memberId);
|
||||
}
|
||||
|
||||
/** Place or resize a break directly when possible, otherwise open the placement modal. */
|
||||
/**
|
||||
* Place a break on the day (new, or re-placing an existing one when `replaceBreakId`
|
||||
* is given). Prefers a gap that already satisfies the placement tolerance; otherwise
|
||||
* raises BreakPlacementDeferred so the page opens the modal. With no work to anchor to,
|
||||
* the break is just dropped in / resized in the first free window.
|
||||
*/
|
||||
async function placeBreak(
|
||||
row: TimesheetRow,
|
||||
dayIndex: number,
|
||||
durationSeconds: number,
|
||||
replaceBreakId?: string
|
||||
): Promise<PlaceBreakResult> {
|
||||
): Promise<void> {
|
||||
const date = weekDays.value[dayIndex]!;
|
||||
const tz = getUserTimezone();
|
||||
const context = dayPlacementContext(date, tz, replaceBreakId);
|
||||
const { work, breaks, blocked, dayStart, dayEnd } = dayPlacementContext(
|
||||
date,
|
||||
tz,
|
||||
replaceBreakId
|
||||
);
|
||||
// Existing breaks block auto-placement into a gap (obstacles), but move
|
||||
// along with the surrounding work when a move plan shifts entries.
|
||||
// Running entries block everything from their start (never movable).
|
||||
const obstacles = [...breaks, ...blocked];
|
||||
|
||||
// On edit, keep the break where it is when its current gap still fits it; only
|
||||
// fall back to the first-gap-centered placement when it can't stay put.
|
||||
const anchorStart = replaceBreakId
|
||||
? (timeEntries.value.find((e) => e.id === replaceBreakId)?.start ?? null)
|
||||
: null;
|
||||
const decision = decideBreakPlacement({
|
||||
const validGap =
|
||||
(anchorStart !== null
|
||||
? findValidBreakGapNear(work, durationSeconds, anchorStart, obstacles)
|
||||
: null) ?? findValidBreakGap(work, durationSeconds, obstacles);
|
||||
if (validGap) {
|
||||
await saveBreakEntry(validGap.start, validGap.end, replaceBreakId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (work.length === 0) {
|
||||
// No work to sit between: for an edit, resize the break in place; for a new
|
||||
// break, drop it in the first free window. Nothing to align to either way.
|
||||
if (replaceBreakId) {
|
||||
const existing = timeEntries.value.find((e) => e.id === replaceBreakId);
|
||||
if (existing) {
|
||||
const newEnd = dayjs
|
||||
.utc(existing.start)
|
||||
.add(durationSeconds, 'second')
|
||||
.format();
|
||||
await updateEntry({ ...existing, end: newEnd });
|
||||
return;
|
||||
}
|
||||
}
|
||||
await createCell(row, dayIndex, durationSeconds);
|
||||
return;
|
||||
}
|
||||
|
||||
const mode: 'split' | 'move' = work.length === 1 ? 'split' : 'move';
|
||||
const defaultBreakStart =
|
||||
mode === 'split'
|
||||
? (planSplitEntry(work[0]!, durationSeconds)?.breakSlot.start ?? null)
|
||||
: (suggestMovePlan(work, dayStart, dayEnd, durationSeconds, breaks)?.breakSlot
|
||||
.start ?? null);
|
||||
|
||||
if (!defaultBreakStart) {
|
||||
// Even splitting/moving can't open a slot on this day.
|
||||
throw new NoFreeWindowError(date, durationSeconds);
|
||||
}
|
||||
|
||||
breakPlacementRequest.value = {
|
||||
date,
|
||||
durationSeconds,
|
||||
context,
|
||||
anchorStart,
|
||||
replaceBreakId,
|
||||
});
|
||||
|
||||
switch (decision.kind) {
|
||||
case 'save':
|
||||
await saveBreakEntry(decision.slot.start, decision.slot.end, replaceBreakId);
|
||||
return 'committed';
|
||||
case 'place-in-free-window':
|
||||
await createCell(row, dayIndex, durationSeconds);
|
||||
return 'committed';
|
||||
case 'needs-input':
|
||||
breakPlacementRequest.value = decision.request;
|
||||
return 'needs-input';
|
||||
case 'reject':
|
||||
throw new NoFreeWindowError(date, durationSeconds);
|
||||
}
|
||||
dayStart,
|
||||
dayEnd,
|
||||
workEntries: work,
|
||||
otherEntries: breaks,
|
||||
defaultBreakStart,
|
||||
replaceBreakId: replaceBreakId ?? null,
|
||||
};
|
||||
throw new BreakPlacementDeferred();
|
||||
}
|
||||
|
||||
function dismissBreakPlacement(): void {
|
||||
breakPlacementRequest.value = null;
|
||||
}
|
||||
|
||||
function shiftChanges(shifted: MovableInterval[]): EntryChange[] {
|
||||
return shifted.map((shift) => {
|
||||
const original = timeEntries.value.find((e) => e.id === shift.id);
|
||||
if (!original) throw new Error('An entry to move no longer exists');
|
||||
return {
|
||||
original,
|
||||
next: { ...original, start: shift.start, end: shift.end },
|
||||
};
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Commit a break at `breakStart` by executing the split or move plan. Shifts
|
||||
* happen before the break is saved so its target slot is free first.
|
||||
*/
|
||||
async function applyBreakPlacement(breakStart: string, durationSeconds: number): Promise<void> {
|
||||
const req = breakPlacementRequest.value;
|
||||
if (!req) return;
|
||||
|
||||
function intervalsOverlap(
|
||||
left: Pick<TimeEntry, 'start' | 'end'>,
|
||||
right: Pick<TimeEntry, 'start' | 'end'>
|
||||
): boolean {
|
||||
const leftEndMs = left.end === null ? Infinity : Date.parse(left.end);
|
||||
const rightEndMs = right.end === null ? Infinity : Date.parse(right.end);
|
||||
return Date.parse(left.start) < rightEndMs && Date.parse(right.start) < leftEndMs;
|
||||
}
|
||||
// The timesheet is the current member's own, so all created/edited entries stay with them.
|
||||
const memberId = getCurrentMembershipId();
|
||||
if (!memberId) throw new Error('No member context');
|
||||
|
||||
/** Order updates so each target is free when overlap prevention is enabled. */
|
||||
function nonOverlappingUpdateOrder(
|
||||
changes: EntryChange[],
|
||||
memberId: string
|
||||
): EntryChange[] | null {
|
||||
if (!preventOverlappingTimeEntries()) return changes;
|
||||
|
||||
const current = new Map(
|
||||
timeEntries.value
|
||||
.filter((entry) => entry.member_id === memberId)
|
||||
.map((entry) => [entry.id, entry] as const)
|
||||
);
|
||||
const pending = [...changes];
|
||||
const ordered: EntryChange[] = [];
|
||||
|
||||
while (pending.length > 0) {
|
||||
const index = pending.findIndex((change) =>
|
||||
[...current.values()].every(
|
||||
(entry) =>
|
||||
entry.id === change.original.id || !intervalsOverlap(change.next, entry)
|
||||
)
|
||||
);
|
||||
if (index === -1) return null;
|
||||
|
||||
const [change] = pending.splice(index, 1);
|
||||
ordered.push(change!);
|
||||
current.set(change!.original.id, change!.next);
|
||||
}
|
||||
return ordered;
|
||||
}
|
||||
|
||||
async function applyUpdates(changes: EntryChange[], undo: UndoOperation[]): Promise<void> {
|
||||
for (const change of changes) {
|
||||
await updateEntry(change.next);
|
||||
undo.push(() => updateEntry(change.original));
|
||||
}
|
||||
}
|
||||
|
||||
async function withCompensation<T>(
|
||||
operation: (undo: UndoOperation[]) => Promise<T>
|
||||
): Promise<T> {
|
||||
const undo: UndoOperation[] = [];
|
||||
let entriesAdjusted = true;
|
||||
try {
|
||||
return await operation(undo);
|
||||
} catch (operationError) {
|
||||
const rollbackErrors: unknown[] = [];
|
||||
for (const rollback of [...undo].reverse()) {
|
||||
try {
|
||||
await rollback();
|
||||
} catch (rollbackError) {
|
||||
rollbackErrors.push(rollbackError);
|
||||
}
|
||||
}
|
||||
throw new BreakPlacementSagaError(operationError, rollbackErrors);
|
||||
}
|
||||
}
|
||||
|
||||
function replacementChange(
|
||||
req: BreakPlacementRequest,
|
||||
start: string,
|
||||
end: string
|
||||
): EntryChange | null {
|
||||
if (!req.replaceBreakId) return null;
|
||||
const original = timeEntries.value.find((entry) => entry.id === req.replaceBreakId);
|
||||
if (!original) throw new Error('Break to update no longer exists');
|
||||
return { original, next: { ...original, start, end } };
|
||||
}
|
||||
|
||||
function buildPlacementCommit({
|
||||
req,
|
||||
breakStart,
|
||||
durationSeconds,
|
||||
memberId,
|
||||
}: {
|
||||
req: BreakPlacementRequest;
|
||||
breakStart: string;
|
||||
durationSeconds: number;
|
||||
memberId: string;
|
||||
}): PlacementCommit {
|
||||
if (placementMode(req) === 'split') {
|
||||
const original = timeEntries.value.find((e) => e.id === req.workEntries[0]!.id);
|
||||
const plan = planSplitEntry(req.workEntries[0]!, durationSeconds, breakStart, {
|
||||
dayStart: req.dayStart,
|
||||
dayEnd: req.dayEnd,
|
||||
otherEntries: req.otherEntries,
|
||||
});
|
||||
if (!original || !plan) throw new NoFreeWindowError(req.date, durationSeconds);
|
||||
|
||||
const replacement = replacementChange(req, plan.breakSlot.start, plan.breakSlot.end);
|
||||
return {
|
||||
updates: [
|
||||
{
|
||||
original,
|
||||
next: {
|
||||
...original,
|
||||
start: plan.firstHalf.start,
|
||||
end: plan.firstHalf.end,
|
||||
},
|
||||
},
|
||||
...(replacement ? [replacement] : []),
|
||||
...shiftChanges(plan.shifted),
|
||||
],
|
||||
creates: [
|
||||
if (placementMode(req) === 'split') {
|
||||
const original = timeEntries.value.find((e) => e.id === req.workEntries[0]!.id);
|
||||
const plan = planSplitEntry(req.workEntries[0]!, durationSeconds, breakStart);
|
||||
if (!original || !plan) throw new NoFreeWindowError(req.date, durationSeconds);
|
||||
// Shrink the original to the first half, then add the second half + break.
|
||||
await updateEntry({
|
||||
...original,
|
||||
start: plan.firstHalf.start,
|
||||
end: plan.firstHalf.end,
|
||||
});
|
||||
await api.createTimeEntry(
|
||||
{
|
||||
member_id: memberId,
|
||||
project_id: original.project_id,
|
||||
@@ -328,65 +240,52 @@ export function useBreakPlacement(deps: BreakPlacementDeps) {
|
||||
description: original.description ?? null,
|
||||
tags: original.tags ?? [],
|
||||
},
|
||||
...(!replacement
|
||||
? [breakEntryBody(plan.breakSlot.start, plan.breakSlot.end, memberId)]
|
||||
: []),
|
||||
],
|
||||
entriesAdjusted: true,
|
||||
};
|
||||
}
|
||||
|
||||
const plan = planMoveInsert(
|
||||
[...req.workEntries, ...req.otherEntries],
|
||||
req.dayStart,
|
||||
req.dayEnd,
|
||||
breakStart,
|
||||
durationSeconds
|
||||
);
|
||||
if (!plan) throw new NoFreeWindowError(req.date, durationSeconds);
|
||||
|
||||
const replacement = replacementChange(req, plan.breakSlot.start, plan.breakSlot.end);
|
||||
return {
|
||||
updates: [...shiftChanges(plan.shifted), ...(replacement ? [replacement] : [])],
|
||||
creates: replacement
|
||||
? []
|
||||
: [breakEntryBody(plan.breakSlot.start, plan.breakSlot.end, memberId)],
|
||||
entriesAdjusted: plan.shifted.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Apply a declarative commit with reverse-order compensation if a later write fails. */
|
||||
async function executePlacement({
|
||||
req,
|
||||
breakStart,
|
||||
durationSeconds,
|
||||
memberId,
|
||||
}: {
|
||||
req: BreakPlacementRequest;
|
||||
breakStart: string;
|
||||
durationSeconds: number;
|
||||
memberId: string;
|
||||
}): Promise<{ entriesAdjusted: boolean }> {
|
||||
const commit = buildPlacementCommit({ req, breakStart, durationSeconds, memberId });
|
||||
const updates = nonOverlappingUpdateOrder(commit.updates, memberId);
|
||||
if (!updates) throw new NoFreeWindowError(req.date, durationSeconds);
|
||||
|
||||
return withCompensation(async (undo) => {
|
||||
await applyUpdates(updates, undo);
|
||||
for (const body of commit.creates) {
|
||||
const id = await createEntry(body);
|
||||
undo.push(() => deleteEntry(id));
|
||||
{ params: { organization: requireOrgId() } }
|
||||
);
|
||||
await saveBreakEntry(
|
||||
plan.breakSlot.start,
|
||||
plan.breakSlot.end,
|
||||
req.replaceBreakId ?? undefined,
|
||||
memberId
|
||||
);
|
||||
} else {
|
||||
const plan = planMoveInsert(
|
||||
[...req.workEntries, ...req.otherEntries],
|
||||
req.dayStart,
|
||||
req.dayEnd,
|
||||
breakStart,
|
||||
durationSeconds
|
||||
);
|
||||
if (!plan) throw new NoFreeWindowError(req.date, durationSeconds);
|
||||
entriesAdjusted = plan.shifted.length > 0;
|
||||
// Order the shifts so no intermediate step overlaps (matters when the org
|
||||
// prevents overlapping entries): entries moving earlier are updated left-to-right,
|
||||
// entries moving later right-to-left, so each one vacates before its neighbour moves.
|
||||
const shifts = plan.shifted
|
||||
.map((shift) => ({
|
||||
shift,
|
||||
original: timeEntries.value.find((e) => e.id === shift.id),
|
||||
}))
|
||||
.filter(
|
||||
(x): x is { shift: (typeof plan.shifted)[number]; original: TimeEntry } =>
|
||||
!!x.original
|
||||
);
|
||||
const movingEarlier = shifts
|
||||
.filter((x) => x.shift.start < x.original.start)
|
||||
.sort((a, b) => a.original.start.localeCompare(b.original.start));
|
||||
const movingLater = shifts
|
||||
.filter((x) => x.shift.start >= x.original.start)
|
||||
.sort((a, b) => b.original.start.localeCompare(a.original.start));
|
||||
for (const { shift, original } of [...movingEarlier, ...movingLater]) {
|
||||
await updateEntry({ ...original, start: shift.start, end: shift.end });
|
||||
}
|
||||
await saveBreakEntry(
|
||||
plan.breakSlot.start,
|
||||
plan.breakSlot.end,
|
||||
req.replaceBreakId ?? undefined,
|
||||
memberId
|
||||
);
|
||||
}
|
||||
return { entriesAdjusted: commit.entriesAdjusted };
|
||||
});
|
||||
}
|
||||
|
||||
const { mutateAsync: commitPlacement } = useMutation({
|
||||
mutationKey: ['timesheet', 'break-placement'],
|
||||
scope: { id: 'timesheet-break-placement' },
|
||||
retry: false,
|
||||
mutationFn: executePlacement,
|
||||
onSuccess: ({ entriesAdjusted }, { req }) => {
|
||||
notifications.addNotification(
|
||||
'success',
|
||||
req.replaceBreakId ? 'Break updated' : 'Break added',
|
||||
@@ -394,19 +293,8 @@ export function useBreakPlacement(deps: BreakPlacementDeps) {
|
||||
? 'Your entries were adjusted to make room for the break.'
|
||||
: 'The break was added at the selected time.'
|
||||
);
|
||||
if (breakPlacementRequest.value === req) breakPlacementRequest.value = null;
|
||||
},
|
||||
onError: (error, { req }) => {
|
||||
const operationError =
|
||||
error instanceof BreakPlacementSagaError ? error.operationError : error;
|
||||
if (error instanceof BreakPlacementSagaError && error.rollbackErrors.length > 0) {
|
||||
notifications.addNotification(
|
||||
'error',
|
||||
'Break placement needs attention',
|
||||
'Some entries could not be restored. The timesheet has been refreshed.'
|
||||
);
|
||||
if (breakPlacementRequest.value === req) breakPlacementRequest.value = null;
|
||||
} else if (operationError instanceof NoFreeWindowError) {
|
||||
} catch (err) {
|
||||
if (err instanceof NoFreeWindowError) {
|
||||
notifications.addNotification(
|
||||
'error',
|
||||
"This day can't fit the break",
|
||||
@@ -415,23 +303,15 @@ export function useBreakPlacement(deps: BreakPlacementDeps) {
|
||||
} else {
|
||||
notifications.addNotification(
|
||||
'error',
|
||||
req.replaceBreakId ? 'Failed to update break' : 'Failed to add break',
|
||||
'Failed to add break',
|
||||
'Please try again later.'
|
||||
);
|
||||
}
|
||||
},
|
||||
onSettled: () => {
|
||||
throw err;
|
||||
} finally {
|
||||
breakPlacementRequest.value = null;
|
||||
queryClient.invalidateQueries({ queryKey: ['timeEntries'] });
|
||||
},
|
||||
});
|
||||
|
||||
async function applyBreakPlacement(breakStart: string, durationSeconds: number): Promise<void> {
|
||||
const req = breakPlacementRequest.value;
|
||||
if (!req) return;
|
||||
const memberId = getCurrentMembershipId();
|
||||
if (!memberId) throw new Error('No member context');
|
||||
|
||||
await commitPlacement({ req, breakStart, durationSeconds, memberId });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -17,25 +17,6 @@ vi.mock('@tanstack/vue-query', () => ({
|
||||
useQueryClient: () => ({
|
||||
invalidateQueries: vi.fn(),
|
||||
}),
|
||||
useMutation: (options: {
|
||||
mutationFn: (variables: unknown) => Promise<unknown>;
|
||||
onSuccess?: (data: unknown, variables: unknown) => void | Promise<void>;
|
||||
onError?: (error: unknown, variables: unknown) => void | Promise<void>;
|
||||
onSettled?: () => void | Promise<void>;
|
||||
}) => ({
|
||||
mutateAsync: async (variables: unknown) => {
|
||||
try {
|
||||
const data = await options.mutationFn(variables);
|
||||
await options.onSuccess?.(data, variables);
|
||||
return data;
|
||||
} catch (error) {
|
||||
await options.onError?.(error, variables);
|
||||
throw error;
|
||||
} finally {
|
||||
await options.onSettled?.();
|
||||
}
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('@/utils/notification', () => ({
|
||||
@@ -362,6 +343,40 @@ describe('useTimesheetCellMutations.handleCellUpdate', () => {
|
||||
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps an edited break anchored to its position instead of recentering', async () => {
|
||||
// 09-10 and 11:30-12:30 leave a 90-min gap; a resized 1h break has a valid
|
||||
// window of 10:00-10:30. The break already starts at 10:00, so it must stay
|
||||
// there (10:00-11:00) rather than jump to the centered 10:15-11:15.
|
||||
const morning = entry('2026-04-10T09:00:00Z', '2026-04-10T10:00:00Z', {
|
||||
id: 'morning',
|
||||
type: 'work',
|
||||
});
|
||||
const afternoon = entry('2026-04-10T11:30:00Z', '2026-04-10T12:30:00Z', {
|
||||
id: 'afternoon',
|
||||
type: 'work',
|
||||
});
|
||||
const existingBreak = entry('2026-04-10T10:00:00Z', '2026-04-10T10:30:00Z', {
|
||||
id: 'break-1',
|
||||
project_id: null,
|
||||
type: 'break',
|
||||
});
|
||||
const row = buildRow(null, [existingBreak], 'break-row');
|
||||
row.type = 'break';
|
||||
const { cellMutations } = setup([morning, afternoon, existingBreak]);
|
||||
|
||||
await cellMutations.handleCellUpdate(row, 0, HOUR);
|
||||
|
||||
expect(apiMocks.updateTimeEntry).toHaveBeenCalledTimes(1);
|
||||
expect(firstArg(apiMocks.updateTimeEntry)).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'break-1',
|
||||
start: '2026-04-10T10:00:00Z',
|
||||
end: '2026-04-10T11:00:00Z',
|
||||
})
|
||||
);
|
||||
expect(apiMocks.createTimeEntry).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('grows a multi-break cell by re-placing the latest break, not fragmenting', async () => {
|
||||
// Two breaks share the break cell. Growing the cell total must extend the
|
||||
// latest-ending break (break-b) in place — never create a third break entry.
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
workDayStartOn,
|
||||
type FreeWindow,
|
||||
} from './cellMath';
|
||||
import { useBreakPlacement, type PlaceBreakResult } from './useBreakPlacement';
|
||||
import { useBreakPlacement, BreakPlacementDeferred } from './useBreakPlacement';
|
||||
|
||||
export type CellSaveStatus = 'saving' | 'saved' | 'error';
|
||||
|
||||
@@ -54,8 +54,7 @@ export function useTimesheetCellMutations(
|
||||
weekDays: Ref<string[]>,
|
||||
timeEntries: Ref<TimeEntry[]>,
|
||||
rows: Ref<TimesheetRow[]>,
|
||||
removeSlot: (key: TimesheetRowKey) => void,
|
||||
preventOverlappingTimeEntries: () => boolean = () => false
|
||||
removeSlot: (key: TimesheetRowKey) => void
|
||||
) {
|
||||
const dayjs = getDayJsInstance();
|
||||
const queryClient = useQueryClient();
|
||||
@@ -71,15 +70,7 @@ export function useTimesheetCellMutations(
|
||||
// modal flow) is its own subsystem — it borrows the generic entry primitives
|
||||
// below (hoisted function declarations, so referenceable here).
|
||||
const { breakPlacementRequest, placeBreak, dismissBreakPlacement, applyBreakPlacement } =
|
||||
useBreakPlacement({
|
||||
weekDays,
|
||||
timeEntries,
|
||||
requireOrgId,
|
||||
createCell,
|
||||
updateEntry,
|
||||
deleteEntry,
|
||||
preventOverlappingTimeEntries,
|
||||
});
|
||||
useBreakPlacement({ weekDays, timeEntries, requireOrgId, createCell, updateEntry });
|
||||
|
||||
function clearStatusTimer(key: string): void {
|
||||
clearTimeout(statusClearTimers[key]);
|
||||
@@ -134,14 +125,7 @@ export function useTimesheetCellMutations(
|
||||
const wasEmpty = row.totalSeconds === 0;
|
||||
|
||||
try {
|
||||
const result = await dispatchCellUpdate(row, dayIndex, newTotalSeconds);
|
||||
if (result === 'needs-input') {
|
||||
// The placement modal owns the actual save, so return the cell to idle.
|
||||
clearStatusTimer(statusKey);
|
||||
delete cellStatus.value[statusKey];
|
||||
delete cellPendingSeconds.value[statusKey];
|
||||
return;
|
||||
}
|
||||
await dispatchCellUpdate(row, dayIndex, newTotalSeconds);
|
||||
|
||||
if (wasEmpty && newTotalSeconds > 0 && hasDuplicateIdentitySlot(row)) {
|
||||
removeSlot(row.key);
|
||||
@@ -153,6 +137,14 @@ export function useTimesheetCellMutations(
|
||||
}
|
||||
markSaved(statusKey);
|
||||
} catch (err) {
|
||||
if (err instanceof BreakPlacementDeferred) {
|
||||
// The break needs manual placement — revert the cell to idle (the
|
||||
// modal drives the actual save) instead of showing an error.
|
||||
clearStatusTimer(statusKey);
|
||||
delete cellStatus.value[statusKey];
|
||||
delete cellPendingSeconds.value[statusKey];
|
||||
return;
|
||||
}
|
||||
markError(statusKey);
|
||||
if (err instanceof NoFreeWindowError) {
|
||||
const friendlyDuration = formatHumanReadableDuration(
|
||||
@@ -190,24 +182,25 @@ export function useTimesheetCellMutations(
|
||||
row: TimesheetRow,
|
||||
dayIndex: number,
|
||||
newTotalSeconds: number
|
||||
): Promise<PlaceBreakResult> {
|
||||
): Promise<void> {
|
||||
const cell = row.cells.get(dayIndex);
|
||||
const existingSeconds = cell?.totalSeconds ?? 0;
|
||||
const diff = newTotalSeconds - existingSeconds;
|
||||
|
||||
if (newTotalSeconds === 0 && cell) {
|
||||
await deleteCell(cell);
|
||||
return 'committed';
|
||||
return;
|
||||
}
|
||||
|
||||
if (!cell || existingSeconds === 0) {
|
||||
// Breaks are placed relative to work (within tolerance), not just in the
|
||||
// first free slot, and may need the placement modal to resolve.
|
||||
if (row.type === 'break' && newTotalSeconds > 0) {
|
||||
return placeBreak(row, dayIndex, newTotalSeconds);
|
||||
await placeBreak(row, dayIndex, newTotalSeconds);
|
||||
return;
|
||||
}
|
||||
await createCell(row, dayIndex, newTotalSeconds);
|
||||
return 'committed';
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-place breaks rather than extend/shrink them, which would fragment a break into
|
||||
@@ -216,23 +209,24 @@ export function useTimesheetCellMutations(
|
||||
// become obstacles); shrinking just trims the tail, which can't fragment.
|
||||
if (row.type === 'break') {
|
||||
if (cell.entries.length === 1) {
|
||||
return placeBreak(row, dayIndex, newTotalSeconds, cell.entries[0]!.id);
|
||||
await placeBreak(row, dayIndex, newTotalSeconds, cell.entries[0]!.id);
|
||||
return;
|
||||
}
|
||||
const tail = pickLatestEndedEntry(cell);
|
||||
if (diff > 0 && tail?.end) {
|
||||
return placeBreak(row, dayIndex, (tail.duration ?? 0) + diff, tail.id);
|
||||
await placeBreak(row, dayIndex, (tail.duration ?? 0) + diff, tail.id);
|
||||
return;
|
||||
}
|
||||
await shrinkFromEnd(cell, -diff);
|
||||
return 'committed';
|
||||
return;
|
||||
}
|
||||
|
||||
if (diff > 0) {
|
||||
await extendCell(row, dayIndex, cell, diff);
|
||||
return 'committed';
|
||||
return;
|
||||
}
|
||||
|
||||
await shrinkFromEnd(cell, -diff);
|
||||
return 'committed';
|
||||
}
|
||||
|
||||
async function deleteCell(cell: TimesheetCell): Promise<void> {
|
||||
|
||||
@@ -7,20 +7,9 @@ import { useTasksQuery } from '@/utils/useTasksQuery';
|
||||
import { useClientsQuery } from '@/utils/useClientsQuery';
|
||||
import { useTagsQuery } from '@/utils/useTagsQuery';
|
||||
import { CheckCircleIcon, UserCircleIcon, UserGroupIcon } from '@heroicons/vue/20/solid';
|
||||
import {
|
||||
CalendarDaysIcon,
|
||||
CalendarIcon,
|
||||
DocumentTextIcon,
|
||||
FolderIcon,
|
||||
} from '@heroicons/vue/16/solid';
|
||||
import { DocumentTextIcon, FolderIcon } from '@heroicons/vue/16/solid';
|
||||
import { Coffee } from '@lucide/vue';
|
||||
import BillableIcon from '@/packages/ui/src/Icons/BillableIcon.vue';
|
||||
import {
|
||||
type DateFormat,
|
||||
formatDate,
|
||||
formatMonth,
|
||||
formatWeekRange,
|
||||
} from '@/packages/ui/src/utils/time';
|
||||
|
||||
export type GroupingOption =
|
||||
| 'project'
|
||||
@@ -30,11 +19,7 @@ export type GroupingOption =
|
||||
| 'client'
|
||||
| 'description'
|
||||
| 'tag'
|
||||
| 'type'
|
||||
| 'day'
|
||||
| 'week'
|
||||
| 'month'
|
||||
| 'year';
|
||||
| 'type';
|
||||
|
||||
export const useReportingStore = defineStore('reporting', () => {
|
||||
// Cache query composables to avoid creating new subscriptions on every call
|
||||
@@ -55,11 +40,7 @@ export const useReportingStore = defineStore('reporting', () => {
|
||||
type: 'Work time',
|
||||
} as Record<string, string>;
|
||||
|
||||
function getNameForReportingRowEntry(
|
||||
key: string | null,
|
||||
type: string | null,
|
||||
dateFormat?: DateFormat
|
||||
) {
|
||||
function getNameForReportingRowEntry(key: string | null, type: string | null) {
|
||||
if (type === null) {
|
||||
return null;
|
||||
}
|
||||
@@ -95,16 +76,6 @@ export const useReportingStore = defineStore('reporting', () => {
|
||||
if (type === 'type') {
|
||||
return key === 'break' ? 'Break' : 'Work time';
|
||||
}
|
||||
if (type === 'day') {
|
||||
return formatDate(key, dateFormat);
|
||||
}
|
||||
if (type === 'week') {
|
||||
return formatWeekRange(key, dateFormat);
|
||||
}
|
||||
if (type === 'month') {
|
||||
return formatMonth(key);
|
||||
}
|
||||
// A `year` key is already a bare year, so it falls through unchanged.
|
||||
return key;
|
||||
}
|
||||
|
||||
@@ -153,16 +124,6 @@ export const useReportingStore = defineStore('reporting', () => {
|
||||
value: 'tag',
|
||||
icon: DocumentTextIcon,
|
||||
},
|
||||
{
|
||||
label: 'Date',
|
||||
value: 'day',
|
||||
icon: CalendarIcon,
|
||||
},
|
||||
{
|
||||
label: 'Week',
|
||||
value: 'week',
|
||||
icon: CalendarDaysIcon,
|
||||
},
|
||||
];
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import {
|
||||
getCoreRowModel,
|
||||
getSortedRowModel,
|
||||
sortingFns,
|
||||
type ColumnDef,
|
||||
type Row,
|
||||
type SortingFn,
|
||||
type SortingState,
|
||||
useVueTable,
|
||||
} from '@tanstack/vue-table';
|
||||
import { computed, type ComputedRef } from 'vue';
|
||||
|
||||
export type SortDirection = 'asc' | 'desc';
|
||||
|
||||
/**
|
||||
* Comparator for every sortable column: empty values (`null`/`undefined`) sort last in
|
||||
* both directions and compare as equal, so the tie-break orders them. TanStack's own
|
||||
* `sortUndefined` cannot do this: `'last'` bypasses the tie-break and the default flips
|
||||
* empty rows to the top when descending.
|
||||
*/
|
||||
function sortEmptyLast<TData>(getSorting: () => SortingState): SortingFn<TData> {
|
||||
return (rowA: Row<TData>, rowB: Row<TData>, columnId: string) => {
|
||||
const a = rowA.getValue(columnId);
|
||||
const b = rowB.getValue(columnId);
|
||||
|
||||
if (a == null && b == null) {
|
||||
return 0;
|
||||
}
|
||||
if (a == null || b == null) {
|
||||
const emptyLast = a == null ? 1 : -1;
|
||||
const desc = getSorting().find((entry) => entry.id === columnId)?.desc ?? false;
|
||||
return desc ? -emptyLast : emptyLast;
|
||||
}
|
||||
return typeof a === 'string' || typeof b === 'string'
|
||||
? sortingFns.alphanumeric(rowA, rowB, columnId)
|
||||
: sortingFns.basic(rowA, rowB, columnId);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires `id` to be one of the table's sortable columns, so a mistyped id is a compile
|
||||
* error instead of a column that silently stops sorting. `sortingFn` is forbidden
|
||||
* because the composable always installs its own comparator.
|
||||
*/
|
||||
export type SortableColumnDef<TData, TColumn extends string> = ColumnDef<TData, unknown> & {
|
||||
id: TColumn;
|
||||
sortingFn?: never;
|
||||
};
|
||||
|
||||
export function useSortableTable<TData, TColumn extends string>(options: {
|
||||
data: () => TData[];
|
||||
columns: () => SortableColumnDef<TData, TColumn>[];
|
||||
sortColumn: () => TColumn;
|
||||
sortDirection: () => SortDirection;
|
||||
tieBreakColumn?: TColumn;
|
||||
}): {
|
||||
sortedRows: ComputedRef<TData[]>;
|
||||
descFirstColumns: ComputedRef<ReadonlySet<TColumn>>;
|
||||
nextDirection: (column: TColumn) => SortDirection;
|
||||
} {
|
||||
const sorting = computed<SortingState>(() => [
|
||||
{
|
||||
id: options.sortColumn(),
|
||||
desc: options.sortDirection() === 'desc',
|
||||
},
|
||||
...(options.tieBreakColumn && options.sortColumn() !== options.tieBreakColumn
|
||||
? [{ id: options.tieBreakColumn, desc: false }]
|
||||
: []),
|
||||
]);
|
||||
|
||||
const resolvedColumns = computed<ColumnDef<TData, unknown>[]>(() =>
|
||||
options.columns().map((column) => ({
|
||||
...column,
|
||||
sortUndefined: false as const,
|
||||
sortingFn: sortEmptyLast<TData>(() => sorting.value),
|
||||
}))
|
||||
);
|
||||
|
||||
const descFirstColumns = computed<ReadonlySet<TColumn>>(
|
||||
() =>
|
||||
new Set(
|
||||
options
|
||||
.columns()
|
||||
.filter((column) => column.sortDescFirst)
|
||||
.map((column) => column.id)
|
||||
)
|
||||
);
|
||||
|
||||
function nextDirection(column: TColumn): SortDirection {
|
||||
if (options.sortColumn() === column) {
|
||||
return options.sortDirection() === 'asc' ? 'desc' : 'asc';
|
||||
}
|
||||
return descFirstColumns.value.has(column) ? 'desc' : 'asc';
|
||||
}
|
||||
|
||||
const table = useVueTable({
|
||||
get data() {
|
||||
return options.data();
|
||||
},
|
||||
get columns() {
|
||||
return resolvedColumns.value;
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
state: {
|
||||
get sorting() {
|
||||
return sorting.value;
|
||||
},
|
||||
},
|
||||
manualSorting: false,
|
||||
});
|
||||
|
||||
const sortedRows = computed(() => table.getRowModel().rows.map((row) => row.original));
|
||||
|
||||
return { sortedRows, descFirstColumns, nextDirection };
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { useStorage } from '@vueuse/core';
|
||||
import type { SortDirection } from '@/utils/useSortableTable';
|
||||
|
||||
export interface TableSortState<TColumn extends string> {
|
||||
sortColumn: TColumn;
|
||||
sortDirection: SortDirection;
|
||||
}
|
||||
|
||||
/**
|
||||
* The sort a table page remembers between visits, persisted in localStorage.
|
||||
*
|
||||
* Pages that persist more than the sort (filters, for example) pass the wider defaults
|
||||
* and get them back on `tableState`; `mergeDefaults` is forwarded to `useStorage` so
|
||||
* nested state can be merged key by key rather than wholesale.
|
||||
*/
|
||||
export function useTableSortState<
|
||||
TColumn extends string,
|
||||
TState extends TableSortState<TColumn> = TableSortState<TColumn>,
|
||||
>(
|
||||
key: string,
|
||||
defaults: TState,
|
||||
mergeDefaults: boolean | ((storageValue: TState, defaults: TState) => TState) = true
|
||||
) {
|
||||
const tableState = useStorage<TState>(key, defaults, undefined, { mergeDefaults });
|
||||
|
||||
function handleSort(column: TColumn, direction: SortDirection) {
|
||||
tableState.value.sortColumn = column;
|
||||
tableState.value.sortDirection = direction;
|
||||
}
|
||||
|
||||
return { tableState, handleSort };
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
{{-- Self-contained on purpose: this page is rendered for a request on an
|
||||
untrusted host, so it must not call url()/route()/asset(), which would
|
||||
re-trigger Host validation and throw again. --}}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Untrusted host</title>
|
||||
<style>
|
||||
html, body { height: 100%; margin: 0; }
|
||||
body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #f5f5f5;
|
||||
color: #1f2937;
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
.card {
|
||||
max-width: 32rem;
|
||||
margin: 1.5rem;
|
||||
padding: 2rem;
|
||||
background: #fff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
h1 { margin: 0 0 0.75rem; font-size: 1.25rem; }
|
||||
p { margin: 0; line-height: 1.6; color: #4b5563; }
|
||||
code {
|
||||
padding: 0.1rem 0.35rem;
|
||||
background: #f3f4f6;
|
||||
border-radius: 0.25rem;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Untrusted host</h1>
|
||||
<p>
|
||||
This hostname is not configured for this instance. Set
|
||||
<code>APP_URL</code>, or add the host to <code>TRUSTED_HOSTS</code>.
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -194,7 +194,7 @@
|
||||
@if($group->is(\App\Enums\TimeEntryAggregationType::Billable))
|
||||
{{ $group1Entry['key'] === '1' ? 'Billable' : 'Non-billable' }}
|
||||
@else
|
||||
{{ $group1Entry['description'] ?? $localization->formatTimeGroupKey($group1Entry['key'], $group) ?? 'No '.Str::lower($group->description()) }}
|
||||
{{ $group1Entry['description'] ?? $group1Entry['key'] ?? 'No '.Str::lower($group->description()) }}
|
||||
@endif
|
||||
</span>
|
||||
</td>
|
||||
@@ -239,7 +239,7 @@
|
||||
<span style="color: #a1a1aa;">
|
||||
{{ $group->description() }}:
|
||||
</span>
|
||||
{{ $group1Entry['description'] ?? $localization->formatTimeGroupKey($group1Entry['key'], $group) ?? 'No '.Str::lower($group->description()) }}
|
||||
{{ $group1Entry['description'] ?? $group1Entry['key'] ?? 'No '.Str::lower($group->description()) }}
|
||||
@endif
|
||||
</h2>
|
||||
|
||||
@@ -278,7 +278,7 @@
|
||||
@if($subGroup->is(\App\Enums\TimeEntryAggregationType::Billable))
|
||||
{{ $group2Entry['key'] === '1' ? 'Billable' : 'Non-billable' }}
|
||||
@else
|
||||
{{ $group2Entry['description'] ?? $localization->formatTimeGroupKey($group2Entry['key'], $subGroup) ?? '-' }}
|
||||
{{ $group2Entry['description'] ?? $group2Entry['key'] ?? '-' }}
|
||||
@endif
|
||||
</td>
|
||||
<td>
|
||||
@@ -318,7 +318,7 @@
|
||||
|
||||
series: [
|
||||
{
|
||||
data: {!! json_encode(collect($aggregatedData['grouped_data'])->map(function (array $data) use (&$colorService, $group, $localization): object {
|
||||
data: {!! json_encode(collect($aggregatedData['grouped_data'])->map(function (array $data) use (&$colorService, $group): object {
|
||||
$color = $data['color'];
|
||||
if ($color === null) {
|
||||
$color = $colorService->getRandomColor($data['key']);
|
||||
@@ -328,7 +328,7 @@
|
||||
}
|
||||
return (object)[
|
||||
'value' => $data['seconds'],
|
||||
'name' => $data['description'] ?? $localization->formatTimeGroupKey($data['key'], $group) ?? 'No '.Str::lower($group->description()),
|
||||
'name' => $data['description'] ?? $data['key'] ?? 'No '.Str::lower($group->description()),
|
||||
'color' => $color,
|
||||
'itemStyle' => (object) [
|
||||
'color' => $color,
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
</td>
|
||||
@else
|
||||
<td style="border: 1px solid black;" data-type="{{ DataType::TYPE_STRING }}">
|
||||
{{ $group1Entry['description'] ?? $localization->formatTimeGroupKey($group1Entry['key'], $group) ?? '-' }}
|
||||
{{ $group1Entry['description'] ?? $group1Entry['key'] ?? '-' }}
|
||||
</td>
|
||||
@endif
|
||||
@if ($subGroup === TimeEntryAggregationType::Billable)
|
||||
@@ -53,7 +53,7 @@
|
||||
</td>
|
||||
@else
|
||||
<td style="border: 1px solid black;" data-type="{{ DataType::TYPE_STRING }}">
|
||||
{{ $group2Entry['description'] ?? $localization->formatTimeGroupKey($group2Entry['key'], $subGroup) ?? '-' }}
|
||||
{{ $group2Entry['description'] ?? $group2Entry['key'] ?? '-' }}
|
||||
</td>
|
||||
@endif
|
||||
<td style="border: 1px solid black;" data-type="{{ DataType::TYPE_STRING }}">
|
||||
@@ -74,7 +74,7 @@
|
||||
</td>
|
||||
@else
|
||||
<td style="border: 1px solid black;" data-type="{{ DataType::TYPE_STRING }}">
|
||||
{{ $group1Entry['description'] ?? $localization->formatTimeGroupKey($group1Entry['key'], $group) ?? '-' }}
|
||||
{{ $group1Entry['description'] ?? $group1Entry['key'] ?? '-' }}
|
||||
</td>
|
||||
@endif
|
||||
@if ($subGroup === TimeEntryAggregationType::Billable)
|
||||
@@ -83,7 +83,7 @@
|
||||
</td>
|
||||
@else
|
||||
<td style="border: 1px solid black;" data-type="{{ DataType::TYPE_STRING }}">
|
||||
{{ $group2Entry['description'] ?? $localization->formatTimeGroupKey($group2Entry['key'], $subGroup) ?? '-' }}
|
||||
{{ $group2Entry['description'] ?? $group2Entry['key'] ?? '-' }}
|
||||
</td>
|
||||
@endif
|
||||
<td style="border: 1px solid black;" data-type="{{ DataType::TYPE_NUMERIC }}"
|
||||
|
||||
@@ -380,40 +380,6 @@ class RegistrationTest extends TestCaseWithDatabase
|
||||
$this->assertSame($user->organization->id, $organizations->first()->id);
|
||||
}
|
||||
|
||||
public function test_registration_joins_invited_organization_even_if_invitation_email_casing_differs(): void
|
||||
{
|
||||
// Arrange: invitation stored with a different casing than the registration email
|
||||
$user = $this->createUserWithPermission();
|
||||
OrganizationInvitation::factory()
|
||||
->forOrganization($user->organization)
|
||||
->role(Role::Employee)
|
||||
->accepted()
|
||||
->create([
|
||||
'email' => 'Invited.User@example.com',
|
||||
]);
|
||||
|
||||
// Act
|
||||
$response = $this->post('/register', [
|
||||
'name' => 'Invited User',
|
||||
'email' => 'invited.user@example.com',
|
||||
'password' => 'password',
|
||||
'password_confirmation' => 'password',
|
||||
'terms' => true,
|
||||
]);
|
||||
|
||||
// Assert: joined the inviting organization, no extra personal organization, invitation consumed
|
||||
$this->assertAuthenticated();
|
||||
$response->assertRedirect(RouteServiceProvider::HOME);
|
||||
$newUser = User::where('email', 'invited.user@example.com')->first();
|
||||
$this->assertNotNull($newUser);
|
||||
$this->assertDatabaseMissing(OrganizationInvitation::class, [
|
||||
'email' => 'Invited.User@example.com',
|
||||
]);
|
||||
$organizations = $newUser->organizations;
|
||||
$this->assertCount(1, $organizations);
|
||||
$this->assertSame($user->organization->id, $organizations->first()->id);
|
||||
}
|
||||
|
||||
public function test_registration_logs_and_skips_accepted_invitation_with_invalid_role(): void
|
||||
{
|
||||
// Arrange
|
||||
|
||||
@@ -4,9 +4,6 @@ declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Endpoint\Api\V1;
|
||||
|
||||
use Closure;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Testing\TestResponse;
|
||||
use Tests\TestCaseWithDatabase;
|
||||
|
||||
@@ -19,26 +16,4 @@ class ApiEndpointTestAbstract extends TestCaseWithDatabase
|
||||
}
|
||||
$response->assertStatus($statusCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the temporary URL builder of the private disk to capture the options
|
||||
* passed to temporaryUrl. Returns a closure that yields the captured options.
|
||||
*
|
||||
* @return Closure(): (array<string, mixed>|null)
|
||||
*/
|
||||
protected function captureTemporaryUrlOptions(): Closure
|
||||
{
|
||||
$captured = null;
|
||||
Storage::disk(config('filesystems.private'))->buildTemporaryUrlsUsing(
|
||||
function (string $path, DateTimeInterface $expiration, array $options) use (&$captured): string {
|
||||
$captured = $options;
|
||||
|
||||
return 'https://storage.fake/'.$path;
|
||||
}
|
||||
);
|
||||
|
||||
return function () use (&$captured): ?array {
|
||||
return $captured;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,35 +90,4 @@ class ExportEndpointTest extends ApiEndpointTestAbstract
|
||||
$response->assertJsonPath('success', true);
|
||||
$this->assertStringContainsString($filepath, $response->json('download_url'));
|
||||
}
|
||||
|
||||
public function test_export_requests_the_download_url_as_an_attachment(): void
|
||||
{
|
||||
// Arrange
|
||||
$user = $this->createUserWithPermission([
|
||||
'export',
|
||||
]);
|
||||
$filepath = 'exports/export_test.zip';
|
||||
$this->mock(ExportService::class, function (MockInterface $mock) use (&$user, $filepath): void {
|
||||
$mock->shouldReceive('export')
|
||||
->withArgs(function (Organization $organization) use (&$user): bool {
|
||||
return $organization->is($user->organization);
|
||||
})
|
||||
->andReturn($filepath)
|
||||
->once();
|
||||
});
|
||||
Passport::actingAs($user->user);
|
||||
$capturedOptions = $this->captureTemporaryUrlOptions();
|
||||
|
||||
// Act
|
||||
$response = $this->postJson(route('api.v1.export.export', [
|
||||
'organization' => $user->organization->getKey(),
|
||||
]));
|
||||
|
||||
// Assert
|
||||
$response->assertStatus(200);
|
||||
$options = $capturedOptions();
|
||||
$this->assertIsArray($options);
|
||||
$this->assertSame('attachment; filename="export_test.zip"', $options['ResponseContentDisposition'] ?? null);
|
||||
$this->assertSame('https://storage.fake/'.$filepath, $response->json('download_url'));
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user