Repository: solidtime-io/solidtime
Branch: main
Commit: 192c8c3b887a
Files: 1208
Total size: 3.9 MB
Directory structure:
gitextract_ryuvl2mb/
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE/
│ │ ├── 1_bug_report.yml
│ │ └── config.yml
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── dependabot.yml
│ └── workflows/
│ ├── build-onpremise.yml
│ ├── build-private.yml
│ ├── build-public.yml
│ ├── generate-api-docs.yml
│ ├── npm-build.yml
│ ├── npm-format-check.yml
│ ├── npm-lint.yml
│ ├── npm-publish-api.yml
│ ├── npm-publish-ui.yml
│ ├── npm-typecheck.yml
│ ├── phpstan.yml
│ ├── phpunit.yml
│ ├── pint.yml
│ └── playwright.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.json
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── SECURITY.md
├── app/
│ ├── Actions/
│ │ ├── Fortify/
│ │ │ ├── CreateNewUser.php
│ │ │ ├── PasswordValidationRules.php
│ │ │ ├── ResetUserPassword.php
│ │ │ ├── UpdateUserPassword.php
│ │ │ └── UpdateUserProfileInformation.php
│ │ └── Jetstream/
│ │ ├── AddOrganizationMember.php
│ │ ├── CreateOrganization.php
│ │ ├── DeleteOrganization.php
│ │ ├── DeleteUser.php
│ │ ├── InviteOrganizationMember.php
│ │ ├── RemoveOrganizationMember.php
│ │ ├── UpdateMemberRole.php
│ │ ├── UpdateOrganization.php
│ │ └── ValidateOrganizationDeletion.php
│ ├── Console/
│ │ ├── Commands/
│ │ │ ├── Admin/
│ │ │ │ ├── OrganizationDeleteCommand.php
│ │ │ │ ├── UserCreateCommand.php
│ │ │ │ └── UserVerifyCommand.php
│ │ │ ├── Auth/
│ │ │ │ └── AuthSendReminderForExpiringApiTokensCommand.php
│ │ │ ├── Correction/
│ │ │ │ └── CorrectionPlaceholderMembersCommand.php
│ │ │ ├── Report/
│ │ │ │ └── ReportSetExpiredToPrivateCommand.php
│ │ │ ├── SelfHost/
│ │ │ │ ├── SelfHostCheckForUpdateCommand.php
│ │ │ │ ├── SelfHostDatabaseConsistency.php
│ │ │ │ ├── SelfHostGenerateKeysCommand.php
│ │ │ │ └── SelfHostTelemetryCommand.php
│ │ │ ├── Test/
│ │ │ │ ├── TestEmailCommand.php
│ │ │ │ ├── TestJobCommand.php
│ │ │ │ └── TestOutputCommand.php
│ │ │ └── TimeEntry/
│ │ │ └── TimeEntrySendStillRunningMailsCommand.php
│ │ └── Kernel.php
│ ├── Enums/
│ │ ├── CurrencyFormat.php
│ │ ├── DateFormat.php
│ │ ├── ExportFormat.php
│ │ ├── IntervalFormat.php
│ │ ├── NumberFormat.php
│ │ ├── Role.php
│ │ ├── TimeEntryAggregationType.php
│ │ ├── TimeEntryAggregationTypeInterval.php
│ │ ├── TimeEntryRoundingType.php
│ │ ├── TimeFormat.php
│ │ └── Weekday.php
│ ├── Events/
│ │ ├── AfterCreateOrganization.php
│ │ ├── BeforeOrganizationDeletion.php
│ │ ├── DatabaseSeederAfterSeed.php
│ │ ├── DatabaseSeederBeforeDelete.php
│ │ ├── MemberMadeToPlaceholder.php
│ │ ├── MemberRemoved.php
│ │ └── NewsletterRegistered.php
│ ├── Exceptions/
│ │ ├── Api/
│ │ │ ├── ApiException.php
│ │ │ ├── CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers.php
│ │ │ ├── CanNotRemoveOwnerFromOrganization.php
│ │ │ ├── ChangingRoleOfPlaceholderIsNotAllowed.php
│ │ │ ├── ChangingRoleToPlaceholderIsNotAllowed.php
│ │ │ ├── EntityStillInUseApiException.php
│ │ │ ├── FeatureIsNotAvailableInFreePlanApiException.php
│ │ │ ├── InactiveUserCanNotBeUsedApiException.php
│ │ │ ├── InvitationForTheEmailAlreadyExistsApiException.php
│ │ │ ├── OnlyOwnerCanChangeOwnership.php
│ │ │ ├── OnlyPlaceholdersCanBeMergedIntoAnotherMember.php
│ │ │ ├── OrganizationHasNoSubscriptionButMultipleMembersException.php
│ │ │ ├── OrganizationNeedsAtLeastOneOwner.php
│ │ │ ├── OverlappingTimeEntryApiException.php
│ │ │ ├── PdfRendererIsNotConfiguredException.php
│ │ │ ├── PersonalAccessClientIsNotConfiguredException.php
│ │ │ ├── ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException.php
│ │ │ ├── TimeEntryCanNotBeRestartedApiException.php
│ │ │ ├── TimeEntryStillRunningApiException.php
│ │ │ ├── UserIsAlreadyMemberOfOrganizationApiException.php
│ │ │ ├── UserIsAlreadyMemberOfProjectApiException.php
│ │ │ └── UserNotPlaceholderApiException.php
│ │ ├── Handler.php
│ │ └── MovedToApiException.php
│ ├── Extensions/
│ │ ├── Auditing/
│ │ │ └── Resolvers/
│ │ │ └── CustomIpAddressResolver.php
│ │ ├── Fortify/
│ │ │ ├── CustomLoginResponse.php
│ │ │ └── CustomTwoFactorLoginResponse.php
│ │ └── Scramble/
│ │ ├── ApiExceptionTypeToSchema.php
│ │ └── PaginatedResourceCollectionTypeToSchema.php
│ ├── Filament/
│ │ ├── Resources/
│ │ │ ├── AuditResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── CreateAudit.php
│ │ │ │ ├── ListAudits.php
│ │ │ │ └── ViewAudit.php
│ │ │ ├── AuditResource.php
│ │ │ ├── ClientResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── CreateClient.php
│ │ │ │ ├── EditClient.php
│ │ │ │ └── ListClients.php
│ │ │ ├── ClientResource.php
│ │ │ ├── FailedJobResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── ListFailedJobs.php
│ │ │ │ └── ViewFailedJobs.php
│ │ │ ├── FailedJobResource.php
│ │ │ ├── OrganizationInvitationResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── EditOrganizationInvitation.php
│ │ │ │ ├── ListOrganizationInvitations.php
│ │ │ │ └── ViewOrganizationInvitation.php
│ │ │ ├── OrganizationInvitationResource.php
│ │ │ ├── OrganizationResource/
│ │ │ │ ├── Actions/
│ │ │ │ │ └── DeleteOrganization.php
│ │ │ │ ├── Pages/
│ │ │ │ │ ├── CreateOrganization.php
│ │ │ │ │ ├── EditOrganization.php
│ │ │ │ │ ├── ListOrganizations.php
│ │ │ │ │ └── ViewOrganization.php
│ │ │ │ └── RelationManagers/
│ │ │ │ ├── InvitationsRelationManager.php
│ │ │ │ └── UsersRelationManager.php
│ │ │ ├── OrganizationResource.php
│ │ │ ├── ProjectMemberResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── CreateProjectMember.php
│ │ │ │ ├── EditProjectMember.php
│ │ │ │ ├── ListProjectMembers.php
│ │ │ │ └── ViewProjectMembers.php
│ │ │ ├── ProjectMemberResource.php
│ │ │ ├── ProjectResource/
│ │ │ │ ├── Pages/
│ │ │ │ │ ├── CreateProject.php
│ │ │ │ │ ├── EditProject.php
│ │ │ │ │ └── ListProjects.php
│ │ │ │ └── RelationManagers/
│ │ │ │ └── ProjectMembersRelationManager.php
│ │ │ ├── ProjectResource.php
│ │ │ ├── ReportResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── EditReport.php
│ │ │ │ ├── ListReports.php
│ │ │ │ └── ViewReport.php
│ │ │ ├── ReportResource.php
│ │ │ ├── TagResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── CreateTag.php
│ │ │ │ ├── EditTag.php
│ │ │ │ └── ListTags.php
│ │ │ ├── TagResource.php
│ │ │ ├── TaskResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── CreateTask.php
│ │ │ │ ├── EditTask.php
│ │ │ │ └── ListTasks.php
│ │ │ ├── TaskResource.php
│ │ │ ├── TimeEntryResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── CreateTimeEntry.php
│ │ │ │ ├── EditTimeEntry.php
│ │ │ │ └── ListTimeEntries.php
│ │ │ ├── TimeEntryResource.php
│ │ │ ├── TokenResource/
│ │ │ │ └── Pages/
│ │ │ │ ├── ListTokens.php
│ │ │ │ └── ViewToken.php
│ │ │ ├── TokenResource.php
│ │ │ ├── UserResource/
│ │ │ │ ├── Actions/
│ │ │ │ │ └── DeleteUser.php
│ │ │ │ ├── Pages/
│ │ │ │ │ ├── CreateUser.php
│ │ │ │ │ ├── EditUser.php
│ │ │ │ │ ├── ListUsers.php
│ │ │ │ │ └── ViewUser.php
│ │ │ │ └── RelationManagers/
│ │ │ │ ├── OrganizationsRelationManager.php
│ │ │ │ └── OwnedOrganizationsRelationManager.php
│ │ │ └── UserResource.php
│ │ └── Widgets/
│ │ ├── ActiveUserOverview.php
│ │ ├── ServerOverview.php
│ │ ├── TimeEntriesCreated.php
│ │ ├── TimeEntriesImported.php
│ │ └── UserRegistrations.php
│ ├── Http/
│ │ ├── Controllers/
│ │ │ ├── Api/
│ │ │ │ └── V1/
│ │ │ │ ├── ApiTokenController.php
│ │ │ │ ├── ChartController.php
│ │ │ │ ├── ClientController.php
│ │ │ │ ├── Controller.php
│ │ │ │ ├── CurrencyController.php
│ │ │ │ ├── ExportController.php
│ │ │ │ ├── ImportController.php
│ │ │ │ ├── InvitationController.php
│ │ │ │ ├── MemberController.php
│ │ │ │ ├── OrganizationController.php
│ │ │ │ ├── ProjectController.php
│ │ │ │ ├── ProjectMemberController.php
│ │ │ │ ├── Public/
│ │ │ │ │ └── ReportController.php
│ │ │ │ ├── ReportController.php
│ │ │ │ ├── TagController.php
│ │ │ │ ├── TaskController.php
│ │ │ │ ├── TimeEntryController.php
│ │ │ │ ├── UserController.php
│ │ │ │ ├── UserMembershipController.php
│ │ │ │ └── UserTimeEntryController.php
│ │ │ ├── Controller.php
│ │ │ └── Web/
│ │ │ ├── Controller.php
│ │ │ ├── DashboardController.php
│ │ │ ├── HealthCheckController.php
│ │ │ └── HomeController.php
│ │ ├── Kernel.php
│ │ ├── Middleware/
│ │ │ ├── Authenticate.php
│ │ │ ├── CheckOrganizationBlocked.php
│ │ │ ├── EncryptCookies.php
│ │ │ ├── EnsureEmailIsVerified.php
│ │ │ ├── ForceHttps.php
│ │ │ ├── ForceJsonResponse.php
│ │ │ ├── HandleInertiaRequests.php
│ │ │ ├── PreventRequestsDuringMaintenance.php
│ │ │ ├── RedirectIfAuthenticated.php
│ │ │ ├── ShareInertiaData.php
│ │ │ ├── TrimStrings.php
│ │ │ ├── TrustProxies.php
│ │ │ ├── ValidateSignature.php
│ │ │ └── VerifyCsrfToken.php
│ │ ├── Requests/
│ │ │ └── V1/
│ │ │ ├── ApiToken/
│ │ │ │ └── ApiTokenStoreRequest.php
│ │ │ ├── BaseFormRequest.php
│ │ │ ├── Client/
│ │ │ │ ├── ClientIndexRequest.php
│ │ │ │ ├── ClientStoreRequest.php
│ │ │ │ └── ClientUpdateRequest.php
│ │ │ ├── Import/
│ │ │ │ └── ImportRequest.php
│ │ │ ├── Invitation/
│ │ │ │ ├── InvitationIndexRequest.php
│ │ │ │ └── InvitationStoreRequest.php
│ │ │ ├── Member/
│ │ │ │ ├── MemberDestroyRequest.php
│ │ │ │ ├── MemberIndexRequest.php
│ │ │ │ ├── MemberMergeIntoRequest.php
│ │ │ │ └── MemberUpdateRequest.php
│ │ │ ├── Organization/
│ │ │ │ └── OrganizationUpdateRequest.php
│ │ │ ├── Project/
│ │ │ │ ├── ProjectIndexRequest.php
│ │ │ │ ├── ProjectStoreRequest.php
│ │ │ │ └── ProjectUpdateRequest.php
│ │ │ ├── ProjectMember/
│ │ │ │ ├── ProjectMemberIndexRequest.php
│ │ │ │ ├── ProjectMemberStoreRequest.php
│ │ │ │ └── ProjectMemberUpdateRequest.php
│ │ │ ├── Report/
│ │ │ │ ├── ReportIndexRequest.php
│ │ │ │ ├── ReportStoreRequest.php
│ │ │ │ └── ReportUpdateRequest.php
│ │ │ ├── Tag/
│ │ │ │ ├── TagIndexRequest.php
│ │ │ │ ├── TagStoreRequest.php
│ │ │ │ └── TagUpdateRequest.php
│ │ │ ├── Task/
│ │ │ │ ├── TaskIndexRequest.php
│ │ │ │ ├── TaskStoreRequest.php
│ │ │ │ └── TaskUpdateRequest.php
│ │ │ └── TimeEntry/
│ │ │ ├── TimeEntryAggregateExportRequest.php
│ │ │ ├── TimeEntryAggregateRequest.php
│ │ │ ├── TimeEntryDestroyMultipleRequest.php
│ │ │ ├── TimeEntryIndexExportRequest.php
│ │ │ ├── TimeEntryIndexRequest.php
│ │ │ ├── TimeEntryStoreRequest.php
│ │ │ ├── TimeEntryUpdateMultipleRequest.php
│ │ │ └── TimeEntryUpdateRequest.php
│ │ └── Resources/
│ │ ├── PaginatedResourceCollection.php
│ │ └── V1/
│ │ ├── ApiToken/
│ │ │ ├── ApiTokenCollection.php
│ │ │ ├── ApiTokenResource.php
│ │ │ └── ApiTokenWithAccessTokenResource.php
│ │ ├── BaseResource.php
│ │ ├── Client/
│ │ │ ├── ClientCollection.php
│ │ │ └── ClientResource.php
│ │ ├── Invitation/
│ │ │ ├── InvitationCollection.php
│ │ │ └── InvitationResource.php
│ │ ├── Member/
│ │ │ ├── MemberCollection.php
│ │ │ ├── MemberResource.php
│ │ │ ├── PersonalMembershipCollection.php
│ │ │ └── PersonalMembershipResource.php
│ │ ├── Organization/
│ │ │ └── OrganizationResource.php
│ │ ├── Project/
│ │ │ ├── ProjectCollection.php
│ │ │ └── ProjectResource.php
│ │ ├── ProjectMember/
│ │ │ ├── ProjectMemberCollection.php
│ │ │ └── ProjectMemberResource.php
│ │ ├── Report/
│ │ │ ├── DetailedReportResource.php
│ │ │ ├── DetailedWithDataReportResource.php
│ │ │ ├── ReportCollection.php
│ │ │ └── ReportResource.php
│ │ ├── Tag/
│ │ │ ├── TagCollection.php
│ │ │ └── TagResource.php
│ │ ├── Task/
│ │ │ ├── TaskCollection.php
│ │ │ └── TaskResource.php
│ │ ├── TimeEntry/
│ │ │ ├── TimeEntryCollection.php
│ │ │ └── TimeEntryResource.php
│ │ └── User/
│ │ └── UserResource.php
│ ├── Jobs/
│ │ ├── RecalculateSpentTimeForProject.php
│ │ ├── RecalculateSpentTimeForTask.php
│ │ └── Test/
│ │ └── TestJob.php
│ ├── Listeners/
│ │ └── RemovePlaceholder.php
│ ├── Mail/
│ │ ├── AuthApiTokenExpirationReminderMail.php
│ │ ├── AuthApiTokenExpiredMail.php
│ │ ├── OrganizationInvitationMail.php
│ │ └── TimeEntryStillRunningMail.php
│ ├── Models/
│ │ ├── Audit.php
│ │ ├── Client.php
│ │ ├── Concerns/
│ │ │ ├── CustomAuditable.php
│ │ │ └── HasUuids.php
│ │ ├── FailedJob.php
│ │ ├── Member.php
│ │ ├── Organization.php
│ │ ├── OrganizationInvitation.php
│ │ ├── Passport/
│ │ │ ├── AuthCode.php
│ │ │ ├── Client.php
│ │ │ ├── RefreshToken.php
│ │ │ └── Token.php
│ │ ├── Project.php
│ │ ├── ProjectMember.php
│ │ ├── Report.php
│ │ ├── Tag.php
│ │ ├── Task.php
│ │ ├── TimeEntry.php
│ │ └── User.php
│ ├── Policies/
│ │ └── OrganizationPolicy.php
│ ├── Providers/
│ │ ├── AppServiceProvider.php
│ │ ├── AuthServiceProvider.php
│ │ ├── EventServiceProvider.php
│ │ ├── Filament/
│ │ │ └── AdminPanelProvider.php
│ │ ├── FortifyServiceProvider.php
│ │ ├── JetstreamServiceProvider.php
│ │ ├── RouteServiceProvider.php
│ │ └── TelescopeServiceProvider.php
│ ├── Rules/
│ │ ├── ColorRule.php
│ │ └── CurrencyRule.php
│ └── Service/
│ ├── ApiService.php
│ ├── BillableRateService.php
│ ├── BillingContract.php
│ ├── ColorService.php
│ ├── CurrencyService.php
│ ├── DashboardService.php
│ ├── DeletionService.php
│ ├── Dto/
│ │ └── ReportPropertiesDto.php
│ ├── Export/
│ │ ├── ExportException.php
│ │ └── ExportService.php
│ ├── Import/
│ │ ├── ImportDatabaseHelper.php
│ │ ├── ImportService.php
│ │ └── Importers/
│ │ ├── ClockifyProjectsImporter.php
│ │ ├── ClockifyTimeEntriesImporter.php
│ │ ├── DefaultImporter.php
│ │ ├── GenericProjectsImporter.php
│ │ ├── GenericTimeEntriesImporter.php
│ │ ├── HarvestClientsImporter.php
│ │ ├── HarvestProjectsImporter.php
│ │ ├── HarvestTimeEntriesImporter.php
│ │ ├── ImportException.php
│ │ ├── ImporterContract.php
│ │ ├── ImporterProvider.php
│ │ ├── ReportDto.php
│ │ ├── SolidtimeImporter.php
│ │ ├── TogglDataImporter.php
│ │ └── TogglTimeEntriesImporter.php
│ ├── IntervalService.php
│ ├── InvitationService.php
│ ├── IpLookup/
│ │ ├── IpLookupResponseDto.php
│ │ ├── IpLookupServiceContract.php
│ │ └── NoIpLookupService.php
│ ├── LocalizationService.php
│ ├── MemberService.php
│ ├── OrganizationInvitationService.php
│ ├── OrganizationService.php
│ ├── PermissionStore.php
│ ├── ReportExport/
│ │ ├── CsvExport.php
│ │ ├── TimeEntriesDetailedCsvExport.php
│ │ ├── TimeEntriesDetailedExport.php
│ │ └── TimeEntriesReportExport.php
│ ├── ReportService.php
│ ├── TimeEntryAggregationService.php
│ ├── TimeEntryFilter.php
│ ├── TimeEntryService.php
│ ├── TimezoneService.php
│ └── UserService.php
├── artisan
├── bootstrap/
│ ├── app.php
│ └── cache/
│ └── .gitignore
├── components.json
├── composer.json
├── config/
│ ├── app.php
│ ├── audit.php
│ ├── auth.php
│ ├── broadcasting.php
│ ├── cache.php
│ ├── cors.php
│ ├── database.php
│ ├── excel.php
│ ├── filament.php
│ ├── filesystems.php
│ ├── fortify.php
│ ├── hashing.php
│ ├── jetstream.php
│ ├── logging.php
│ ├── mail.php
│ ├── modules.php
│ ├── octane.php
│ ├── passport.php
│ ├── queue.php
│ ├── scheduling.php
│ ├── scramble.php
│ ├── services.php
│ ├── session.php
│ ├── telescope.php
│ ├── trustedproxy.php
│ └── view.php
├── database/
│ ├── .gitignore
│ ├── factories/
│ │ ├── AuditFactory.php
│ │ ├── ClientFactory.php
│ │ ├── FailedJobFactory.php
│ │ ├── MemberFactory.php
│ │ ├── OrganizationFactory.php
│ │ ├── OrganizationInvitationFactory.php
│ │ ├── Passport/
│ │ │ ├── ClientFactory.php
│ │ │ └── TokenFactory.php
│ │ ├── ProjectFactory.php
│ │ ├── ProjectMemberFactory.php
│ │ ├── ReportFactory.php
│ │ ├── TagFactory.php
│ │ ├── TaskFactory.php
│ │ ├── TimeEntryFactory.php
│ │ └── UserFactory.php
│ ├── migrations/
│ │ ├── 2014_10_12_000000_create_users_table.php
│ │ ├── 2014_10_12_100000_create_password_reset_tokens_table.php
│ │ ├── 2014_10_12_200000_add_two_factor_columns_to_users_table.php
│ │ ├── 2016_06_01_000001_create_oauth_auth_codes_table.php
│ │ ├── 2016_06_01_000002_create_oauth_access_tokens_table.php
│ │ ├── 2016_06_01_000003_create_oauth_refresh_tokens_table.php
│ │ ├── 2016_06_01_000004_create_oauth_clients_table.php
│ │ ├── 2016_06_01_000005_create_oauth_personal_access_clients_table.php
│ │ ├── 2018_08_08_100000_create_telescope_entries_table.php
│ │ ├── 2019_08_19_000000_create_failed_jobs_table.php
│ │ ├── 2019_12_14_000001_create_personal_access_tokens_table.php
│ │ ├── 2020_05_21_100000_create_organizations_table.php
│ │ ├── 2020_05_21_200000_create_organization_user_table.php
│ │ ├── 2020_05_21_300000_create_organization_invitations_table.php
│ │ ├── 2024_01_16_161030_create_sessions_table.php
│ │ ├── 2024_01_20_110218_create_clients_table.php
│ │ ├── 2024_01_20_110439_create_projects_table.php
│ │ ├── 2024_01_20_110444_create_tasks_table.php
│ │ ├── 2024_01_20_110452_create_tags_table.php
│ │ ├── 2024_01_20_110837_create_time_entries_table.php
│ │ ├── 2024_03_26_171253_create_project_members_table.php
│ │ ├── 2024_04_11_150130_create_jobs_table.php
│ │ ├── 2024_04_12_095010_create_cache_table.php
│ │ ├── 2024_05_07_134711_move_from_user_id_to_member_id_in_project_members_table.php
│ │ ├── 2024_05_07_141842_move_from_user_id_to_member_id_in_time_entries_table.php
│ │ ├── 2024_05_13_171020_rename_table_organization_user_to_members.php
│ │ ├── 2024_05_22_151226_add_client_id_to_time_entries_table.php
│ │ ├── 2024_05_30_175801_add_is_billable_column_to_projects_table.php
│ │ ├── 2024_05_30_175825_add_is_imported_column_to_time_entries_table.php
│ │ ├── 2024_06_01_000001_create_oauth_device_codes_table.php
│ │ ├── 2024_06_07_113443_change_member_id_foreign_keys_to_restrict_on_delete.php
│ │ ├── 2024_06_10_161831_reset_billable_rates_with_zero_as_value.php
│ │ ├── 2024_06_21_122754_add_is_archived_columns_to_projects_and_clients_table.php
│ │ ├── 2024_06_24_114433_add_done_at_to_tasks_table.php
│ │ ├── 2024_07_02_134307_add_estimated_time_to_projects_and_tasks_table.php
│ │ ├── 2024_07_03_145445_change_data_type_of_id_column_in_failed_jobs_table.php
│ │ ├── 2024_07_18_080906_add_still_active_email_sent_at_to_time_entries_table.php
│ │ ├── 2024_08_01_104840_create_reports_table.php
│ │ ├── 2024_09_02_094105_create_audits_table.php
│ │ ├── 2024_09_18_120203_add_spent_time_to_projects_and_tasks_table.php
│ │ ├── 2024_10_01_143608_add_employees_can_see_billable_rates_to_organizations_table.php
│ │ ├── 2024_11_04_164807_add_foreign_key_to_organizations_and_members_table.php
│ │ ├── 2024_11_04_170614_add_foreign_keys_to_oauth_tables.php
│ │ ├── 2025_04_03_101827_add_localization_columns_to_organizations_table.php
│ │ ├── 2025_04_25_202047_change_data_type_for_spent_time_columns.php
│ │ ├── 2025_05_06_152804_fix_typos_in_organizations_table_format_columns.php
│ │ ├── 2025_05_16_075757_add_foreign_key_for_current_team_id_in_users_table.php
│ │ ├── 2025_06_30_095942_remove_oauth_personal_access_clients_table.php
│ │ ├── 2025_06_30_132538_update_oauth_clients_table.php
│ │ ├── 2025_07_15_105949_hash_oauth_clients.php
│ │ ├── 2025_07_17_104903_add_reminder_sent_at_to_oauth_access_tokens_table.php
│ │ ├── 2025_10_02_000001_add_prevent_overlapping_time_entries_to_organizations_table.php
│ │ ├── 2025_10_16_000001_extend_time_entry_description.php
│ │ └── 2025_10_24_120845_add_employees_can_manage_tasks_to_organizations_table.php
│ ├── schema/
│ │ └── pgsql_test-schema.sql
│ └── seeders/
│ └── DatabaseSeeder.php
├── docker/
│ ├── local/
│ │ ├── 8.3/
│ │ │ ├── Dockerfile
│ │ │ ├── php.ini
│ │ │ ├── start-container
│ │ │ └── supervisord.conf
│ │ ├── minio/
│ │ │ └── create_bucket.sh
│ │ └── pgsql/
│ │ └── create-testing-database.sql
│ └── prod/
│ ├── Dockerfile
│ ├── LICENSE
│ └── deployment/
│ ├── healthcheck
│ ├── octane/
│ │ └── FrankenPHP/
│ │ ├── Caddyfile
│ │ └── supervisord.frankenphp.conf
│ ├── php.ini
│ ├── start-container
│ ├── supervisord.conf
│ ├── supervisord.horizon.conf
│ ├── supervisord.reverb.conf
│ ├── supervisord.scheduler.conf
│ └── supervisord.worker.conf
├── docker-compose.yml
├── e2e/
│ ├── auth.spec.ts
│ ├── calendar-settings.spec.ts
│ ├── calendar.spec.ts
│ ├── clients.spec.ts
│ ├── command-palette.spec.ts
│ ├── dashboard.spec.ts
│ ├── import-export.spec.ts
│ ├── members.spec.ts
│ ├── organization.spec.ts
│ ├── profile.spec.ts
│ ├── project-members.spec.ts
│ ├── projects.spec.ts
│ ├── reporting-detailed.spec.ts
│ ├── reporting.spec.ts
│ ├── shared-reports.spec.ts
│ ├── tags.spec.ts
│ ├── tasks.spec.ts
│ ├── time.spec.ts
│ ├── timetracker.spec.ts
│ └── utils/
│ ├── api.ts
│ ├── currentTimeEntry.ts
│ ├── mailpit.ts
│ ├── members.ts
│ ├── money.ts
│ ├── reporting.ts
│ ├── table.ts
│ └── tags.ts
├── eslint.config.mjs
├── jsconfig.json
├── lang/
│ └── en/
│ ├── auth.php
│ ├── enum.php
│ ├── exceptions.php
│ ├── importer.php
│ ├── pagination.php
│ ├── passwords.php
│ └── validation.php
├── openapi.json
├── package.json
├── phpstan.neon
├── phpunit.xml
├── pint.json
├── playwright/
│ ├── config.ts
│ └── fixtures.ts
├── playwright.config.ts
├── postcss.config.js
├── public/
│ ├── .htaccess
│ ├── desktop-version/
│ │ ├── latest-linux.yml
│ │ ├── latest-mac.yml
│ │ └── latest.yml
│ ├── favicons/
│ │ ├── browserconfig.xml
│ │ └── site.webmanifest
│ ├── index.php
│ ├── robots.txt
│ └── security.txt
├── resources/
│ ├── css/
│ │ ├── app.css
│ │ └── filament/
│ │ └── admin/
│ │ ├── tailwind.config.js
│ │ └── theme.css
│ ├── js/
│ │ ├── Components/
│ │ │ ├── ActionMessage.vue
│ │ │ ├── ActionSection.vue
│ │ │ ├── ApplicationLogo.vue
│ │ │ ├── ApplicationMark.vue
│ │ │ ├── AuthenticationCard.vue
│ │ │ ├── AuthenticationCardLogo.vue
│ │ │ ├── Banner.vue
│ │ │ ├── Billing/
│ │ │ │ └── BillingBanner.vue
│ │ │ ├── CommandPalette/
│ │ │ │ ├── CommandPaletteProvider.vue
│ │ │ │ └── index.ts
│ │ │ ├── Common/
│ │ │ │ ├── Card.vue
│ │ │ │ ├── Client/
│ │ │ │ │ ├── ClientCreateModal.vue
│ │ │ │ │ ├── ClientEditModal.vue
│ │ │ │ │ ├── ClientMoreOptionsDropdown.vue
│ │ │ │ │ ├── ClientMultiselectDropdown.vue
│ │ │ │ │ ├── ClientTable.vue
│ │ │ │ │ ├── ClientTableHeading.vue
│ │ │ │ │ └── ClientTableRow.vue
│ │ │ │ ├── Invitation/
│ │ │ │ │ ├── InvitationMoreOptionsDropdown.vue
│ │ │ │ │ ├── InvitationTable.vue
│ │ │ │ │ ├── InvitationTableHeading.vue
│ │ │ │ │ └── InvitationTableRow.vue
│ │ │ │ ├── Member/
│ │ │ │ │ ├── MemberBillableRateModal.vue
│ │ │ │ │ ├── MemberBillableSelect.vue
│ │ │ │ │ ├── MemberCombobox.vue
│ │ │ │ │ ├── MemberDeleteModal.vue
│ │ │ │ │ ├── MemberEditModal.vue
│ │ │ │ │ ├── MemberInviteModal.vue
│ │ │ │ │ ├── MemberMakePlaceholderModal.vue
│ │ │ │ │ ├── MemberMergeModal.vue
│ │ │ │ │ ├── MemberMoreOptionsDropdown.vue
│ │ │ │ │ ├── MemberMultiselectDropdown.vue
│ │ │ │ │ ├── MemberOwnershipTransferConfirmModal.vue
│ │ │ │ │ ├── MemberRoleSelect.vue
│ │ │ │ │ ├── MemberTable.vue
│ │ │ │ │ ├── MemberTableHeading.vue
│ │ │ │ │ └── MemberTableRow.vue
│ │ │ │ ├── Notification/
│ │ │ │ │ └── Notification.vue
│ │ │ │ ├── Organization/
│ │ │ │ │ └── OrganizationBillableRateModal.vue
│ │ │ │ ├── PageTitle.vue
│ │ │ │ ├── Project/
│ │ │ │ │ ├── BaseFilterBadge.vue
│ │ │ │ │ ├── ProjectClientFilterBadge.vue
│ │ │ │ │ ├── ProjectDropdown.vue
│ │ │ │ │ ├── ProjectEditModal.vue
│ │ │ │ │ ├── ProjectMoreOptionsDropdown.vue
│ │ │ │ │ ├── ProjectMultiselectDropdown.vue
│ │ │ │ │ ├── ProjectStatusFilterBadge.vue
│ │ │ │ │ ├── ProjectTable.vue
│ │ │ │ │ ├── ProjectTableHeading.vue
│ │ │ │ │ ├── ProjectTableRow.vue
│ │ │ │ │ ├── ProjectsFilterDropdown.vue
│ │ │ │ │ └── constants.ts
│ │ │ │ ├── ProjectMember/
│ │ │ │ │ ├── ProjectMemberBillableRateModal.vue
│ │ │ │ │ ├── ProjectMemberCreateModal.vue
│ │ │ │ │ ├── ProjectMemberEditModal.vue
│ │ │ │ │ ├── ProjectMemberMoreOptionsDropdown.vue
│ │ │ │ │ ├── ProjectMemberTable.vue
│ │ │ │ │ ├── ProjectMemberTableHeading.vue
│ │ │ │ │ └── ProjectMemberTableRow.vue
│ │ │ │ ├── Report/
│ │ │ │ │ ├── ReportCreateModal.vue
│ │ │ │ │ ├── ReportEditModal.vue
│ │ │ │ │ ├── ReportMoreOptionsDropdown.vue
│ │ │ │ │ ├── ReportSaveButton.vue
│ │ │ │ │ ├── ReportTable.vue
│ │ │ │ │ ├── ReportTableHeading.vue
│ │ │ │ │ └── ReportTableRow.vue
│ │ │ │ ├── Reporting/
│ │ │ │ │ ├── ReportingChart.vue
│ │ │ │ │ ├── ReportingExportButton.vue
│ │ │ │ │ ├── ReportingExportModal.vue
│ │ │ │ │ ├── ReportingFilterBadge.vue
│ │ │ │ │ ├── ReportingFilterBar.vue
│ │ │ │ │ ├── ReportingGroupBySelect.vue
│ │ │ │ │ ├── ReportingOverview.vue
│ │ │ │ │ ├── ReportingPieChart.vue
│ │ │ │ │ ├── ReportingRoundingControls.vue
│ │ │ │ │ ├── ReportingRow.vue
│ │ │ │ │ └── ReportingTabNavbar.vue
│ │ │ │ ├── StatCard.vue
│ │ │ │ ├── TabBar/
│ │ │ │ │ ├── TabBar.vue
│ │ │ │ │ └── TabBarItem.vue
│ │ │ │ ├── TableHeading.vue
│ │ │ │ ├── Tag/
│ │ │ │ │ ├── TagEditModal.vue
│ │ │ │ │ ├── TagMoreOptionsDropdown.vue
│ │ │ │ │ ├── TagTable.vue
│ │ │ │ │ ├── TagTableHeading.vue
│ │ │ │ │ └── TagTableRow.vue
│ │ │ │ ├── Task/
│ │ │ │ │ ├── TaskCreateModal.vue
│ │ │ │ │ ├── TaskEditModal.vue
│ │ │ │ │ ├── TaskMoreOptionsDropdown.vue
│ │ │ │ │ ├── TaskMultiselectDropdown.vue
│ │ │ │ │ ├── TaskTable.vue
│ │ │ │ │ ├── TaskTableHeading.vue
│ │ │ │ │ └── TaskTableRow.vue
│ │ │ │ ├── UpgradeBadge.vue
│ │ │ │ ├── UpgradeModal.vue
│ │ │ │ └── User/
│ │ │ │ └── UserTimezoneMismatchModal.vue
│ │ │ ├── ConfirmationModal.vue
│ │ │ ├── ConfirmsPassword.vue
│ │ │ ├── CurrentSidebarTimer.vue
│ │ │ ├── Dashboard/
│ │ │ │ ├── ActivityGraphCard.vue
│ │ │ │ ├── DashboardCard.vue
│ │ │ │ ├── DayOverviewCardChart.vue
│ │ │ │ ├── DayOverviewCardEntry.vue
│ │ │ │ ├── LastSevenDaysCard.vue
│ │ │ │ ├── ProjectsChartCard.vue
│ │ │ │ ├── RecentlyTrackedTasksCard.vue
│ │ │ │ ├── RecentlyTrackedTasksCardEntry.vue
│ │ │ │ ├── TeamActivityCard.vue
│ │ │ │ ├── TeamActivityCardEntry.vue
│ │ │ │ ├── ThisWeekOverview.vue
│ │ │ │ └── ThisWeekReportingTable.vue
│ │ │ ├── DropdownLink.vue
│ │ │ ├── FormSection.vue
│ │ │ ├── NavLink.vue
│ │ │ ├── NavigationSidebarItem.vue
│ │ │ ├── NavigationSidebarLink.vue
│ │ │ ├── NotificationContainer.vue
│ │ │ ├── OrganizationSwitcher.vue
│ │ │ ├── ResponsiveNavLink.vue
│ │ │ ├── SectionBorder.vue
│ │ │ ├── SectionTitle.vue
│ │ │ ├── TableRow.vue
│ │ │ ├── TimeTracker.vue
│ │ │ ├── UpdateSidebarNotification.vue
│ │ │ ├── UserSettingsIcon.vue
│ │ │ └── ui/
│ │ │ ├── alert-dialog/
│ │ │ │ ├── AlertDialog.vue
│ │ │ │ ├── AlertDialogAction.vue
│ │ │ │ ├── AlertDialogCancel.vue
│ │ │ │ ├── AlertDialogContent.vue
│ │ │ │ ├── AlertDialogDescription.vue
│ │ │ │ ├── AlertDialogFooter.vue
│ │ │ │ ├── AlertDialogHeader.vue
│ │ │ │ ├── AlertDialogTitle.vue
│ │ │ │ ├── AlertDialogTrigger.vue
│ │ │ │ └── index.ts
│ │ │ ├── calendar/
│ │ │ │ ├── Calendar.vue
│ │ │ │ ├── CalendarCell.vue
│ │ │ │ ├── CalendarCellTrigger.vue
│ │ │ │ ├── CalendarDateInput.vue
│ │ │ │ ├── CalendarGrid.vue
│ │ │ │ ├── CalendarGridBody.vue
│ │ │ │ ├── CalendarGridHead.vue
│ │ │ │ ├── CalendarGridRow.vue
│ │ │ │ ├── CalendarHeadCell.vue
│ │ │ │ ├── CalendarHeader.vue
│ │ │ │ ├── CalendarHeading.vue
│ │ │ │ ├── CalendarNextButton.vue
│ │ │ │ ├── CalendarPrevButton.vue
│ │ │ │ └── index.ts
│ │ │ ├── dialog/
│ │ │ │ ├── Dialog.vue
│ │ │ │ ├── DialogClose.vue
│ │ │ │ ├── DialogContent.vue
│ │ │ │ ├── DialogDescription.vue
│ │ │ │ ├── DialogFooter.vue
│ │ │ │ ├── DialogHeader.vue
│ │ │ │ ├── DialogScrollContent.vue
│ │ │ │ ├── DialogTitle.vue
│ │ │ │ ├── DialogTrigger.vue
│ │ │ │ └── index.ts
│ │ │ ├── dropdown-menu/
│ │ │ │ ├── DropdownMenu.vue
│ │ │ │ ├── DropdownMenuCheckboxItem.vue
│ │ │ │ ├── DropdownMenuContent.vue
│ │ │ │ ├── DropdownMenuGroup.vue
│ │ │ │ ├── DropdownMenuItem.vue
│ │ │ │ ├── DropdownMenuLabel.vue
│ │ │ │ ├── DropdownMenuRadioGroup.vue
│ │ │ │ ├── DropdownMenuRadioItem.vue
│ │ │ │ ├── DropdownMenuSeparator.vue
│ │ │ │ ├── DropdownMenuShortcut.vue
│ │ │ │ ├── DropdownMenuSub.vue
│ │ │ │ ├── DropdownMenuSubContent.vue
│ │ │ │ ├── DropdownMenuSubTrigger.vue
│ │ │ │ ├── DropdownMenuTrigger.vue
│ │ │ │ └── index.ts
│ │ │ ├── label/
│ │ │ │ ├── Label.vue
│ │ │ │ └── index.ts
│ │ │ ├── number-field/
│ │ │ │ ├── NumberField.vue
│ │ │ │ ├── NumberFieldContent.vue
│ │ │ │ ├── NumberFieldDecrement.vue
│ │ │ │ ├── NumberFieldIncrement.vue
│ │ │ │ ├── NumberFieldInput.vue
│ │ │ │ └── index.ts
│ │ │ ├── select/
│ │ │ │ ├── Select.vue
│ │ │ │ ├── SelectContent.vue
│ │ │ │ ├── SelectGroup.vue
│ │ │ │ ├── SelectItem.vue
│ │ │ │ ├── SelectItemText.vue
│ │ │ │ ├── SelectLabel.vue
│ │ │ │ ├── SelectScrollDownButton.vue
│ │ │ │ ├── SelectScrollUpButton.vue
│ │ │ │ ├── SelectSeparator.vue
│ │ │ │ ├── SelectTrigger.vue
│ │ │ │ ├── SelectValue.vue
│ │ │ │ └── index.ts
│ │ │ ├── switch/
│ │ │ │ ├── Switch.vue
│ │ │ │ └── index.ts
│ │ │ ├── table/
│ │ │ │ ├── Table.vue
│ │ │ │ ├── TableBody.vue
│ │ │ │ ├── TableCaption.vue
│ │ │ │ ├── TableCell.vue
│ │ │ │ ├── TableEmpty.vue
│ │ │ │ ├── TableFooter.vue
│ │ │ │ ├── TableHead.vue
│ │ │ │ ├── TableHeader.vue
│ │ │ │ ├── TableRow.vue
│ │ │ │ └── index.ts
│ │ │ └── tabs/
│ │ │ ├── Tabs.vue
│ │ │ ├── TabsContent.vue
│ │ │ ├── TabsList.vue
│ │ │ ├── TabsTrigger.vue
│ │ │ └── index.ts
│ │ ├── Layouts/
│ │ │ └── AppLayout.vue
│ │ ├── Pages/
│ │ │ ├── API/
│ │ │ │ ├── Index.vue
│ │ │ │ └── Partials/
│ │ │ │ └── ApiTokenManager.vue
│ │ │ ├── Auth/
│ │ │ │ ├── ConfirmPassword.vue
│ │ │ │ ├── ForgotPassword.vue
│ │ │ │ ├── Login.vue
│ │ │ │ ├── Register.vue
│ │ │ │ ├── ResetPassword.vue
│ │ │ │ ├── TwoFactorChallenge.vue
│ │ │ │ └── VerifyEmail.vue
│ │ │ ├── Calendar.vue
│ │ │ ├── Clients.vue
│ │ │ ├── Dashboard.vue
│ │ │ ├── Import.vue
│ │ │ ├── Members.vue
│ │ │ ├── PrivacyPolicy.vue
│ │ │ ├── Profile/
│ │ │ │ ├── Partials/
│ │ │ │ │ ├── ApiTokensForm.vue
│ │ │ │ │ ├── DeleteUserForm.vue
│ │ │ │ │ ├── LogoutOtherBrowserSessionsForm.vue
│ │ │ │ │ ├── ThemeForm.vue
│ │ │ │ │ ├── TwoFactorAuthenticationForm.vue
│ │ │ │ │ ├── UpdatePasswordForm.vue
│ │ │ │ │ └── UpdateProfileInformationForm.vue
│ │ │ │ └── Show.vue
│ │ │ ├── ProjectShow.vue
│ │ │ ├── Projects.vue
│ │ │ ├── Reporting.vue
│ │ │ ├── ReportingDetailed.vue
│ │ │ ├── ReportingShared.vue
│ │ │ ├── SharedReport.vue
│ │ │ ├── Tags.vue
│ │ │ ├── Teams/
│ │ │ │ ├── Create.vue
│ │ │ │ ├── Partials/
│ │ │ │ │ ├── CreateTeamForm.vue
│ │ │ │ │ ├── DeleteTeamForm.vue
│ │ │ │ │ ├── ExportData.vue
│ │ │ │ │ ├── ImportData.vue
│ │ │ │ │ ├── OrganizationBillableRate.vue
│ │ │ │ │ ├── OrganizationFormatSettings.vue
│ │ │ │ │ ├── OrganizationTimeEntrySettings.vue
│ │ │ │ │ ├── TeamMemberManager.vue
│ │ │ │ │ └── UpdateTeamNameForm.vue
│ │ │ │ └── Show.vue
│ │ │ ├── TermsOfService.vue
│ │ │ ├── Time.vue
│ │ │ └── Welcome.vue
│ │ ├── app.ts
│ │ ├── bootstrap.js
│ │ ├── lib/
│ │ │ └── utils.ts
│ │ ├── packages/
│ │ │ ├── api/
│ │ │ │ ├── .gitignore
│ │ │ │ ├── package.json
│ │ │ │ ├── src/
│ │ │ │ │ ├── index.ts
│ │ │ │ │ └── openapi.json.client.ts
│ │ │ │ ├── tsconfig.json
│ │ │ │ └── vite.config.js
│ │ │ └── ui/
│ │ │ ├── .gitignore
│ │ │ ├── package.json
│ │ │ ├── src/
│ │ │ │ ├── Badge.vue
│ │ │ │ ├── BillableRateModal.vue
│ │ │ │ ├── Buttons/
│ │ │ │ │ ├── Button.vue
│ │ │ │ │ ├── DangerButton.vue
│ │ │ │ │ ├── PrimaryButton.vue
│ │ │ │ │ ├── SecondaryButton.vue
│ │ │ │ │ └── index.ts
│ │ │ │ ├── CardTitle.vue
│ │ │ │ ├── Client/
│ │ │ │ │ ├── ClientDropdown.vue
│ │ │ │ │ └── ClientDropdownItem.vue
│ │ │ │ ├── CommandPalette/
│ │ │ │ │ ├── CommandPalette.vue
│ │ │ │ │ ├── CommandPaletteTypes.ts
│ │ │ │ │ └── index.ts
│ │ │ │ ├── DialogModal.vue
│ │ │ │ ├── EstimatedTimeProgress.vue
│ │ │ │ ├── EstimatedTimeSection.vue
│ │ │ │ ├── FullCalendar/
│ │ │ │ │ ├── CalendarSettingsPopover.vue
│ │ │ │ │ ├── FullCalendarDayHeader.vue
│ │ │ │ │ ├── FullCalendarEventContent.vue
│ │ │ │ │ ├── TimeEntryCalendar.vue
│ │ │ │ │ ├── calendarSettings.ts
│ │ │ │ │ ├── idleStatusPlugin.ts
│ │ │ │ │ └── useVisualSnap.ts
│ │ │ │ ├── GroupedItemsCountButton.vue
│ │ │ │ ├── Icons/
│ │ │ │ │ ├── BillableIcon.vue
│ │ │ │ │ ├── DollarIcon.vue
│ │ │ │ │ ├── EuroIcon.vue
│ │ │ │ │ └── ListFilterIcon.vue
│ │ │ │ ├── Input/
│ │ │ │ │ ├── BillableRateInput.vue
│ │ │ │ │ ├── BillableToggleButton.vue
│ │ │ │ │ ├── Checkbox.vue
│ │ │ │ │ ├── DatePicker.vue
│ │ │ │ │ ├── DateRangePicker.vue
│ │ │ │ │ ├── Dropdown.vue
│ │ │ │ │ ├── DurationHumanInput.vue
│ │ │ │ │ ├── EstimatedTimeInput.vue
│ │ │ │ │ ├── InputError.vue
│ │ │ │ │ ├── InputLabel.vue
│ │ │ │ │ ├── MultiselectDropdown.vue
│ │ │ │ │ ├── TextInput.vue
│ │ │ │ │ ├── TextareaInput.vue
│ │ │ │ │ ├── TimePickerSimple.vue
│ │ │ │ │ └── TimeRangeSelector.vue
│ │ │ │ ├── LoadingSpinner.vue
│ │ │ │ ├── MainContainer.vue
│ │ │ │ ├── Modal.vue
│ │ │ │ ├── Project/
│ │ │ │ │ ├── ProjectBadge.vue
│ │ │ │ │ ├── ProjectBillableRateModal.vue
│ │ │ │ │ ├── ProjectBillableSelect.vue
│ │ │ │ │ ├── ProjectColorSelector.vue
│ │ │ │ │ ├── ProjectCreateModal.vue
│ │ │ │ │ ├── ProjectDropdownItem.vue
│ │ │ │ │ └── ProjectEditBillableSection.vue
│ │ │ │ ├── Tag/
│ │ │ │ │ ├── TagBadge.vue
│ │ │ │ │ ├── TagCreateModal.vue
│ │ │ │ │ └── TagDropdown.vue
│ │ │ │ ├── TimeEntry/
│ │ │ │ │ ├── TimeEntryAggregateRow.vue
│ │ │ │ │ ├── TimeEntryCreateModal.vue
│ │ │ │ │ ├── TimeEntryDescriptionInput.vue
│ │ │ │ │ ├── TimeEntryEditModal.vue
│ │ │ │ │ ├── TimeEntryGroupedTable.vue
│ │ │ │ │ ├── TimeEntryMassActionRow.vue
│ │ │ │ │ ├── TimeEntryMassUpdateModal.vue
│ │ │ │ │ ├── TimeEntryMoreOptionsDropdown.vue
│ │ │ │ │ ├── TimeEntryRangeSelector.vue
│ │ │ │ │ ├── TimeEntryRow.vue
│ │ │ │ │ ├── TimeEntryRowDurationInput.vue
│ │ │ │ │ ├── TimeEntryRowHeading.vue
│ │ │ │ │ └── TimeEntryRowTagDropdown.vue
│ │ │ │ ├── TimeTracker/
│ │ │ │ │ ├── TimeTrackerControls.vue
│ │ │ │ │ ├── TimeTrackerMoreOptionsDropdown.vue
│ │ │ │ │ ├── TimeTrackerProjectTaskDropdown.vue
│ │ │ │ │ ├── TimeTrackerRangeSelector.vue
│ │ │ │ │ ├── TimeTrackerRecentlyTrackedEntry.vue
│ │ │ │ │ ├── TimeTrackerRunningInDifferentOrganizationOverlay.vue
│ │ │ │ │ └── TimeTrackerTagDropdown.vue
│ │ │ │ ├── TimeTrackerStartStop.vue
│ │ │ │ ├── TimezoneMismatchModal.vue
│ │ │ │ ├── accordion/
│ │ │ │ │ ├── Accordion.vue
│ │ │ │ │ ├── AccordionContent.vue
│ │ │ │ │ ├── AccordionItem.vue
│ │ │ │ │ ├── AccordionTrigger.vue
│ │ │ │ │ └── index.ts
│ │ │ │ ├── command/
│ │ │ │ │ ├── Command.vue
│ │ │ │ │ ├── CommandGroup.vue
│ │ │ │ │ ├── CommandInput.vue
│ │ │ │ │ ├── CommandItem.vue
│ │ │ │ │ ├── CommandList.vue
│ │ │ │ │ ├── CommandSeparator.vue
│ │ │ │ │ ├── CommandShortcut.vue
│ │ │ │ │ └── index.ts
│ │ │ │ ├── field/
│ │ │ │ │ ├── Field.vue
│ │ │ │ │ ├── FieldContent.vue
│ │ │ │ │ ├── FieldDescription.vue
│ │ │ │ │ ├── FieldError.vue
│ │ │ │ │ ├── FieldGroup.vue
│ │ │ │ │ ├── FieldLabel.vue
│ │ │ │ │ ├── FieldLegend.vue
│ │ │ │ │ ├── FieldSeparator.vue
│ │ │ │ │ ├── FieldSet.vue
│ │ │ │ │ ├── FieldTitle.vue
│ │ │ │ │ └── index.ts
│ │ │ │ ├── index.ts
│ │ │ │ ├── popover/
│ │ │ │ │ ├── Popover.vue
│ │ │ │ │ ├── PopoverContent.vue
│ │ │ │ │ ├── PopoverTrigger.vue
│ │ │ │ │ └── index.ts
│ │ │ │ ├── range-calendar/
│ │ │ │ │ ├── RangeCalendar.vue
│ │ │ │ │ ├── RangeCalendarCell.vue
│ │ │ │ │ ├── RangeCalendarCellTrigger.vue
│ │ │ │ │ ├── RangeCalendarGrid.vue
│ │ │ │ │ ├── RangeCalendarGridBody.vue
│ │ │ │ │ ├── RangeCalendarGridHead.vue
│ │ │ │ │ ├── RangeCalendarGridRow.vue
│ │ │ │ │ ├── RangeCalendarHeadCell.vue
│ │ │ │ │ ├── RangeCalendarHeader.vue
│ │ │ │ │ ├── RangeCalendarHeading.vue
│ │ │ │ │ ├── RangeCalendarNextButton.vue
│ │ │ │ │ ├── RangeCalendarPrevButton.vue
│ │ │ │ │ └── index.ts
│ │ │ │ ├── separator/
│ │ │ │ │ ├── Separator.vue
│ │ │ │ │ └── index.ts
│ │ │ │ ├── tooltip/
│ │ │ │ │ ├── Tooltip.vue
│ │ │ │ │ ├── TooltipContent.vue
│ │ │ │ │ ├── TooltipProvider.vue
│ │ │ │ │ ├── TooltipTrigger.vue
│ │ │ │ │ └── index.ts
│ │ │ │ └── utils/
│ │ │ │ ├── cn.ts
│ │ │ │ ├── color.ts
│ │ │ │ ├── money.ts
│ │ │ │ ├── number.ts
│ │ │ │ ├── random.ts
│ │ │ │ ├── select.ts
│ │ │ │ ├── settings.ts
│ │ │ │ └── time.ts
│ │ │ ├── styles.css
│ │ │ ├── tailwind.theme.js
│ │ │ ├── tsconfig.json
│ │ │ └── vite.config.js
│ │ ├── types/
│ │ │ ├── dom.d.ts
│ │ │ ├── dom.ts
│ │ │ ├── global.d.ts
│ │ │ ├── inertia.d.ts
│ │ │ ├── jetstream.ts
│ │ │ ├── models.d.ts
│ │ │ ├── models.ts
│ │ │ ├── projects.d.ts
│ │ │ ├── reporting.ts
│ │ │ ├── time-entries.d.ts
│ │ │ ├── vite-env.d.ts
│ │ │ └── vue-shim.d.ts
│ │ ├── utils/
│ │ │ ├── billing.ts
│ │ │ ├── commandPaletteCommands.ts
│ │ │ ├── feedback.ts
│ │ │ ├── fetchAllPages.ts
│ │ │ ├── format.ts
│ │ │ ├── init.ts
│ │ │ ├── money.ts
│ │ │ ├── notification.ts
│ │ │ ├── permissions.ts
│ │ │ ├── prefetch.ts
│ │ │ ├── roles.ts
│ │ │ ├── session.ts
│ │ │ ├── theme.ts
│ │ │ ├── useAggregatedTimeEntriesQuery.ts
│ │ │ ├── useClients.ts
│ │ │ ├── useClientsQuery.ts
│ │ │ ├── useCommandPalette.ts
│ │ │ ├── useCssVariable.ts
│ │ │ ├── useCurrentTimeEntry.ts
│ │ │ ├── useInvitations.ts
│ │ │ ├── useMembers.ts
│ │ │ ├── useMembersQuery.ts
│ │ │ ├── useOrganization.ts
│ │ │ ├── useOrganizationQuery.ts
│ │ │ ├── useProjectMembers.ts
│ │ │ ├── useProjectMembersQuery.ts
│ │ │ ├── useProjects.ts
│ │ │ ├── useProjectsQuery.ts
│ │ │ ├── useReporting.ts
│ │ │ ├── useReportsQuery.ts
│ │ │ ├── useTags.ts
│ │ │ ├── useTagsQuery.ts
│ │ │ ├── useTasks.ts
│ │ │ ├── useTasksQuery.ts
│ │ │ ├── useTimeEntriesCalendarQuery.ts
│ │ │ ├── useTimeEntriesInfiniteQuery.ts
│ │ │ ├── useTimeEntriesMutations.ts
│ │ │ ├── useTimeEntriesReportQuery.ts
│ │ │ └── useUser.ts
│ │ ├── ziggy.d.ts
│ │ └── ziggy.js
│ ├── markdown/
│ │ ├── policy.md
│ │ └── terms.md
│ ├── testfiles/
│ │ ├── clockify_projects_import_test_1.csv
│ │ ├── clockify_time_entries_import_test_1.csv
│ │ ├── clockify_time_entries_import_test_2.csv
│ │ ├── clockify_time_entries_import_test_3.csv
│ │ ├── generic_projects_import_test_1.csv
│ │ ├── generic_time_entries_import_test_1.csv
│ │ ├── harvest_clients_import_test_1.csv
│ │ ├── harvest_projects_import_test_1.csv
│ │ ├── harvest_time_entries_import_test_1.csv
│ │ ├── solidtime_import_test_1/
│ │ │ ├── clients.csv
│ │ │ ├── members.csv
│ │ │ ├── meta.json
│ │ │ ├── organization_invitations.csv
│ │ │ ├── organizations.csv
│ │ │ ├── project_members.csv
│ │ │ ├── projects.csv
│ │ │ ├── tags.csv
│ │ │ ├── tasks.csv
│ │ │ └── time_entries.csv
│ │ ├── toggl_data_import_test_1/
│ │ │ ├── clients.json
│ │ │ ├── projects.json
│ │ │ ├── projects_users/
│ │ │ │ ├── 401.json
│ │ │ │ ├── 402.json
│ │ │ │ └── 403.json
│ │ │ ├── tags.json
│ │ │ ├── tasks/
│ │ │ │ ├── 401.json
│ │ │ │ ├── 402.json
│ │ │ │ └── 403.json
│ │ │ └── workspace_users.json
│ │ ├── toggl_data_import_test_2/
│ │ │ ├── clients.json
│ │ │ ├── projects.json
│ │ │ ├── projects_users/
│ │ │ │ ├── 401.json
│ │ │ │ ├── 402.json
│ │ │ │ └── 403.json
│ │ │ ├── tags.json
│ │ │ ├── tasks/
│ │ │ │ ├── 401.json
│ │ │ │ ├── 402.json
│ │ │ │ └── 403.json
│ │ │ └── workspace_users.json
│ │ ├── toggl_time_entries_import_test_1.csv
│ │ └── toggl_time_entries_import_test_2.csv
│ └── views/
│ ├── app.blade.php
│ ├── auth/
│ │ └── oauth/
│ │ └── authorize.blade.php
│ ├── emails/
│ │ ├── auth-api-expiration-reminder.blade.php
│ │ ├── auth-api-token-expired.blade.php
│ │ ├── organization-invitation.blade.php
│ │ └── time-entry-still-running.blade.php
│ ├── filament/
│ │ └── widgets/
│ │ └── server-overview.blade.php
│ ├── reports/
│ │ ├── time-entry-aggregate/
│ │ │ ├── pdf-footer.blade.php
│ │ │ ├── pdf.blade.php
│ │ │ └── spreadsheet.blade.php
│ │ └── time-entry-index/
│ │ ├── pdf-footer.blade.php
│ │ └── pdf.blade.php
│ └── vendor/
│ └── mail/
│ ├── html/
│ │ ├── button.blade.php
│ │ ├── footer.blade.php
│ │ ├── header.blade.php
│ │ ├── layout.blade.php
│ │ ├── message.blade.php
│ │ ├── panel.blade.php
│ │ ├── subcopy.blade.php
│ │ ├── table.blade.php
│ │ └── themes/
│ │ └── default.css
│ └── text/
│ ├── button.blade.php
│ ├── footer.blade.php
│ ├── header.blade.php
│ ├── layout.blade.php
│ ├── message.blade.php
│ ├── panel.blade.php
│ ├── subcopy.blade.php
│ └── table.blade.php
├── routes/
│ ├── api.php
│ └── web.php
├── storage/
│ ├── app/
│ │ └── .gitignore
│ ├── framework/
│ │ ├── .gitignore
│ │ ├── cache/
│ │ │ └── .gitignore
│ │ ├── sessions/
│ │ │ └── .gitignore
│ │ ├── testing/
│ │ │ └── .gitignore
│ │ └── views/
│ │ └── .gitignore
│ └── logs/
│ └── .gitignore
├── tailwind.config.js
├── tests/
│ ├── CreatesApplication.php
│ ├── Feature/
│ │ ├── AuthenticationTest.php
│ │ ├── BrowserSessionsTest.php
│ │ ├── CreateOrganizationTest.php
│ │ ├── DeleteAccountTest.php
│ │ ├── DeleteOrganizationTest.php
│ │ ├── EmailVerificationTest.php
│ │ ├── InviteTeamMemberTest.php
│ │ ├── LeaveTeamTest.php
│ │ ├── PasswordConfirmationTest.php
│ │ ├── PasswordResetTest.php
│ │ ├── ProfileInformationTest.php
│ │ ├── RegistrationTest.php
│ │ ├── RemoveTeamMemberTest.php
│ │ ├── TwoFactorAuthenticationSettingsTest.php
│ │ ├── UpdatePasswordTest.php
│ │ ├── UpdateTeamMemberRoleTest.php
│ │ └── UpdateTeamTest.php
│ ├── TestCase.php
│ ├── TestCaseWithDatabase.php
│ └── Unit/
│ ├── Console/
│ │ ├── Commands/
│ │ │ ├── Admin/
│ │ │ │ ├── OrganizationDeleteCommandTest.php
│ │ │ │ ├── UserCreateCommandCommandTest.php
│ │ │ │ └── UserVerifyCommandTest.php
│ │ │ ├── Auth/
│ │ │ │ └── AuthSendReminderForExpiringApiTokensCommandTest.php
│ │ │ ├── Correction/
│ │ │ │ └── CorrectionPlaceholderMembersCommandTest.php
│ │ │ ├── Report/
│ │ │ │ └── ReportSetExpiredToPrivateCommandTest.php
│ │ │ ├── SelfHost/
│ │ │ │ ├── SelfHostCheckForUpdateCommandTest.php
│ │ │ │ ├── SelfHostDatabaseConsistencyCommandTest.php
│ │ │ │ ├── SelfHostGenerateKeysCommandTest.php
│ │ │ │ └── SelfHostTelemetryCommandTest.php
│ │ │ └── TimeEntry/
│ │ │ └── TimeEntrySendStillRunningMailsCommandTest.php
│ │ └── KernelTest.php
│ ├── Database/
│ │ ├── MigrationTest.php
│ │ └── SeederTest.php
│ ├── Endpoint/
│ │ ├── Api/
│ │ │ └── V1/
│ │ │ ├── ApiEndpointTestAbstract.php
│ │ │ ├── ApiTokenEndpointTest.php
│ │ │ ├── ChartEndpointTest.php
│ │ │ ├── ClientEndpointTest.php
│ │ │ ├── CurrencyEndpointTest.php
│ │ │ ├── ExportEndpointTest.php
│ │ │ ├── ImportEndpointTest.php
│ │ │ ├── InvitationEndpointTest.php
│ │ │ ├── MemberEndpointTest.php
│ │ │ ├── OrganizationEndpointTest.php
│ │ │ ├── ProjectEndpointTest.php
│ │ │ ├── ProjectMemberEndpointTest.php
│ │ │ ├── Public/
│ │ │ │ └── PublicReportEndpointTest.php
│ │ │ ├── ReportEndpointTest.php
│ │ │ ├── TagEndpointTest.php
│ │ │ ├── TaskEndpointTest.php
│ │ │ ├── TimeEntryEndpointTest.php
│ │ │ ├── UserEndpointTest.php
│ │ │ ├── UserMembershipEndpointTest.php
│ │ │ └── UserTimeEntryEndpointTest.php
│ │ └── Web/
│ │ ├── DashboardEndpointTest.php
│ │ ├── EndpointTestAbstract.php
│ │ ├── HealthCheckEndpointTest.php
│ │ └── HomeEndpointTest.php
│ ├── Filament/
│ │ ├── FilamentTestCase.php
│ │ ├── Resources/
│ │ │ ├── AuditResourceTest.php
│ │ │ ├── ClientResourceTest.php
│ │ │ ├── FailedJobResourceTest.php
│ │ │ ├── OrganizationInvitationResourceTest.php
│ │ │ ├── OrganizationResourceTest.php
│ │ │ ├── ProjectResourceTest.php
│ │ │ ├── ReportResourceTest.php
│ │ │ ├── TagResourceTest.php
│ │ │ ├── TaskResourceTest.php
│ │ │ ├── TimeEntryResourceTest.php
│ │ │ ├── TokenResourceTest.php
│ │ │ └── UserResourceTest.php
│ │ └── Widgets/
│ │ └── ServerOverviewWidgetTest.php
│ ├── Jobs/
│ │ ├── RecalculateSpentTimeForProjectTest.php
│ │ ├── RecalculateSpentTimeForTaskTest.php
│ │ └── Test/
│ │ └── TestJobTest.php
│ ├── Mail/
│ │ ├── AuthApiTokenExpirationReminderMailTest.php
│ │ ├── AuthApiTokenExpiredMailTest.php
│ │ ├── OrganizationInvitationMailTest.php
│ │ └── TimeEntryStillRunningMailTest.php
│ ├── Middleware/
│ │ ├── CheckOrganizationBlockedMiddlewareTest.php
│ │ ├── EnsureEmailIsVerifiedMiddlewareTest.php
│ │ ├── ForceHttpsMiddlewareTest.php
│ │ ├── HandleInertiaRequestsMiddlewareTest.php
│ │ └── MiddlewareTestAbstract.php
│ ├── Model/
│ │ ├── ClientModelTest.php
│ │ ├── MemberModelTest.php
│ │ ├── ModelTestAbstract.php
│ │ ├── OrganizationModelTest.php
│ │ ├── Passport/
│ │ │ └── TokenModelTest.php
│ │ ├── ProjectMemberModelTest.php
│ │ ├── ProjectModelTest.php
│ │ ├── ReportModelTest.php
│ │ ├── TagModelTest.php
│ │ ├── TaskModelTest.php
│ │ ├── TimeEntryModelTest.php
│ │ └── UserModelTest.php
│ ├── Rules/
│ │ ├── ColorRuleTest.php
│ │ └── CurrencyRuleTest.php
│ └── Service/
│ ├── BillableRateServiceTest.php
│ ├── CurrencyServiceTest.php
│ ├── DashboardServiceTest.php
│ ├── DeletionServiceTest.php
│ ├── Export/
│ │ └── ExportServiceTest.php
│ ├── Import/
│ │ ├── ImportDatabaseHelperTest.php
│ │ ├── ImportServiceTest.php
│ │ └── Importers/
│ │ ├── ClockifyProjectsImporterTest.php
│ │ ├── ClockifyTimeEntriesImporterTest.php
│ │ ├── GenericProjectsImporterTest.php
│ │ ├── GenericTimeEntriesImporterTest.php
│ │ ├── HarvestClientsImporterTest.php
│ │ ├── HarvestProjectsImporterTest.php
│ │ ├── HarvestTimeEntriesImporterTest.php
│ │ ├── ImporterProviderTest.php
│ │ ├── ImporterTestAbstract.php
│ │ ├── SolidtimeImporterTest.php
│ │ ├── TogglDataImporterTest.php
│ │ └── TogglTimeEntriesImporterTest.php
│ ├── IntervalServiceTest.php
│ ├── LocalizationServiceTest.php
│ ├── MemberServiceTest.php
│ ├── PermissionStoreTest.php
│ ├── TimeEntryAggregationServiceTest.php
│ ├── TimeEntryFilterTest.php
│ ├── TimezoneServiceTest.php
│ └── UserServiceTest.php
├── tsconfig.json
├── vite-module-loader.js
└── vite.config.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4
================================================
FILE: .gitattributes
================================================
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore
================================================
FILE: .github/FUNDING.yml
================================================
github: solidtime-io
================================================
FILE: .github/ISSUE_TEMPLATE/1_bug_report.yml
================================================
name: Bug Report
description: "Report a bug"
body:
- type: markdown
attributes:
value: |
Before creating a new bug report, please check that there isn't already a similar issue.
- type: textarea
attributes:
label: Description
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: "Steps To Reproduce"
description: How do you trigger this bug? Please walk us through it step by step.
value: |
1.
2.
3.
...
validations:
required: false
- type: dropdown
attributes:
label: "Self-hosted or Cloud?"
options:
- Self-Hosted
- solidtime Cloud
- Both
- type: input
attributes:
label: "Version of solidtime: (for self-hosted)"
validations:
required: false
- type: input
attributes:
label: "solidtime self-hosting guide: (for self-hosted)"
description: "Did you use the official guide to self-host solidtime? If yes, which one?"
validations:
required: false
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: 🚀 Feature Request
url: https://github.com/solidtime-io/solidtime/discussions/new?category=feature-requests
about: Share ideas for new features
- name: ❓ Ask a Question
url: https://github.com/solidtime-io/solidtime/discussions/new?category=general
about: Ask the community for help
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
## What does this PR do?
- Fixes #XXXX (GitHub issue number)
## Checklist (DO NOT REMOVE)
- [ ] I read the [contributing guide](https://github.com/solidtime-io/solidtime/blob/main/CONTRIBUTING.md)
- [ ] I signed the [Contributor License Agreement](https://cla-assistant.io/solidtime-io/solidtime).
- [ ] I commented my code, particularly in hard-to-understand areas
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
target-branch: "main"
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "daily"
target-branch: "main"
- package-ecosystem: "composer"
directory: "/"
schedule:
interval: "weekly"
target-branch: "main"
groups:
major-updates:
update-types:
- "major"
minor-updates:
update-types:
- "minor"
- "patch"
security-updates:
applies-to: version-updates
update-types:
- "minor"
- "patch"
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
target-branch: "main"
groups:
major-updates:
update-types:
- "major"
minor-updates:
update-types:
- "minor"
- "patch"
security-updates:
applies-to: version-updates
update-types:
- "minor"
- "patch"
================================================
FILE: .github/workflows/build-onpremise.yml
================================================
on:
push:
branches:
- main
- develop
tags:
- '*'
pull_request:
paths:
- '.github/workflows/build-onpremise.yml'
- 'docker/prod/**'
workflow_dispatch:
permissions:
packages: write
contents: read
attestations: write
id-token: write
env:
DOCKER_REPO: registry.on-premise.solidtime.io/solidtime/solidtime
name: Build - On Premise
jobs:
build:
strategy:
matrix:
include:
- runs-on: "ubuntu-24.04-arm"
platform: "linux/arm64"
- runs-on: "ubuntu-24.04"
platform: "linux/amd64"
runs-on: ${{ matrix.runs-on }}
timeout-minutes: 90
steps:
- name: "Check out code"
uses: actions/checkout@v4
with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
- name: "Get build"
id: release-build
run: echo "build=$(git rev-parse --short=8 HEAD)" >> "$GITHUB_OUTPUT"
- name: "Get Previous tag (normal push)"
id: previoustag
if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
uses: "WyriHaximus/github-action-get-previous-tag@v1"
with:
prefix: "v"
- name: "Get version"
id: release-version
run: |
if ${{ !startsWith(github.ref, 'refs/tags/v') }}; then
if ${{ startsWith(steps.previoustag.outputs.tag, 'v') }}; then
version=$(echo "${{ steps.previoustag.outputs.tag }}" | cut -c 2-)
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
else
echo "ERROR: No previous tag found";
exit 1;
fi
else
version=$(echo "${{ github.ref }}" | cut -c 12-)
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
fi
- name: "Copy .env template for production"
run: |
cp .env.production .env
rm .env.production .env.ci .env.example
- name: "Add version to .env"
run: sed -i 's/APP_VERSION=0.0.0/APP_VERSION=${{ steps.release-version.outputs.app_version }}/g' .env
- name: "Add build to .env"
run: sed -i 's/APP_BUILD=0/APP_BUILD=${{ steps.release-build.outputs.build }}/g' .env
- name: "Output .env"
run: cat .env
- name: "Setup PHP with PECL extension"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, dom, fileinfo, pgsql
- name: "Install dependencies"
run: composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit
- name: "Use Node.js"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Checkout invoicing extension"
uses: actions/checkout@v4
with:
repository: solidtime-io/extension-invoicing
path: extensions/Invoicing
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_INVOICING_EXTENSION }}
- name: "Install composer dependencies in invoicing extension"
run: cd extensions/Invoicing && composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
- name: "Install npm dependencies in invoicing extension"
run: cd extensions/Invoicing && npm ci
- name: "Activate invoicing extension"
run: php artisan module:enable Invoicing
- name: "Install npm dependencies"
run: npm ci
- name: "Build"
run: npm run build
- name: "Prepare"
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: "Docker meta"
id: "meta"
uses: docker/metadata-action@v5
with:
images: |
${{ env.DOCKER_REPO }}
- name: "Login to solidtime OnPremise Registry"
uses: docker/login-action@v3
with:
registry: registry.on-premise.solidtime.io
username: ${{ secrets.ONPREMISE_USERNAME }}
password: ${{ secrets.ONPREMISE_TOKEN }}
- name: "Set up QEMU"
uses: docker/setup-qemu-action@v3
- name: "Set up Docker Buildx"
uses: docker/setup-buildx-action@v3
- name: "Build and push by digest"
id: build
uses: docker/build-push-action@v6
with:
context: .
file: docker/prod/Dockerfile
build-args: |
DOCKER_FILES_BASE_PATH=docker/prod/
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,"name=${{ env.DOCKER_REPO }}",push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha
cache-to: type=gha,mode=max
- name: "Export digest"
run: |
mkdir -p ${{ runner.temp }}/digests
digest="${{ steps.build.outputs.digest }}"
touch "${{ runner.temp }}/digests/${digest#sha256:}"
- name: "Upload digest"
uses: actions/upload-artifact@v4
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: ${{ runner.temp }}/digests/*
if-no-files-found: error
retention-days: 1
merge:
runs-on: ubuntu-latest
timeout-minutes: 90
needs:
- build
steps:
- name: "Download digests"
uses: actions/download-artifact@v4
with:
path: ${{ runner.temp }}/digests
pattern: digests-*
merge-multiple: true
- name: "Login to solidtime OnPremise Registry"
uses: docker/login-action@v3
with:
registry: registry.on-premise.solidtime.io
username: ${{ secrets.ONPREMISE_USERNAME }}
password: ${{ secrets.ONPREMISE_TOKEN }}
- name: "Set up Docker Buildx"
uses: docker/setup-buildx-action@v3
- name: "Docker meta"
id: meta
uses: docker/metadata-action@v5
with:
images: |
${{ env.DOCKER_REPO }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: "Create manifest list and push"
working-directory: ${{ runner.temp }}/digests
run: |
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ env.DOCKER_REPO }}@sha256:%s ' *)
- name: "Inspect image"
run: |
docker buildx imagetools inspect ${{ env.DOCKER_REPO }}:${{ steps.meta.outputs.version }}
================================================
FILE: .github/workflows/build-private.yml
================================================
on:
push:
branches:
- main
- develop
tags:
- '*'
pull_request:
paths:
- '.github/workflows/build-private.yml'
- 'docker/prod/**'
workflow_dispatch:
permissions:
contents: read
name: Build - Private
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: "Check out code"
uses: actions/checkout@v4
with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
- name: "Get build"
id: build
run: echo "build=$(git rev-parse --short=8 HEAD)" >> "$GITHUB_OUTPUT"
- name: "Get Previous tag (normal push)"
id: previoustag
if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
uses: "WyriHaximus/github-action-get-previous-tag@v1"
with:
prefix: "v"
- name: "Get version"
id: version
run: |
if ${{ !startsWith(github.ref, 'refs/tags/v') }}; then
if ${{ startsWith(steps.previoustag.outputs.tag, 'v') }}; then
version=$(echo "${{ steps.previoustag.outputs.tag }}" | cut -c 2-)
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
else
echo "ERROR: No previous tag found";
exit 1;
fi
else
version=$(echo "${{ github.ref }}" | cut -c 12-)
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
fi
- name: "Copy .env template for production"
run: |
cp .env.production .env
rm .env.production .env.ci .env.example
- name: "Add version to .env"
run: sed -i 's/APP_VERSION=0.0.0/APP_VERSION=${{ steps.version.outputs.app_version }}/g' .env
- name: "Add build to .env"
run: sed -i 's/APP_BUILD=0/APP_BUILD=${{ steps.build.outputs.build }}/g' .env
- name: "Output .env"
run: cat .env
- name: "Use Node.js"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Checkout billing extension"
uses: actions/checkout@v4
with:
repository: solidtime-io/extension-billing
path: extensions/Billing
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_BILLING_EXTENSION }}
- name: "Install dependencies in billing extension"
uses: php-actions/composer@v6
env:
COMPOSER_AUTH: '{"http-basic": {"spark.laravel.com": {"username": "gregor@vostrak.at", "password": "${{ secrets.LARAVEL_SPARK_API_KEY }}"}}}'
with:
working_dir: "extensions/Billing"
command: install
only_args: --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
php_version: 8.3
- name: "Install npm dependencies in billing extension"
run: cd extensions/Billing && npm ci
- name: "Checkout services extension"
uses: actions/checkout@v4
with:
repository: solidtime-io/extension-services
path: extensions/Services
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_SERVICES_EXTENSION }}
- name: "Install composer dependencies in services extension"
uses: php-actions/composer@v6
with:
working_dir: "extensions/Services"
command: install
only_args: --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
php_version: 8.3
- name: "Install npm dependencies in services extension"
run: cd extensions/Services && npm ci
- name: "Checkout invoicing extension"
uses: actions/checkout@v4
with:
repository: solidtime-io/extension-invoicing
path: extensions/Invoicing
ssh-key: ${{ secrets.SSH_PRIVATE_KEY_INVOICING_EXTENSION }}
- name: "Install composer dependencies in invoicing extension"
uses: php-actions/composer@v6
with:
working_dir: "extensions/Invoicing"
command: install
only_args: --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
php_version: 8.3
- name: "Install npm dependencies in invoicing extension"
run: cd extensions/Invoicing && npm ci
- name: "Setup PHP with PECL extension"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, dom, fileinfo, pgsql
- name: "Install dependencies"
uses: php-actions/composer@v6
if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit
with:
command: install
only_args: --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
php_version: 8.3
- name: "Activate billing extension"
run: php artisan module:enable Billing
- name: "Activate services extension"
run: php artisan module:enable Services
- name: "Activate invoicing extension"
run: php artisan module:enable Invoicing
- name: "Install npm dependencies"
run: npm ci
- name: "Build"
run: npm run build
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
- name: "Login to GitHub Container Registry"
uses: docker/login-action@v3
with:
registry: rg.fr-par.scw.cloud/solidtime
username: nologin
password: ${{ secrets.SCALEWAY_REGISTRY_TOKEN }}
- name: "Docker meta"
id: "meta"
uses: docker/metadata-action@v5
with:
images: rg.fr-par.scw.cloud/solidtime/solidtime
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,format=long
- name: "Set up QEMU"
uses: docker/setup-qemu-action@v3
- name: "Set up Docker Buildx"
uses: docker/setup-buildx-action@v3
- name: "Build and push"
uses: docker/build-push-action@v6
with:
context: .
build-args: |
DOCKER_FILES_BASE_PATH=docker/prod/
file: docker/prod/Dockerfile
push: true
platforms: linux/amd64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
================================================
FILE: .github/workflows/build-public.yml
================================================
on:
push:
branches:
- main
- develop
tags:
- '*'
pull_request:
paths:
- '.github/workflows/build-public.yml'
- 'docker/prod/**'
workflow_dispatch:
permissions:
packages: write
contents: read
attestations: write
id-token: write
env:
DOCKERHUB_REPO: solidtime/solidtime
GHCR_REPO: ghcr.io/solidtime-io/solidtime
name: Build - Public
jobs:
build:
strategy:
matrix:
include:
- runs-on: "ubuntu-24.04-arm"
platform: "linux/arm64"
- runs-on: "ubuntu-24.04"
platform: "linux/amd64"
runs-on: ${{ matrix.runs-on }}
timeout-minutes: 90
steps:
- name: "Check out code"
uses: actions/checkout@v4
with:
fetch-depth: 0 # Required for WyriHaximus/github-action-get-previous-tag
- name: "Get build"
id: release-build
run: echo "build=$(git rev-parse --short=8 HEAD)" >> "$GITHUB_OUTPUT"
- name: "Get Previous tag (normal push)"
id: previoustag
if: ${{ !startsWith(github.ref, 'refs/tags/v') }}
uses: "WyriHaximus/github-action-get-previous-tag@v1"
with:
prefix: "v"
- name: "Get version"
id: release-version
run: |
if ${{ !startsWith(github.ref, 'refs/tags/v') }}; then
if ${{ startsWith(steps.previoustag.outputs.tag, 'v') }}; then
version=$(echo "${{ steps.previoustag.outputs.tag }}" | cut -c 2-)
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
else
echo "ERROR: No previous tag found";
exit 1;
fi
else
version=$(echo "${{ github.ref }}" | cut -c 12-)
echo "app_version=${version}" >> "$GITHUB_OUTPUT"
fi
- name: "Copy .env template for production"
run: |
cp .env.production .env
rm .env.production .env.ci .env.example
- name: "Add version to .env"
run: sed -i 's/APP_VERSION=0.0.0/APP_VERSION=${{ steps.release-version.outputs.app_version }}/g' .env
- name: "Add build to .env"
run: sed -i 's/APP_BUILD=0/APP_BUILD=${{ steps.release-build.outputs.build }}/g' .env
- name: "Output .env"
run: cat .env
- name: "Setup PHP with PECL extension"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, dom, fileinfo, pgsql
- name: "Install dependencies"
run: composer install --no-dev --no-ansi --no-interaction --prefer-dist --ignore-platform-reqs --classmap-authoritative
if: steps.cache-vendor.outputs.cache-hit != 'true' # Skip if cache hit
- name: "Use Node.js"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Install npm dependencies"
run: npm ci
- name: "Build"
run: npm run build
- name: "Prepare"
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: "Docker meta"
id: "meta"
uses: docker/metadata-action@v5
with:
images: |
${{ env.DOCKERHUB_REPO }}
${{ env.GHCR_REPO }}
- name: "Login to Docker Hub Container Registry"
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: "Login to GitHub Container Registry"
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: "Set up QEMU"
uses: docker/setup-qemu-action@v3
- name: "Set up Docker Buildx"
uses: docker/setup-buildx-action@v3
- name: "Build and push by digest"
id: build
uses: docker/build-push-action@v6
with:
context: .
file: docker/prod/Dockerfile
build-args: |
DOCKER_FILES_BASE_PATH=docker/prod/
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,"name=${{ env.DOCKERHUB_REPO }},${{ env.GHCR_REPO }}",push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha
cache-to: type=gha,mode=max
- name: "Export digest"
run: |
mkdir -p ${{ runner.temp }}/digests
digest="${{ steps.build.outputs.digest }}"
touch "${{ runner.temp }}/digests/${digest#sha256:}"
- name: "Upload digest"
uses: actions/upload-artifact@v4
with:
name: digests-${{ env.PLATFORM_PAIR }}
path: ${{ runner.temp }}/digests/*
if-no-files-found: error
retention-days: 1
merge:
runs-on: ubuntu-latest
timeout-minutes: 90
needs:
- build
steps:
- name: "Download digests"
uses: actions/download-artifact@v4
with:
path: ${{ runner.temp }}/digests
pattern: digests-*
merge-multiple: true
- name: "Login to Docker Hub"
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: "Login to GHCR"
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: "Set up Docker Buildx"
uses: docker/setup-buildx-action@v3
- name: "Docker meta"
id: meta
uses: docker/metadata-action@v5
with:
images: |
${{ env.DOCKERHUB_REPO }}
${{ env.GHCR_REPO }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: "Create manifest list and push"
working-directory: ${{ runner.temp }}/digests
run: |
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ env.DOCKERHUB_REPO }}@sha256:%s ' *)
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ env.GHCR_REPO }}@sha256:%s ' *)
- name: "Inspect image"
run: |
docker buildx imagetools inspect ${{ env.DOCKERHUB_REPO }}:${{ steps.meta.outputs.version }}
docker buildx imagetools inspect ${{ env.GHCR_REPO }}:${{ steps.meta.outputs.version }}
================================================
FILE: .github/workflows/generate-api-docs.yml
================================================
name: Generate API docs
on:
push:
branches:
- main
permissions:
contents: read
jobs:
api_docs:
runs-on: ubuntu-latest
timeout-minutes: 10
services:
pgsql_test:
image: postgres:15
env:
PGPASSWORD: 'root'
POSTGRES_DB: 'laravel'
POSTGRES_USER: 'root'
POSTGRES_PASSWORD: 'root'
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv
- name: "Run composer install"
run: composer install -n --prefer-dist
- name: "Create build directory"
run: mkdir build
- name: Prepare Laravel Application
run: |
cp .env.ci .env
php artisan migrate
- name: "Export API docs"
run: php artisan scramble:export --path=build/api-docs.json
- name: "Upload API docs to GitHub"
uses: actions/upload-artifact@v4
with:
name: api-docs.json
path: build/api-docs.json
- name: "Download Fastfront CLI"
run: curl https://fastfront-cli.s3.fr-par.scw.cloud/fastfront-cli.phar -o fastfront-cli.phar
- name: "Deploy with Fastfront"
run: php fastfront-cli.phar deploy 9beab6cf-f459-446b-85f1-38ec007cf457 ./build
env:
FASTFRONT_API_KEY: ${{ secrets.FASTFRONT_API_DOCS_API_KEY }}
================================================
FILE: .github/workflows/npm-build.yml
================================================
name: NPM Build
on: [push]
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Setup PHP (for Ziggy)"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: intl, zip
coverage: none
- name: "Run composer install (for Ziggy)"
run: composer install -n --prefer-dist
- name: "Use Node.js"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Install npm dependencies"
run: npm ci
- name: "Build"
run: npm run build
================================================
FILE: .github/workflows/npm-format-check.yml
================================================
name: NPM Format Check
on: [push]
jobs:
format-check:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Use Node.js"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Install npm dependencies"
run: npm ci
- name: "Check code formatting"
run: npm run format:check
================================================
FILE: .github/workflows/npm-lint.yml
================================================
name: NPM Lint
on: [push]
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Use Node.js"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Install npm dependencies"
run: npm ci
- name: "Run linter"
run: npm run lint
================================================
FILE: .github/workflows/npm-publish-api.yml
================================================
name: Publish API package to NPM
on:
workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: "Checkout code"
uses: actions/checkout@v4
# Setup .npmrc file to publish to npm
- name: Install root project dependencies
run: npm ci
- uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: npm ci
working-directory: ./resources/js/packages/api
- name: Build package
run: npm run build
working-directory: ./resources/js/packages/api
- name: Publish Package
run: npm publish --provenance --access public
working-directory: ./resources/js/packages/api
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
================================================
FILE: .github/workflows/npm-publish-ui.yml
================================================
name: Publish UI package to NPM
on:
workflow_dispatch
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- name: "Checkout code"
uses: actions/checkout@v4
# Setup .npmrc file to publish to npm
- uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Install root project dependencies
run: npm ci
- name: Install package dependencies
run: npm ci
working-directory: ./resources/js/packages/ui
- name: Build package
run: npm run build
working-directory: ./resources/js/packages/ui
- name: Publish Package
run: npm publish --provenance --access public
working-directory: ./resources/js/packages/ui
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
================================================
FILE: .github/workflows/npm-typecheck.yml
================================================
name: NPM Typecheck
on: [push]
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Setup PHP (for Ziggy)"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: intl, zip
coverage: none
- name: "Run composer install (for Ziggy)"
run: composer install -n --prefer-dist
- name: "Use Node.js"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Install npm dependencies"
run: npm ci
- name: "Run type check"
run: npm run type-check
================================================
FILE: .github/workflows/phpstan.yml
================================================
name: Static code analysis (PHPStan)
on: push
permissions:
contents: read
jobs:
phpstan:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv
coverage: none
- name: "Run composer install"
run: composer install -n --prefer-dist
- name: "Run PHPStan"
run: composer analyse
================================================
FILE: .github/workflows/phpunit.yml
================================================
name: PHPUnit Tests
on: push
permissions:
contents: read
jobs:
phpunit:
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
postgres_version: [ 15, 16, 17 ]
services:
pgsql_test:
image: postgres:${{ matrix.postgres_version }}
env:
PGPASSWORD: 'root'
POSTGRES_DB: 'laravel'
POSTGRES_USER: 'root'
POSTGRES_PASSWORD: 'root'
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
gotenberg:
image: gotenberg/gotenberg:8
ports:
- 3000:3000
options: >-
--health-cmd "curl --silent --fail http://localhost:3000/health"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv
coverage: pcov
- name: "Run composer install"
run: composer install -n --prefer-dist
- uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Install dependencies"
run: npm ci
- name: "Build Frontend"
run: npm run build
- name: "Prepare Laravel Application"
run: |
cp .env.ci .env
php artisan key:generate
php artisan passport:keys
- name: "Run PHPUnit"
run: php artisan test --stop-on-failure --coverage-text --coverage-clover=coverage.xml
- name: "Upload coverage reports to Codecov"
uses: codecov/codecov-action@v5.4.3
with:
token: ${{ secrets.CODECOV_TOKEN }}
slug: solidtime-io/solidtime
================================================
FILE: .github/workflows/pint.yml
================================================
name: PHP Linting
on: push
permissions:
contents: read
jobs:
pint:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Check code style"
uses: aglipanci/laravel-pint-action@2.5
with:
configPath: "pint.json"
================================================
FILE: .github/workflows/playwright.yml
================================================
name: Playwright Tests
on: [push]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shardIndex: [1, 2, 3, 4, 5, 6, 7, 8]
shardTotal: [8]
services:
mailpit:
image: 'axllent/mailpit:latest'
ports:
- 1025:1025
- 8025:8025
pgsql_test:
image: postgres:15
env:
PGPASSWORD: 'root'
POSTGRES_DB: 'laravel'
POSTGRES_USER: 'root'
POSTGRES_PASSWORD: 'root'
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Setup node"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv
coverage: none
- name: "Run composer install"
run: composer install -n --prefer-dist
- name: "Prepare Laravel Application"
run: |
cp .env.ci .env
php artisan key:generate
php artisan passport:keys
php artisan migrate --seed
- name: "Install dependencies"
run: npm ci
- name: "Build Frontend"
run: npm run build
- name: "Install FrankenPHP"
run: |
ARCH="$(uname -m)"
curl -fsSL "https://github.com/dunglas/frankenphp/releases/latest/download/frankenphp-linux-${ARCH}" -o /usr/local/bin/frankenphp
chmod +x /usr/local/bin/frankenphp
- name: "Run Laravel Octane Server"
run: php artisan octane:start --server=frankenphp --host=127.0.0.1 --port=8000 --workers=4 --max-requests=500 > /dev/null 2>&1 &
env:
OCTANE_SERVER: frankenphp
- name: "Install Playwright Browsers"
run: npx playwright install --with-deps
- name: "Run Playwright tests"
run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
env:
PLAYWRIGHT_BASE_URL: 'http://127.0.0.1:8000'
MAILPIT_BASE_URL: 'http://localhost:8025'
- name: "Upload blob report"
uses: actions/upload-artifact@v4
if: always()
with:
name: blob-report-${{ matrix.shardIndex }}
path: blob-report/
retention-days: 7
merge-reports:
if: always()
needs: [test]
runs-on: ubuntu-latest
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Setup node"
uses: actions/setup-node@v4
with:
node-version: '20.x'
- name: "Install dependencies"
run: npm ci
- name: "Download blob reports"
uses: actions/download-artifact@v4
with:
path: all-blob-reports
pattern: blob-report-*
merge-multiple: true
- name: "Merge reports"
run: npx playwright merge-reports --reporter html ./all-blob-reports
- name: "Upload merged HTML report"
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report/
retention-days: 30
================================================
FILE: .gitignore
================================================
/.phpunit.cache
node_modules
dist
/public/build
/public/hot
/public/storage
/public/css
/public/js
/public/vendor
/lang/vendor
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/coverage
/extensions
!/extensions/.gitkeep
!/extensions/extensions_autoload.php
/auth.json
/modules_statuses.json
/k8s
/_ide_helper.php
/.phpstorm.meta.php
/.rnd
/caddy
/frankenphp
/public/frankenphp-worker.php
/data
/config/caddy
/config/composer
================================================
FILE: .prettierignore
================================================
# Ignore build outputs
node_modules/
vendor/
storage/
bootstrap/cache/
public/build/
public/hot/
# Ignore lock files
package-lock.json
composer.lock
# Ignore generated files
*.min.js
*.min.css
# Ignore test results
test-results/
playwright-report/
# Ignore IDE files
.idea/
.vscode/
# Ignore OS files
.DS_Store
Thumbs.db
================================================
FILE: .prettierrc.json
================================================
{
"trailingComma": "es5",
"tabWidth": 4,
"singleQuote": true,
"bracketSameLine": true,
"quoteProps": "preserve",
"printWidth": 100
}
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Code of Conduct
The goal is to create a community that is open and welcoming to all individuals.
To achieve this, we have developed a code of conduct that outlines the expectations for behavior of all members of our community.
## Pledge
This community is founded on respect and understanding.
All members are expected to treat others with respect and empathy, and to not tolerate any form of discrimination,
harassment, or attacks.
## Expectations
Examples of behavior that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and sexual attention or advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate
and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits,
issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily
or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Contact
If you feel uncomfortable or believe that someone has violated the code of conduct, please contact us at [hello@solidtime.io](mailto:hello@solidtime.io).
We will thoroughly investigate the incident and aim for the best possible outcome.
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to solidtime
Contributions are greatly apprecited, please make sure to read the rules and vision for solidtime before contributing.
## Rules
### Issues for Bugs, Discussions for Feature requests
In order to keep the issues of the repository clean we decided to only use them for bugs. Feature Requests and enhancement are handled in discussions. This also helps us to see which feature requests are popular as they can be upvoted.
### Only work on approved issues
To respect your time and help us manage contributions effectively, please open an issue or start a discussion and wait for approval before submitting a pull request (PR). This does not apply to tiny fixes or changes however, please keep in mind that we might not merge PRs for various reasons.
### Contributor License Agreement
You'll also notice that we’ve set up a [Contributor License Agreement (CLA)](https://cla-assistant.io/solidtime-io/solidtime), which must be signed before any PR can be merged. Don’t worry - the process is quick and only takes a few clicks.
We want to be transparent about why we require the CLA and what it means for your contributions and the codebase. That’s why we’ve written a few paragraphs below outlining our plans and vision for solidtime in the **Vision** part of this document.
### Prevent Duplicate Work
Before you submit a new PR, make sure that none exists already. If you plan to work on an issue, make sure to let us and others know by commenting on the issue/discussion.
### Give context
Tell us what you thinking was behind the decisions you made while drafting the PR. Treat the PR itself as documentation for everyone who wants to go back and understand why certain decisions were made.
### Summarize your PR
Please make sure to include a short summary at the top of your PR to make it easy for us to quickly check what the PR is about, without looking at the code changes.
### Use Github Keywords and Auto-Link Issues
Use phrases like "Closes #123" or "Fixes #123" in the PR description to link the PR with the issue that you are adressing.
### Mention what you tested and how
Explain how you tested and validated the implementation.
### Keep Naming consistent
Look at existing code patterns and use naming conventions that already exist in the code base.
### Testing
We have an exhaustive test-suite of PHPUnit (Backend) and Playwright (Frontend) testing. Whereever applicable please make sure to write add tests to the codebase.
### Linting & Formatting
Make sure to run linting and formatting commands before you commit the changes.
For backend changes:
```
composer fix
composer analyse
```
For frontend changes:
```
npm run lint:fix
npm run format
```
## Vision
We started solidtime to provide an open infrastructure solution for time tracking—one that empowers teams and individuals to fully own their data, instead of depending on proprietary platforms. We believe infrastructure software should be open, accessible, and built to last. However, competing with established market leaders in this space requires long-term financial sustainability.
solidtime is licensed under the AGPL, which we believe is the best available license to strike a balance between openness and financial viability. The AGPL gives us, as the copyright holders, certain exclusive rights that we plan to leverage to fund development. To ensure we retain those rights across the entire codebase, we've put a CLA in place that contributors must sign before submitting code.
One of solidtime’s key advantages is that it's built to be self-hostable. This makes it a great solution for organizations like governments, healthcare providers, and enterprises that are required to keep data on their own infrastructure due to regulations or internal policies. These organizations may need custom licenses, integrations, or modifications that aren't suitable for the open-source version. To support them, we offer relicensed versions of solidtime along with support plans.
We’ll also provide proprietary extensions for solidtime. These will be available to enterprise customers with support plans, but also to individual users or teams who don’t need support, at much more accessible price points. For companies running solidtime on their own infrastructure, this is the easiest way to support the project while gaining additional functionality. While we plan to make it easier to build custom extensions in the future, our current APIs are still highly experimental.
Finally - and perhaps most importantly - we offer a hosted SaaS version called solidtime Cloud, for users who can’t or don’t want to run the software themselves. This version includes proprietary extensions, always runs the latest commit, and includes monitoring and billing features available exclusively on this hosted instance. We expect solidtime Cloud to play a critical role in funding the project long-term.
Having full control over the source code’s licensing also gives us the ability to change the license of the main project in the future. That said, we have no plans to do so and would only consider it in extreme cases - for example, if a malicious actor were to directly compete with our hosted service in a way that threatens the sustainability of the project, the legal interpretation of AGPL changes in a way that would make it unreasonable to use for certain companies, or a new similar license gains wide-spread adoption. Regardless, solidtime will always remain free to self-host for individuals and companies who use it as part of their work, and all previous releases will remain licensed under AGPL.
If you are using the open-source version of solidtime and want to support us, the best way to do so is to spread the word.
================================================
FILE: LICENSE.md
================================================
GNU Affero General Public License
=================================
_Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. <>_
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
## Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: **(1)** assert copyright on the software, and **(2)** offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
## TERMS AND CONDITIONS
### 0. Definitions
“This License” refers to version 3 of the GNU Affero General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this
License. Each licensee is addressed as “you”. “Licensees” and
“recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a “modified version” of the
earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based
on the Program.
To “propagate” a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices”
to the extent that it includes a convenient and prominently visible
feature that **(1)** displays an appropriate copyright notice, and **(2)**
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code
The “source code” for a work means the preferred form of the work
for making modifications to it. “Object code” means any non-source
form of a work.
A “Standard Interface” means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other
than the work as a whole, that **(a)** is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and **(b)** serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
“Major Component”, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
### 2. Basic Permissions
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
### 4. Conveying Verbatim Copies
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
### 5. Conveying Modified Source Versions
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified
it, and giving a relevant date.
* **b)** The work must carry prominent notices stating that it is
released under this License and any conditions added under section 7.
This requirement modifies the requirement in section 4 to
“keep intact all notices”.
* **c)** You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
* **d)** If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
“aggregate” if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
### 6. Conveying Non-Source Forms
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either **(1)** a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or **(2)** access to copy the
Corresponding Source from a network server at no charge.
* **c)** Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
* **d)** Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A “User Product” is either **(1)** a “consumer product”, which means any
tangible personal property which is normally used for personal, family,
or household purposes, or **(2)** anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, “normally used” refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
“Installation Information” for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
### 7. Additional Terms
“Additional permissions” are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or
authors of the material; or
* **e)** Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered “further
restrictions” within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
### 8. Termination
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated **(a)**
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and **(b)** permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
### 9. Acceptance Not Required for Having Copies
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
### 11. Patents
A “contributor” is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, “control” includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To “grant” such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either **(1)** cause the Corresponding Source to be so
available, or **(2)** arrange to deprive yourself of the benefit of the
patent license for this particular work, or **(3)** arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. “Knowingly relying” means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is “discriminatory” if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license **(a)** in connection with copies of the covered work
conveyed by you (or copies made from those copies), or **(b)** primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
### 12. No Surrender of Others' Freedom
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
### 13. Remote Network Interaction; Use with the GNU General Public License
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
### 14. Revised Versions of this License
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License “or any later version” applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
### 15. Disclaimer of Warranty
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
_END OF TERMS AND CONDITIONS_
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the “copyright” line and a pointer to where the full notice is found.
Copyright (C) 2024 Gregor Vostrak & Constantin Graf
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a “Source” link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a “copyright disclaimer” for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<>.
================================================
FILE: README.md
================================================
# solidtime - The modern Open-Source Time Tracker
[](https://github.com/solidtime-io/solidtime/blob/main/LICENSE.md)
[](https://codecov.io/gh/solidtime-io/solidtime)



solidtime is a modern open-source time tracking application for Freelancers and Agencies.
## Features
- Time tracking: Track your time with a modern and easy-to-use interface
- Projects: Create and manage projects and assign project members
- Tasks: Create and manage tasks and assign tasks to projects
- Clients: Create and manage clients and assign clients to projects
- Billable rates: Set billable rates for projects, project members, organization members and organizations
- Multiple organizations: Create and manage multiple organizations with one account
- Roles and permissions: Create and manage organizations
- Import: Import your time tracking data from other time tracking applications (Supported: Toggl, Clockify, Timeentry CSV)
## Self Hosting
If you are looking into self-hosting solidtime, you can find the guides [here](https://docs.solidtime.io/self-hosting/intro)
We also have an examples repository [here](https://github.com/solidtime-io/self-hosting-examples)
If you do not want to self-host solidtime or try it out you can sign up for [solidtime cloud](https://www.solidtime.io/)
## Issues & Feature Requests
If you find any **bugs in solidtime**, please feel free to [**open an issue**](https://github.com/solidtime-io/solidtime/issues/new) in this repository, with instructions on how to reproduce the bug.
If you have a **feature request**, please [**create a discussion**](https://github.com/solidtime-io/solidtime/discussions/new?category=feature-requests) in this repository.
## Contributing
Please open an issue or start a discussion and wait for approval before submitting a pull request. This does not apply to tiny fixes or changes however, please keep in mind that we might not merge PRs for various reasons.
**If you submit an AI slop pull request (especially without following the proper procedure), you will be banned from future contributions to solidtime.**
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.
## Security
Looking to report a vulnerability? Please refer our [SECURITY.md](./SECURITY.md) file.
## License
This project is open-source and available under the GNU Affero General Public License v3.0 (AGPL v3). Please see the [license file](LICENSE.md) for more information.
================================================
FILE: SECURITY.md
================================================
# Security Policy
## Reporting a Vulnerability
If you discover a security vulnerability regarding this project, please e-mail me to [security@solidtime.io](mailto:security@solidtime.io)!
================================================
FILE: app/Actions/Fortify/CreateNewUser.php
================================================
$input
*
* @throws ValidationException
*/
public function create(array $input): User
{
if (! config('app.enable_registration')) {
throw ValidationException::withMessages([
'email' => [__('Registration is disabled.')],
]);
}
Validator::make($input, [
'name' => [
'required',
'string',
'max:255',
],
'email' => [
'required',
'string',
'email:rfc,strict',
'max:255',
UniqueEloquent::make(User::class, 'email', function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->where('is_placeholder', '=', false);
}),
],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '',
'newsletter_consent' => [
'boolean',
],
])->validate();
$timezone = null;
if (array_key_exists('timezone', $input) && is_string($input['timezone'])) {
if (app(TimezoneService::class)->isValid($input['timezone'])) {
$timezone = $input['timezone'];
} else {
$timezone = app(TimezoneService::class)->mapLegacyTimezone($input['timezone']);
if ($timezone === null) {
Log::debug('Invalid timezone', ['timezone' => $input['timezone']]);
}
}
}
$ipLookupResponse = app(IpLookupServiceContract::class)->lookup(request()->ip());
$startOfWeek = Weekday::Monday;
$numberFormat = null;
$currencyFormat = null;
$dateFormat = null;
$intervalFormat = null;
$timeFormat = null;
$currency = null;
if ($ipLookupResponse !== null) {
$startOfWeek = $ipLookupResponse->startOfWeek ?? Weekday::Monday;
if ($timezone === null) {
$timezone = $ipLookupResponse->timezone;
}
$currency = $ipLookupResponse->currency;
}
$user = null;
DB::transaction(function () use (&$user, $input, $timezone, $startOfWeek, $currency, $numberFormat, $currencyFormat, $dateFormat, $intervalFormat, $timeFormat): void {
$userService = app(UserService::class);
$user = $userService->createUser(
$input['name'],
$input['email'],
$input['password'],
$timezone ?? 'UTC',
$startOfWeek,
$currency,
$numberFormat,
$currencyFormat,
$dateFormat,
$intervalFormat,
$timeFormat
);
});
$newsletterConsent = isset($input['newsletter_consent']) && (bool) $input['newsletter_consent'];
if ($newsletterConsent) {
NewsletterRegistered::dispatch($input['name'], $input['email'], $user->getKey());
}
return $user;
}
}
================================================
FILE: app/Actions/Fortify/PasswordValidationRules.php
================================================
*/
protected function passwordRules(): array
{
return ['required', 'string', Password::default(), 'confirmed'];
}
}
================================================
FILE: app/Actions/Fortify/ResetUserPassword.php
================================================
$input
*/
public function reset(User $user, array $input): void
{
Validator::make($input, [
'password' => $this->passwordRules(),
])->validate();
$user->forceFill([
'password' => Hash::make($input['password']),
])->save();
}
}
================================================
FILE: app/Actions/Fortify/UpdateUserPassword.php
================================================
$input
*/
public function update(User $user, array $input): void
{
Validator::make($input, [
'current_password' => ['required', 'string', 'current_password:web'],
'password' => $this->passwordRules(),
], [
'current_password.current_password' => __('The provided password does not match your current password.'),
])->validateWithBag('updatePassword');
$user->forceFill([
'password' => Hash::make($input['password']),
])->save();
}
}
================================================
FILE: app/Actions/Fortify/UpdateUserProfileInformation.php
================================================
$input
*
* @throws ValidationException
*/
public function update(User $user, array $input): void
{
Validator::make($input, [
'name' => [
'required',
'string',
'max:255',
],
'email' => [
'required',
'email',
'max:255',
UniqueEloquent::make(User::class, 'email')->ignore($user->id)->query(function (Builder $query) {
/** @var Builder $query */
return $query->where('is_placeholder', '=', false);
}),
],
'photo' => [
'nullable',
'mimes:jpg,jpeg,png',
'max:1024',
],
'timezone' => [
'required',
'timezone:all',
],
'week_start' => [
'required',
Rule::enum(Weekday::class),
],
])->validateWithBag('updateProfileInformation');
if (isset($input['photo'])) {
$user->updateProfilePhoto($input['photo']);
}
if ($input['email'] !== $user->email) {
$user->forceFill([
'name' => $input['name'],
'email' => $input['email'],
'email_verified_at' => null,
'timezone' => $input['timezone'],
'week_start' => $input['week_start'],
])->save();
$user->sendEmailVerificationNotification();
} else {
$user->forceFill([
'name' => $input['name'],
'timezone' => $input['timezone'],
'week_start' => $input['week_start'],
])->save();
}
}
}
================================================
FILE: app/Actions/Jetstream/AddOrganizationMember.php
================================================
authorize('addTeamMember', $organization); // TODO: refactor after owner refactoring
$this->validate($organization, $email, $role);
$newOrganizationMember = User::query()
->where('email', $email)
->where('is_placeholder', '=', false)
->firstOrFail();
app(MemberService::class)->addMember($newOrganizationMember, $organization, Role::from($role));
}
/**
* Validate the add member operation.
*/
protected function validate(Organization $organization, string $email, ?string $role): void
{
Validator::make([
'email' => $email,
'role' => $role,
], $this->rules())->after(
$this->ensureUserIsNotAlreadyOnTeam($organization, $email)
)->validateWithBag('addTeamMember');
}
/**
* Get the validation rules for adding a team member.
*
* @return array>
*/
protected function rules(): array
{
return [
'email' => [
'required',
'email',
ExistsEloquent::make(User::class, 'email', function (Builder $builder) {
/** @var Builder $builder */
return $builder->where('is_placeholder', '=', false);
})->withMessage(__('We were unable to find a registered user with this email address.')),
],
'role' => [
'required',
'string',
Rule::in([
Role::Admin->value,
Role::Manager->value,
Role::Employee->value,
]),
],
];
}
/**
* Ensure that the user is not already on the team.
*/
protected function ensureUserIsNotAlreadyOnTeam(Organization $team, string $email): Closure
{
return function ($validator) use ($team, $email): void {
$validator->errors()->addIf(
$team->hasRealUserWithEmail($email),
'email',
__('This user already belongs to the team.')
);
};
}
}
================================================
FILE: app/Actions/Jetstream/CreateOrganization.php
================================================
$input
*
* @throws AuthorizationException
* @throws ValidationException
*/
public function create(User $user, array $input): Organization
{
Gate::forUser($user)->authorize('create', Jetstream::newTeamModel());
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
])->validateWithBag('createTeam');
$ipLookupResponse = app(IpLookupServiceContract::class)->lookup(request()->ip());
$currency = null;
if ($ipLookupResponse !== null) {
$currency = $ipLookupResponse->currency;
}
$organization = app(OrganizationService::class)->createOrganization(
$input['name'],
$user,
false,
$currency
);
$user->switchTeam($organization);
// Note: The refresh is necessary for currently unknown reasons. Do not remove it.
$organization = $organization->refresh();
AfterCreateOrganization::dispatch($organization);
return $organization;
}
}
================================================
FILE: app/Actions/Jetstream/DeleteOrganization.php
================================================
deleteOrganization($organization);
}
}
================================================
FILE: app/Actions/Jetstream/DeleteUser.php
================================================
deleteUser($user);
} catch (ApiException $exception) {
throw ValidationException::withMessages([
'password' => $exception->getTranslatedMessage(),
]);
}
}
}
================================================
FILE: app/Actions/Jetstream/InviteOrganizationMember.php
================================================
$input
*
* @throws AuthorizationException
* @throws ValidationException
*/
public function update(User $user, Organization $organization, array $input): void
{
Gate::forUser($user)->authorize('update', $organization);
Validator::make($input, [
'name' => [
'required',
'string',
'max:255',
],
'currency' => [
'required',
'string',
new CurrencyRule,
],
])->validateWithBag('updateTeamName');
$organization->forceFill([
'name' => $input['name'],
'currency' => $input['currency'],
])->save();
}
}
================================================
FILE: app/Actions/Jetstream/ValidateOrganizationDeletion.php
================================================
userHas($organization, $user, 'organizations:delete')) {
throw new AuthorizationException;
}
}
}
================================================
FILE: app/Console/Commands/Admin/OrganizationDeleteCommand.php
================================================
argument('organization');
if (! Str::isUuid($organizationId)) {
$this->error('Organization ID must be a valid UUID.');
return self::FAILURE;
}
/** @var Organization|null $organization */
$organization = Organization::find($organizationId);
if ($organization === null) {
$this->error('Organization with ID '.$organizationId.' not found.');
return self::FAILURE;
}
$this->info('Deleting organization with ID '.$organization->getKey());
$deletionService->deleteOrganization($organization);
$this->info('Organization with ID '.$organization->getKey().' has been deleted.');
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Admin/UserCreateCommand.php
================================================
argument('name');
$email = $this->argument('email');
$askForPassword = (bool) $this->option('ask-for-password');
$verifyEmail = (bool) $this->option('verify-email');
if (User::query()->where('email', $email)->where('is_placeholder', '=', false)->exists()) {
$this->error('User with email "'.$email.'" already exists.');
return self::FAILURE;
}
if ($askForPassword) {
$outputPassword = false;
$password = $this->secret('Enter the password');
} else {
$outputPassword = true;
$password = bin2hex(random_bytes(16));
}
$user = null;
DB::transaction(function () use (&$user, $name, $email, $password, $verifyEmail): void {
$user = app(UserService::class)->createUser(
$name,
$email,
$password,
'UTC',
Weekday::Monday,
null,
verifyEmail: $verifyEmail
);
});
/** @var Organization|null $organization */
$organization = $user->ownedTeams->first();
if ($organization === null) {
throw new LogicException('User does not have an organization');
}
$this->info('Created user "'.$name.'" ("'.$email.'")');
$this->line('ID: '.$user->getKey());
$this->line('Name: '.$name);
$this->line('Email: '.$email);
if ($outputPassword) {
$this->line('Password: '.$password);
}
$this->line('Timezone: '.$user->timezone);
$this->line('Week start: '.$user->week_start->value);
// Organization
$this->line('Currency: '.$organization->currency);
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Admin/UserVerifyCommand.php
================================================
argument('email');
$this->info('Start verifying user with email "'.$email.'"');
/** @var User|null $user */
$user = User::query()->where('email', $email)
->where('is_placeholder', '=', false)
->first();
if ($user === null) {
$this->error('User with email "'.$email.'" not found.');
return self::FAILURE;
}
if ($user->hasVerifiedEmail()) {
$this->info('User with email "'.$email.'" already verified.');
return self::FAILURE;
}
$user->markEmailAsVerified();
event(new Verified($user));
$this->info('User with email "'.$email.'" has been verified.');
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Auth/AuthSendReminderForExpiringApiTokensCommand.php
================================================
option('dry-run');
if ($dryRun) {
$this->comment('Running in dry-run mode. No emails will be sent and nothing will be saved to the database.');
}
$this->comment('Sending reminder emails about expiring API tokens...');
$sentMails = 0;
Token::query()
->where('expires_at', '<=', Carbon::now()->addDays(7))
->whereNull('reminder_sent_at')
->with([
'client',
'user',
])
->whereHas('user', function (Builder $query): void {
/** @var Builder $query */
$query->where('is_placeholder', '=', false);
})
->isApiToken(true)
->orderBy('created_at', 'asc')
->chunk(500, function (Collection $tokens) use ($dryRun, &$sentMails): void {
/** @var Collection $tokens */
foreach ($tokens as $token) {
$user = $token->user;
$this->info('Start sending email to user "'.$user->email.'" ('.$user->getKey().') reminding about API token '.$token->getKey());
$sentMails++;
if (! $dryRun) {
Mail::to($user->email)
->queue(new AuthApiTokenExpirationReminderMail($token, $user));
$token->reminder_sent_at = Carbon::now();
$token->save();
}
}
});
$this->comment('Finished sending '.$sentMails.' expiring API token emails...');
$this->comment('Sent emails about expired API tokens');
$sentMails = 0;
Token::query()
->where('expires_at', '<=', Carbon::now())
->whereNull('expired_info_sent_at')
->with([
'client',
'user',
])
->whereHas('user', function (Builder $query): void {
/** @var Builder $query */
$query->where('is_placeholder', '=', false);
})
->isApiToken(true)
->orderBy('created_at', 'asc')
->chunk(500, function (Collection $tokens) use ($dryRun, &$sentMails): void {
/** @var Collection $tokens */
foreach ($tokens as $token) {
$user = $token->user;
$this->info('Start sending email to user "'.$user->email.'" ('.$user->getKey().') about expired API token '.$token->getKey());
$sentMails++;
if (! $dryRun) {
Mail::to($user->email)
->queue(new AuthApiTokenExpiredMail($token, $user));
$token->expired_info_sent_at = Carbon::now();
$token->save();
}
}
});
$this->comment('Finished sending '.$sentMails.' expired API token emails...');
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Correction/CorrectionPlaceholderMembersCommand.php
================================================
comment('Sets all members who belong to a placeholder user to role placeholder...');
$dryRun = (bool) $this->option('dry-run');
if ($dryRun) {
$this->comment('Running in dry-run mode. Nothing will be saved to the database.');
}
$members = Member::query()
->where('role', '!=', Role::Placeholder->value)
->whereHas('user', function (Builder $builder): void {
/** @var Builder $builder */
$builder->where('is_placeholder', '=', true);
})
->get();
foreach ($members as $member) {
/** @var Member $member */
$member->role = Role::Placeholder->value;
if (! $dryRun) {
$member->save();
}
$this->line('Set role of member (id='.$member->getKey().') to placeholder');
}
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Report/ReportSetExpiredToPrivateCommand.php
================================================
comment('Makes public reports private if the public_until date has passed...');
$dryRun = (bool) $this->option('dry-run');
if ($dryRun) {
$this->comment('Running in dry-run mode. Nothing will be saved to the database.');
}
$resetReports = 0;
Report::query()
->where('public_until', '<', Carbon::now())
->orderBy('created_at', 'asc')
->chunk(500, function (Collection $reports) use ($dryRun, &$resetReports): void {
/** @var Collection $reports */
foreach ($reports as $report) {
$publicUntil = $report->public_until;
if ($publicUntil === null) {
throw new LogicException('public_until should not be null');
}
$this->info('Make report "'.$report->name.'" ('.$report->getKey().') private, expired: '.
$publicUntil->toIso8601ZuluString().' ('.$publicUntil->diffForHumans().')');
$resetReports++;
if (! $dryRun) {
$report->is_public = false;
$report->share_secret = null;
$report->save();
}
}
});
$this->comment('Finished setting '.$resetReports.' expired reports to private...');
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/SelfHost/SelfHostCheckForUpdateCommand.php
================================================
checkForUpdate();
if ($latestVersion === null) {
$this->error('Failed to check for update, check the logs for more information.');
return self::FAILURE;
}
// Note: Cache for 13 hours, because the command runs twice daily (every 12 hours).
Cache::put('latest_version', $latestVersion, 60 * 60 * 12);
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/SelfHost/SelfHostDatabaseConsistency.php
================================================
select(['time_entries.id as id'])
->join('tasks', 'time_entries.task_id', '=', 'tasks.id')
->where('tasks.project_id', '!=', DB::raw('time_entries.project_id'))
->get();
$this->logProblems($problems, 'Time entries have a task that does not belong to the project of the time entry', $hadAProblem);
// Client id is the client id of the project
$problems = DB::table('time_entries')
->select(['time_entries.id as id'])
->join('projects', 'time_entries.project_id', '=', 'projects.id')
->where(DB::raw('coalesce(projects.client_id::varchar, \'\')'), '!=', DB::raw('coalesce(time_entries.client_id::varchar, \'\')'))
->get();
$this->logProblems($problems, 'Time entries have a client that does not match the client of the project', $hadAProblem);
// Client id can only be not null if the project id is not null
$problems = DB::table('time_entries')
->select(['time_entries.id as id'])
->whereNotNull('client_id')
->whereNull('project_id')
->get();
$this->logProblems($problems, 'Time entries have a client but no project', $hadAProblem);
// Every user needs to be a member of at least one organization
$problems = DB::table('users')
->select(['users.id as id'])
->leftJoin('members', 'users.id', '=', 'members.user_id')
->whereNull('members.id')
->get();
$this->logProblems($problems, 'Users are not member of any organization', $hadAProblem);
// Every organization needs at least an owner
$problems = DB::table('organizations')
->select(['organizations.id as id'])
->leftJoin('members', function (JoinClause $join): void {
$join->on('organizations.id', '=', 'members.organization_id')
->where('members.role', '=', 'owner');
})
->whereNull('members.id')
->get();
$this->logProblems($problems, 'Organizations without an owner', $hadAProblem);
// Every member can only have one running time entry
$problems = DB::table('time_entries')
->select(['user_id as id'])
->whereNull('end')
->groupBy('user_id')
->havingRaw('count(*) > 1')
->get(['user_id', DB::raw('count(*) as count')]);
$this->logProblems($problems, 'Users with more than one running time entry', $hadAProblem);
// Users have a current organization that they are not a member of
$problems = DB::table('users')
->select(['users.id as id'])
->whereNotNull('current_team_id')
->whereNotIn('current_team_id', function (Builder $query): void {
$query->select('organization_id')
->from('members')
->whereColumn('members.user_id', 'users.id');
})->get();
$this->logProblems($problems, 'Users have a current organization that they are not a member of', $hadAProblem);
return $hadAProblem ? self::FAILURE : self::SUCCESS;
}
/**
* @param Collection $problems
*/
private function logProblems(Collection $problems, string $message, bool &$hadAProblem): void
{
$message = 'Consistency problem: '.$message;
if ($problems->isNotEmpty()) {
$ids = $problems->pluck('id');
$hadAProblem = true;
Log::error($message, [
'ids' => $ids,
]);
$error = $message;
foreach ($ids as $id) {
$error .= "\n - ".$id;
}
$this->error($error);
}
}
}
================================================
FILE: app/Console/Commands/SelfHost/SelfHostGenerateKeysCommand.php
================================================
option('format');
$key = RSA::createKey((int) $this->option('length'));
$multiLine = (bool) $this->option('multi-line');
$publicKey = (string) $key->getPublicKey();
$privateKey = (string) $key;
$appKey = 'base64:'.base64_encode(Encrypter::generateKey(config('app.cipher')));
if ($format === 'env') {
$this->line('APP_KEY="'.$appKey.'"');
if ($multiLine) {
$this->line('PASSPORT_PRIVATE_KEY="'.Str::replace("\r\n", "\n", $privateKey).'"');
$this->line('PASSPORT_PUBLIC_KEY="'.Str::replace("\r\n", "\n", $publicKey).'"');
} else {
$this->line('PASSPORT_PRIVATE_KEY="'.Str::replace("\r\n", '\n', $privateKey).'"');
$this->line('PASSPORT_PUBLIC_KEY="'.Str::replace("\r\n", '\n', $publicKey).'"');
}
} elseif ($format === 'yaml') {
$this->line('APP_KEY: "'.$appKey.'"');
$this->line("PASSPORT_PRIVATE_KEY: |\n ".Str::replace("\r\n", "\n ", $privateKey));
$this->line("PASSPORT_PUBLIC_KEY: |\n ".Str::replace("\r\n", "\n ", $publicKey));
} else {
$this->error('Invalid format');
return self::FAILURE;
}
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/SelfHost/SelfHostTelemetryCommand.php
================================================
telemetry();
if (! $success) {
$this->error('Failed to send telemetry data, check the logs for more information.');
return self::FAILURE;
}
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Test/TestEmailCommand.php
================================================
argument('email');
Mail::raw('Hello World!', function (Message $message) use ($email): void {
$message->to($email)
->subject('Test Email')
->html('Hello World!
');
});
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Test/TestJobCommand.php
================================================
option('fail');
TestJob::dispatch($user, 'Test job message.', $fail);
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/Test/TestOutputCommand.php
================================================
info('Test command output');
$this->error('Test command output error');
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Commands/TimeEntry/TimeEntrySendStillRunningMailsCommand.php
================================================
comment('Sending still running time entry emails...');
$dryRun = (bool) $this->option('dry-run');
if ($dryRun) {
$this->comment('Running in dry-run mode. No emails will be sent and nothing will be saved to the database.');
}
$sentMails = 0;
TimeEntry::query()
->whereNull('end')
->where('start', '<', now()->subHours(8))
->whereNull('still_active_email_sent_at')
->with([
'user',
])
->whereHas('user', function (Builder $query): void {
/** @var Builder $query */
$query->where('is_placeholder', '=', false);
})
->orderBy('created_at', 'asc')
->chunk(500, function (Collection $timeEntries) use ($dryRun, &$sentMails): void {
/** @var Collection $timeEntries */
foreach ($timeEntries as $timeEntry) {
$user = $timeEntry->user;
$this->info('Start sending email to user "'.$user->email.'" ('.$user->getKey().') for time entry '.$timeEntry->getKey());
$sentMails++;
if (! $dryRun) {
Mail::to($user->email)
->queue(new TimeEntryStillRunningMail($timeEntry, $user));
$timeEntry->still_active_email_sent_at = Carbon::now();
$timeEntry->save();
}
}
});
$this->comment('Finished sending '.$sentMails.' still running time entry emails...');
return self::SUCCESS;
}
}
================================================
FILE: app/Console/Kernel.php
================================================
command('time-entry:send-still-running-mails')
->when(fn (): bool => config('scheduling.tasks.time_entry_send_still_running_mails'))
->everyTenMinutes();
$schedule->command('auth:send-mails-expiring-api-tokens')
->when(fn (): bool => config('scheduling.tasks.auth_send_mails_expiring_api_tokens'))
->everyTenMinutes();
if (config('app.key') && (config('scheduling.tasks.self_hosting_check_for_update') || config('scheduling.tasks.self_hosting_telemetry'))) {
// Convert string to a stable integer for seeding
/** @var int $seed Take the first 8 hex chars → 32-bit int */
$seed = hexdec(substr(hash('md5', config('app.key')), 0, 8));
$seed = abs($seed); // Ensure it's positive
mt_srand($seed);
$firstHour = mt_rand(0, 23);
$secondHour = ($firstHour + 12) % 24;
$minuteOffset = mt_rand(0, 59);
mt_srand(null); // Reset the random number generator
if (config('scheduling.tasks.self_hosting_check_for_update')) {
$schedule->command('self-host:check-for-update')
->twiceDailyAt($firstHour, $secondHour, $minuteOffset);
}
if (config('scheduling.tasks.self_hosting_telemetry')) {
$schedule->command('self-host:telemetry')
->twiceDailyAt($firstHour, $secondHour, $minuteOffset);
}
}
$schedule->command('self-host:database-consistency')
->when(fn (): bool => config('scheduling.tasks.self_hosting_database_consistency'))
->everySixHours();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
}
}
================================================
FILE: app/Enums/CurrencyFormat.php
================================================
*/
public static function toSelectArray(): array
{
$selectArray = [];
foreach (self::values() as $value) {
$selectArray[(string) $value] = (string) __('enum.currency_format.'.$value);
}
return $selectArray;
}
}
================================================
FILE: app/Enums/DateFormat.php
================================================
value) {
self::PointSeparatedDMYYYY->value => 'j.n.Y',
self::SlashSeparatedMMDDYYYY->value => 'm/d/Y',
self::SlashSeparatedDDMMYYYY->value => 'd/m/Y',
self::HyphenSeparatedDDMMYYY->value => 'd-m-Y',
self::HyphenSeparatedMMDDDYYYY->value => 'm-d-Y',
self::HyphenSeparatedYYYYMMDD->value => 'Y-m-d',
};
}
/**
* @return array
*/
public static function toSelectArray(): array
{
$selectArray = [];
foreach (self::values() as $value) {
$selectArray[(string) $value] = (string) __('enum.date_format.'.$value);
}
return $selectArray;
}
}
================================================
FILE: app/Enums/ExportFormat.php
================================================
'csv',
self::PDF => 'pdf',
self::XLSX => 'xlsx',
self::ODS => 'ods',
};
}
public function getExportPackageType(): string
{
return match ($this) {
self::CSV => Excel::CSV,
self::PDF => Excel::MPDF,
self::XLSX => Excel::XLSX,
self::ODS => Excel::ODS,
};
}
}
================================================
FILE: app/Enums/IntervalFormat.php
================================================
*/
public static function toSelectArray(): array
{
$selectArray = [];
foreach (self::values() as $value) {
$selectArray[(string) $value] = (string) __('enum.interval_format.'.$value);
}
return $selectArray;
}
}
================================================
FILE: app/Enums/NumberFormat.php
================================================
*/
public static function toSelectArray(): array
{
$selectArray = [];
foreach (self::values() as $value) {
$selectArray[(string) $value] = (string) __('enum.number_format.'.$value);
}
return $selectArray;
}
}
================================================
FILE: app/Enums/Role.php
================================================
TimeEntryAggregationType::Day,
TimeEntryAggregationTypeInterval::Week => TimeEntryAggregationType::Week,
TimeEntryAggregationTypeInterval::Month => TimeEntryAggregationType::Month,
TimeEntryAggregationTypeInterval::Year => TimeEntryAggregationType::Year,
};
}
public function toInterval(): ?TimeEntryAggregationTypeInterval
{
return match ($this) {
TimeEntryAggregationType::Day => TimeEntryAggregationTypeInterval::Day,
TimeEntryAggregationType::Week => TimeEntryAggregationTypeInterval::Week,
TimeEntryAggregationType::Month => TimeEntryAggregationTypeInterval::Month,
TimeEntryAggregationType::Year => TimeEntryAggregationTypeInterval::Year,
default => null
};
}
}
================================================
FILE: app/Enums/TimeEntryAggregationTypeInterval.php
================================================
*/
public static function toSelectArray(): array
{
$selectArray = [];
foreach (self::values() as $value) {
$selectArray[(string) $value] = (string) __('enum.time_format.'.$value);
}
return $selectArray;
}
}
================================================
FILE: app/Enums/Weekday.php
================================================
Weekday::Sunday,
Weekday::Tuesday => Weekday::Monday,
Weekday::Wednesday => Weekday::Tuesday,
Weekday::Thursday => Weekday::Wednesday,
Weekday::Friday => Weekday::Thursday,
Weekday::Saturday => Weekday::Friday,
Weekday::Sunday => Weekday::Saturday,
};
}
public function carbonWeekDay(): int
{
return match ($this) {
Weekday::Monday => Carbon::MONDAY,
Weekday::Tuesday => Carbon::TUESDAY,
Weekday::Wednesday => Carbon::WEDNESDAY,
Weekday::Thursday => Carbon::THURSDAY,
Weekday::Friday => Carbon::FRIDAY,
Weekday::Saturday => Carbon::SATURDAY,
Weekday::Sunday => Carbon::SUNDAY,
};
}
/**
* @return array
*/
public static function toSelectArray(): array
{
return [
Weekday::Monday->value => __('enum.weekday.'.Weekday::Monday->value),
Weekday::Tuesday->value => __('enum.weekday.'.Weekday::Tuesday->value),
Weekday::Wednesday->value => __('enum.weekday.'.Weekday::Wednesday->value),
Weekday::Thursday->value => __('enum.weekday.'.Weekday::Thursday->value),
Weekday::Friday->value => __('enum.weekday.'.Weekday::Friday->value),
Weekday::Saturday->value => __('enum.weekday.'.Weekday::Saturday->value),
Weekday::Sunday->value => __('enum.weekday.'.Weekday::Sunday->value),
];
}
}
================================================
FILE: app/Events/AfterCreateOrganization.php
================================================
organization = $organization;
}
}
================================================
FILE: app/Events/BeforeOrganizationDeletion.php
================================================
organization = $organization;
}
}
================================================
FILE: app/Events/DatabaseSeederAfterSeed.php
================================================
member = $member;
$this->organization = $organization;
}
}
================================================
FILE: app/Events/MemberRemoved.php
================================================
member = $member;
$this->organization = $organization;
}
}
================================================
FILE: app/Events/NewsletterRegistered.php
================================================
name = $name;
$this->email = $email;
$this->id = $id;
}
}
================================================
FILE: app/Exceptions/Api/ApiException.php
================================================
json([
'error' => true,
'key' => $this->getKey(),
'message' => $this->getTranslatedMessage(),
], 400);
}
/**
* Get the key for the exception.
*/
public function getKey(): string
{
$key = static::KEY;
if ($key === ApiException::KEY) {
throw new LogicException('API exceptions need the KEY constant defined.');
}
return $key;
}
/**
* Get the translated message for the exception.
*/
public function getTranslatedMessage(): string
{
return __('exceptions.api.'.$this->getKey());
}
/**
* Report the exception.
*
* @return bool true means the exception handler will not report it again
*/
public function report(): bool
{
// TODO: temporary activated
return false;
}
}
================================================
FILE: app/Exceptions/Api/CanNotDeleteUserWhoIsOwnerOfOrganizationWithMultipleMembers.php
================================================
modelToDelete = $modelToDelete;
$this->modelInUse = $modelInUse;
}
public const string KEY = 'entity_still_in_use';
/**
* Get the translated message for the exception.
*/
#[\Override]
public function getTranslatedMessage(): string
{
return __('exceptions.api.'.$this->getKey(), [
'modelToDelete' => __('validation.entities.'.$this->modelToDelete),
'modelInUse' => __('validation.entities.'.$this->modelInUse),
]);
}
}
================================================
FILE: app/Exceptions/Api/FeatureIsNotAvailableInFreePlanApiException.php
================================================
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e): void {
//
});
}
public function render($request, Throwable $e): Response|RedirectResponse
{
$response = parent::render($request, $e);
if ($response->getStatusCode() === 419) {
return back()->with([
'message' => 'The page expired, please try again.',
]);
}
return $response;
}
}
================================================
FILE: app/Exceptions/MovedToApiException.php
================================================
preloadedResolverData['ip_address'] ?? Request::ip();
if ($ip !== null) {
$ip = self::anonymizeIpAddress($ip);
}
return $ip;
}
}
================================================
FILE: app/Extensions/Fortify/CustomLoginResponse.php
================================================
pull('url.intended', route('dashboard', [], false));
return $request->wantsJson()
? response()->json(['two_factor' => false])
: Inertia::location($redirectPath);
}
}
================================================
FILE: app/Extensions/Fortify/CustomTwoFactorLoginResponse.php
================================================
pull('url.intended', route('dashboard', [], false));
return $request->wantsJson()
? new JsonResponse('', 204)
: Inertia::location($redirectPath);
}
}
================================================
FILE: app/Extensions/Scramble/ApiExceptionTypeToSchema.php
================================================
isInstanceOf(ApiException::class);
}
public function toResponse(Type $type): Response
{
$validationResponseBodyType = (new OpenApiTypes\ObjectType)
->addProperty(
'error',
(new OpenApiTypes\BooleanType)
->setDescription('Whether the response is an error.')
)
->addProperty(
'key',
(new OpenApiTypes\StringType)
->setDescription('Error key.')
)
->addProperty(
'message',
(new OpenApiTypes\StringType)
->setDescription('Error message.')
)
->setRequired(['error', 'key', 'message']);
return Response::make(400)
->description('API exception')
->setContent(
'application/json',
Schema::fromType($validationResponseBodyType)
);
}
public function reference(ObjectType $type): Reference
{
return new Reference('responses', Str::start($type->name, '\\'), $this->components);
}
}
================================================
FILE: app/Extensions/Scramble/PaginatedResourceCollectionTypeToSchema.php
================================================
isInstanceOf(PaginatedResourceCollection::class);
}
public function toSchema(Type $type): ?OpenApiObjectType
{
/** @var Type|null $collectingClassType */
$collectingClassType = $type->templateTypes[0] ?? null;
if (! $collectingClassType instanceof ObjectType) {
return null;
}
if (! $collectingClassType->isInstanceOf(JsonResource::class) && ! $collectingClassType->isInstanceOf(Model::class)) {
return null;
}
$collectingType = $this->openApiTransformer->transform($collectingClassType);
$newType = new OpenApiObjectType;
$newType->addProperty('data', (new ArrayType)->setItems($collectingType));
if ($type instanceof ObjectType && $type->isInstanceOf(TimeEntryCollection::class)) {
$newType->addProperty(
'meta',
(new OpenApiObjectType)
->addProperty('total', (new IntegerType)->setDescription('Total number of items being paginated.'))
->setRequired(['total'])
);
$newType->setRequired(['data', 'meta']);
} else {
$newType->addProperty(
'links',
(new OpenApiObjectType)
->addProperty('first', (new StringType)->nullable(true))
->addProperty('last', (new StringType)->nullable(true))
->addProperty('prev', (new StringType)->nullable(true))
->addProperty('next', (new StringType)->nullable(true))
->setRequired(['first', 'last', 'prev', 'next'])
);
$newType->addProperty(
'meta',
(new OpenApiObjectType)
->addProperty('current_page', new IntegerType)
->addProperty('from', (new IntegerType)->nullable(true))
->addProperty('last_page', new IntegerType)
->addProperty('links', (new ArrayType)->setItems(
(new OpenApiObjectType)
->addProperty('url', (new StringType)->nullable(true))
->addProperty('label', new StringType)
->addProperty('active', new BooleanType)
->setRequired(['url', 'label', 'active'])
)->setDescription('Generated paginator links.'))
->addProperty('path', (new StringType)->nullable(true)->setDescription('Base path for paginator generated URLs.'))
->addProperty('per_page', (new IntegerType)->setDescription('Number of items shown per page.'))
->addProperty('to', (new IntegerType)->nullable(true)->setDescription('Number of the last item in the slice.'))
->addProperty('total', (new IntegerType)->setDescription('Total number of items being paginated.'))
->setRequired(['current_page', 'from', 'last_page', 'links', 'path', 'per_page', 'to', 'total'])
);
$newType->setRequired(['data', 'links', 'meta']);
}
return $newType;
}
/**
* @param Generic $type
*/
public function toResponse(Type $type): ?Response
{
/** @var ObjectType|null $collectingClassType */
$collectingClassType = $type->templateTypes[0] ?? null;
if (! $collectingClassType instanceof ObjectType) {
return null;
}
$type = $this->toSchema($type);
return Response::make(200)
->description('Paginated set of `'.$this->components->uniqueSchemaName($collectingClassType->name).'`')
->setContent('application/json', Schema::fromType($type));
}
}
================================================
FILE: app/Filament/Resources/AuditResource/Pages/CreateAudit.php
================================================
schema([
Forms\Components\TextInput::make('user_type')
->maxLength(255),
Forms\Components\TextInput::make('user_id'),
Forms\Components\TextInput::make('event')
->required()
->maxLength(255),
Forms\Components\TextInput::make('auditable_type')
->required()
->maxLength(255),
Forms\Components\TextInput::make('auditable_id')
->required(),
PrettyJsonField::make('old_values'),
PrettyJsonField::make('new_values'),
Forms\Components\Textarea::make('url'),
Forms\Components\TextInput::make('ip_address'),
Forms\Components\TextInput::make('user_agent')
->maxLength(1023),
Forms\Components\TextInput::make('tags')
->maxLength(255),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('user.name'),
Tables\Columns\TextColumn::make('event'),
Tables\Columns\TextColumn::make('auditable_type'),
Tables\Columns\TextColumn::make('auditable_id'),
IconColumn::make('was_command')
->getStateUsing(fn (Audit $record) => Str::startsWith($record->url, 'artisan '))
->boolean(),
Tables\Columns\TextColumn::make('created_at')
->sortable()
->dateTime(),
Tables\Columns\TextColumn::make('updated_at')
->sortable()
->dateTime(),
])
->filters([
//
])
->actions([
Tables\Actions\ViewAction::make(),
])
->bulkActions([
])
->defaultSort('created_at', 'desc');
}
public static function getRelations(): array
{
return [
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListAudits::route('/'),
'create' => Pages\CreateAudit::route('/create'),
'view' => Pages\ViewAudit::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Resources/ClientResource/Pages/CreateClient.php
================================================
icon('heroicon-m-trash'),
];
}
}
================================================
FILE: app/Filament/Resources/ClientResource/Pages/ListClients.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/ClientResource.php
================================================
schema([
TextInput::make('name')
->label('Name')
->required(),
Select::make('organization_id')
->relationship(name: 'organization', titleAttribute: 'name')
->label('Organization')
->searchable(['name'])
->required(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->label('Name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('organization.name')
->sortable()
->label('Organization'),
Tables\Columns\TextColumn::make('created_at')
->label('Created at')
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated at')
->sortable(),
])
->defaultSort('created_at', 'desc')
->filters([
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListClients::route('/'),
'create' => Pages\CreateClient::route('/create'),
'edit' => Pages\EditClient::route('/{record}/edit'),
];
}
}
================================================
FILE: app/Filament/Resources/FailedJobResource/Pages/ListFailedJobs.php
================================================
icon('heroicon-o-arrow-path')
->label('Retry all')
->requiresConfirmation()
->action(function (): void {
Artisan::call('queue:retry all');
Notification::make()
->title('All failed jobs have been pushed back onto the queue.')
->success()
->send();
}),
Action::make('delete_all')
->icon('heroicon-o-trash')
->label('Delete all')
->requiresConfirmation()
->color('danger')
->action(function (): void {
FailedJob::truncate();
Notification::make()
->title('All failed jobs have been removed.')
->success()
->send();
}),
];
}
}
================================================
FILE: app/Filament/Resources/FailedJobResource/Pages/ViewFailedJobs.php
================================================
count();
}
public static function form(Form $form): Form
{
return $form
->schema([
TextInput::make('uuid')->disabled()->columnSpan(4),
TextInput::make('failed_at')->disabled(),
TextInput::make('id')->disabled(),
TextInput::make('connection')->disabled(),
TextInput::make('queue')->disabled(),
// make text a little bit smaller because often a complete Stack Trace is shown:
TextArea::make('exception')->disabled()->columnSpan(4)->extraInputAttributes(['style' => 'font-size: 80%;']),
PrettyJsonField::make('payload')->disabled()->columnSpan(4),
])->columns(4);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('id', 'desc')
->columns([
TextColumn::make('id')->sortable()->searchable()->toggleable(),
TextColumn::make('failed_at')->sortable()->searchable(false)->toggleable(),
TextColumn::make('exception')
->sortable()
->searchable()
->toggleable()
->wrap()
->limit(200)
->tooltip(fn (FailedJob $record) => "{$record->failed_at} UUID: {$record->uuid}; Connection: {$record->connection}; Queue: {$record->queue};"),
TextColumn::make('uuid')->sortable()->searchable()->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('connection')->sortable()->searchable()->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('queue')->sortable()->searchable()->toggleable(isToggledHiddenByDefault: true),
])
->filters([])
->bulkActions([
BulkAction::make('retry')
->icon('heroicon-o-arrow-path')
->label('Retry selected')
->requiresConfirmation()
->action(function (Collection $records): void {
/** @var FailedJob $record */
foreach ($records as $record) {
Artisan::call("queue:retry {$record->uuid}");
}
Notification::make()
->title("{$records->count()} jobs have been pushed back onto the queue.")
->success()
->send();
}),
DeleteBulkAction::make(),
])
->actions([
DeleteAction::make(),
ViewAction::make(),
Action::make('retry')
->icon('heroicon-o-arrow-path')
->label('Retry')
->requiresConfirmation()
->action(function (FailedJob $record): void {
Artisan::call("queue:retry {$record->uuid}");
Notification::make()
->title("The job with uuid '{$record->uuid}' has been pushed back onto the queue.")
->success()
->send();
}),
]);
}
public static function getPages(): array
{
return [
'index' => ListFailedJobs::route('/'),
'view' => ViewFailedJobs::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Resources/OrganizationInvitationResource/Pages/EditOrganizationInvitation.php
================================================
icon('heroicon-m-trash'),
];
}
}
================================================
FILE: app/Filament/Resources/OrganizationInvitationResource/Pages/ListOrganizationInvitations.php
================================================
icon('heroicon-s-pencil'),
];
}
}
================================================
FILE: app/Filament/Resources/OrganizationInvitationResource.php
================================================
columns(1)
->schema([
Forms\Components\TextInput::make('email')
->label('Email')
->disabledOn(['edit'])
->required(),
Select::make('role')
->options(Role::class),
Forms\Components\Select::make('organization_id')
->label('Organization')
->relationship(name: 'organization', titleAttribute: 'name')
->searchable(['name'])
->disabledOn(['edit'])
->required(),
Forms\Components\DateTimePicker::make('created_at')
->label('Created At')
->hiddenOn(['create'])
->disabled(),
Forms\Components\DateTimePicker::make('updated_at')
->label('Updated At')
->hiddenOn(['create'])
->disabled(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('organization.name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('email')
->sortable(),
Tables\Columns\TextColumn::make('role'),
Tables\Columns\TextColumn::make('created_at')
->label('Created At')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated At')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('created_at', 'desc')
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\BulkAction::make('resend')
->label('Resend')
->action(function (Collection $records): void {
foreach ($records as $organizationInvite) {
app(OrganizationInvitationService::class)->resend($organizationInvite);
}
}),
]),
]);
}
public static function getRelations(): array
{
return [
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListOrganizationInvitations::route('/'),
'edit' => Pages\EditOrganizationInvitation::route('/{record}/edit'),
'view' => Pages\ViewOrganizationInvitation::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Resources/OrganizationResource/Actions/DeleteOrganization.php
================================================
icon('heroicon-m-trash');
$this->action(function (): void {
$result = $this->process(function (Organization $record): bool {
try {
$deletionService = app(DeletionService::class);
$deletionService->deleteOrganization($record);
return true;
} catch (ApiException $exception) {
$this->failureNotificationTitle($exception->getTranslatedMessage());
report($exception);
} catch (Throwable $exception) {
$this->failureNotificationTitle(__('exceptions.unknown_error_in_admin_panel'));
report($exception);
}
return false;
});
if (! $result) {
$this->failure();
return;
}
$this->success();
});
}
}
================================================
FILE: app/Filament/Resources/OrganizationResource/Pages/CreateOrganization.php
================================================
record;
$user = $organization->owner;
$organization->users()->attach(
$user, [
'role' => Role::Owner->value,
]
);
}
}
================================================
FILE: app/Filament/Resources/OrganizationResource/Pages/EditOrganization.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/OrganizationResource/Pages/ViewOrganization.php
================================================
icon('heroicon-s-pencil'),
];
}
}
================================================
FILE: app/Filament/Resources/OrganizationResource/RelationManagers/InvitationsRelationManager.php
================================================
schema([
TextInput::make('email')
->label('Email')
->disabledOn(['edit'])
->required(),
Select::make('role')
->options(Role::class)
->label('Role')
->rules([
'required',
'string',
Rule::enum(Role::class)
->except([Role::Owner, Role::Placeholder]),
])
->required(),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('email')
->modelLabel('Invitation')
->pluralModelLabel('Invitations')
->columns([
Tables\Columns\TextColumn::make('email'),
Tables\Columns\TextColumn::make('role'),
])
->headerActions([
Tables\Actions\CreateAction::make()
->icon('heroicon-s-plus')
->using(function (array $data, string $model): Model {
/** @var Organization $ownerRecord */
$ownerRecord = $this->getOwnerRecord();
return app(InvitationService::class)
->inviteUser($ownerRecord, $data['email'], Role::from($data['role']));
}),
])
->actions([
Action::make('view')
->icon('heroicon-o-eye')
->color('gray')
->url(fn (OrganizationInvitation $record): string => OrganizationInvitationResource::getUrl('view', [
'record' => $record->getKey(),
])),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DetachBulkAction::make(),
]),
]);
}
}
================================================
FILE: app/Filament/Resources/OrganizationResource/RelationManagers/UsersRelationManager.php
================================================
schema([
Select::make('role')
->options(Role::class),
TextInput::make('billable_rate')
->label('Billable rate (in Cents)')
->nullable()
->numeric(),
]);
}
public function table(Table $table): Table
{
/** @var Organization $organization */
$organization = $this->getOwnerRecord();
return $table
->recordTitleAttribute('name')
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('role'),
TextColumn::make('billable_rate')
->money($organization->currency, divideBy: 100),
])
->headerActions([
Tables\Actions\AttachAction::make()
->recordTitle(fn (User $record): string => "{$record->name} ({$record->email})")
->form(fn (AttachAction $action): array => [
$action->getRecordSelect(),
Select::make('role')
->required()
->options(Role::class)
->rule([
'required',
'string',
Rule::enum(Role::class)
->except([Role::Owner, Role::Placeholder]),
]),
])
->label('Add user')
->modalHeading('Add user')
->icon('heroicon-s-plus')
->using(function (User $record, array $data): void {
/** @var Organization $organization */
$organization = $this->getOwnerRecord();
app(MemberService::class)->addMember($record, $organization, Role::from($data['role']), true);
}),
])
->actions([
Action::make('view')
->icon('heroicon-o-eye')
->color('gray')
->url(fn (User $record): string => UserResource::getUrl('view', [
'record' => $record->getKey(),
])),
Tables\Actions\EditAction::make()
->using(function (User $record, array $data): User {
/** @var Organization $organization */
$organization = $this->getOwnerRecord();
/** @var Member $member */
$member = $record->getRelation('membership');
if ($data['billable_rate'] !== $member->billable_rate) {
$member->billable_rate = $data['billable_rate'];
app(BillableRateService::class)->updateTimeEntriesBillableRateForMember($member);
}
if ($data['role'] !== $member->role) {
try {
app(MemberService::class)->changeRole($member, $organization, Role::from($data['role']), true);
} catch (ApiException $exception) {
Notification::make()
->danger()
->title('Update failed')
->body($exception->getTranslatedMessage())
->persistent()
->send();
}
}
$member->save();
return $record;
}),
Tables\Actions\DetachAction::make()
->using(function (User $record): void {
/** @var Organization $organization */
$organization = $this->getOwnerRecord();
$member = Member::query()
->whereBelongsTo($record, 'user')
->whereBelongsTo($organization, 'organization')
->firstOrFail();
try {
app(MemberService::class)->removeMember($member, $organization);
} catch (ApiException $exception) {
Notification::make()
->danger()
->title('Delete failed')
->body($exception->getTranslatedMessage())
->persistent()
->send();
}
}),
])
->bulkActions([
]);
}
}
================================================
FILE: app/Filament/Resources/OrganizationResource.php
================================================
columns(1)
->schema([
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
Forms\Components\Toggle::make('personal_team')
->label('Is personal?')
->hiddenOn(['create'])
->required(),
Forms\Components\Select::make('user_id')
->label('Owner')
->relationship(name: 'owner', titleAttribute: 'email')
->searchable(['name', 'email'])
->disabledOn(['edit'])
->required(),
Select::make('date_format')
->options(DateFormat::toSelectArray())
->required(),
Select::make('currency_format')
->options(CurrencyFormat::toSelectArray())
->required(),
Select::make('interval_format')
->options(IntervalFormat::toSelectArray())
->required(),
Select::make('number_format')
->options(NumberFormat::toSelectArray())
->required(),
Select::make('time_format')
->options(TimeFormat::toSelectArray())
->required(),
Forms\Components\Select::make('currency')
->label('Currency')
->options(function (): array {
$currencies = ISOCurrencyProvider::getInstance()->getAvailableCurrencies();
$select = [];
foreach ($currencies as $currency) {
$select[$currency->getCurrencyCode()] = $currency->getName().' ('.$currency->getCurrencyCode().')';
}
return $select;
})
->required()
->searchable(),
Forms\Components\TextInput::make('billable_rate')
->label('Billable rate (in Cents)')
->nullable()
->rules([
'nullable',
'integer',
'gt:0',
'max:2147483647',
])
->numeric(),
Forms\Components\DateTimePicker::make('created_at')
->label('Created At')
->hiddenOn(['create'])
->disabled(),
Forms\Components\DateTimePicker::make('updated_at')
->label('Updated At')
->hiddenOn(['create'])
->disabled(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\IconColumn::make('personal_team')
->boolean()
->label('Is personal?')
->sortable(),
Tables\Columns\TextColumn::make('owner.email')
->sortable(),
Tables\Columns\TextColumn::make('currency'),
TextColumn::make('billable_rate')
->money(fn (Organization $resource) => $resource->currency, divideBy: 100),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('created_at', 'desc')
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make()
->using(function (Organization $record): void {
app(DeletionService::class)->deleteOrganization($record);
}),
Action::make('Export')
->icon('heroicon-o-arrow-down-tray')
->action(function (Organization $record) {
try {
$file = app(ExportService::class)->export($record);
Notification::make()
->title('Export successful')
->success()
->persistent()
->send();
return response()->streamDownload(function () use ($file): void {
echo Storage::disk(config('filesystems.private'))->get($file);
}, 'export.zip');
} catch (\Exception $exception) {
report($exception);
Notification::make()
->title('Export failed')
->danger()
->body('Message: '.$exception->getMessage())
->persistent()
->send();
}
}),
Action::make('Import')
->icon('heroicon-o-inbox-arrow-down')
->action(function (Organization $record, array $data): void {
try {
$file = Storage::disk(config('filament.default_filesystem_disk'))->get($data['file']);
if ($file === null) {
throw new \Exception('File not found');
}
/** @var string $timezone */
$timezone = $data['timezone'];
/** @var ReportDto $report */
$report = app(ImportService::class)->import(
$record,
$data['type'],
$file,
$timezone
);
Notification::make()
->title('Import successful')
->success()
->body(
'Imported time entries: '.$report->timeEntriesCreated.'
'.
'Imported clients: '.$report->clientsCreated.'
'.
'Imported projects: '.$report->projectsCreated.'
'.
'Imported tasks: '.$report->tasksCreated.'
'.
'Imported tags: '.$report->tagsCreated.'
'.
'Imported users: '.$report->usersCreated
)
->persistent()
->send();
} catch (ImportException $exception) {
report($exception);
Notification::make()
->title('Import failed, changes rolled back')
->danger()
->body('Message: '.$exception->getMessage())
->persistent()
->send();
}
})
->tooltip(fn (Organization $record): string => 'Import into '.$record->name)
->form([
Forms\Components\FileUpload::make('file')
->label('File')
->required(),
Select::make('type')
->required()
->options(function (): array {
$select = [];
foreach (app(ImporterProvider::class)->getImporterKeys() as $key) {
$select[$key] = $key;
}
return $select;
}),
Forms\Components\Select::make('timezone')
->label('Timezone')
->options(fn (): array => app(TimezoneService::class)->getSelectOptions())
->searchable()
->required(),
]),
])
->bulkActions([
]);
}
public static function getRelations(): array
{
return [
UsersRelationManager::class,
InvitationsRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListOrganizations::route('/'),
'create' => Pages\CreateOrganization::route('/create'),
'edit' => Pages\EditOrganization::route('/{record}/edit'),
'view' => Pages\ViewOrganization::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Resources/ProjectMemberResource/Pages/CreateProjectMember.php
================================================
icon('heroicon-m-trash'),
];
}
}
================================================
FILE: app/Filament/Resources/ProjectMemberResource/Pages/ListProjectMembers.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/ProjectMemberResource/Pages/ViewProjectMembers.php
================================================
icon('heroicon-s-pencil'),
];
}
}
================================================
FILE: app/Filament/Resources/ProjectMemberResource.php
================================================
schema([
Forms\Components\TextInput::make('billable_rate')
->label('Billable rate (in Cents)')
->nullable()
->rules([
'nullable',
'integer',
'gt:0',
'max:2147483647',
])
->numeric(),
Forms\Components\Select::make('user_id')
->relationship('user', 'name')
->required(),
Forms\Components\Select::make('member_id')
->relationship('member', 'id')
->required(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('id')
->label('ID'),
Tables\Columns\TextColumn::make('billable_rate')
->numeric()
->sortable(),
Tables\Columns\TextColumn::make('project.name'),
Tables\Columns\TextColumn::make('user.name'),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
//
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListProjectMembers::route('/'),
'create' => Pages\CreateProjectMember::route('/create'),
'edit' => Pages\EditProjectMember::route('/{record}/edit'),
'view' => Pages\ViewProjectMembers::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Resources/ProjectResource/Pages/CreateProject.php
================================================
icon('heroicon-m-trash'),
];
}
}
================================================
FILE: app/Filament/Resources/ProjectResource/Pages/ListProjects.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/ProjectResource/RelationManagers/ProjectMembersRelationManager.php
================================================
schema([
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('name')
->columns([
Tables\Columns\TextColumn::make('user.name'),
Tables\Columns\TextColumn::make('billable_rate')
->numeric()
->sortable(),
])
->filters([
//
])
->headerActions([
])
->actions([
Action::make('view')
->icon('heroicon-o-eye')
->color('gray')
->url(fn (ProjectMember $record): string => ProjectMemberResource::getUrl('view', [
'record' => $record->getKey(),
])),
Action::make('edit')
->icon('heroicon-o-pencil')
->url(fn (ProjectMember $record): string => ProjectMemberResource::getUrl('edit', [
'record' => $record->getKey(),
]))
->openUrlInNewTab(),
])
->bulkActions([
]);
}
}
================================================
FILE: app/Filament/Resources/ProjectResource.php
================================================
schema([
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
ColorPicker::make('color')
->label('Color')
->required(),
Forms\Components\TextInput::make('billable_rate')
->label('Billable rate (in Cents)')
->nullable()
->rules([
'nullable',
'integer',
'gt:0',
'max:2147483647',
])
->numeric(),
Forms\Components\Select::make('organization_id')
->relationship(name: 'organization', titleAttribute: 'name')
->searchable(['name'])
->required(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
ColorColumn::make('color'),
TextColumn::make('name')
->searchable()
->sortable(),
TextColumn::make('organization.name')
->sortable(),
TextColumn::make('created_at')
->sortable(),
TextColumn::make('updated_at')
->sortable(),
])
->filters([
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->defaultSort('created_at', 'desc')
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
ProjectMembersRelationManager::make(),
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListProjects::route('/'),
'create' => Pages\CreateProject::route('/create'),
'edit' => Pages\EditProject::route('/{record}/edit'),
];
}
}
================================================
FILE: app/Filament/Resources/ReportResource/Pages/EditReport.php
================================================
icon('heroicon-m-trash'),
];
}
}
================================================
FILE: app/Filament/Resources/ReportResource/Pages/ListReports.php
================================================
icon('heroicon-s-pencil'),
];
}
}
================================================
FILE: app/Filament/Resources/ReportResource.php
================================================
columns(1)
->schema([
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
Forms\Components\TextInput::make('description')
->label('Description')
->nullable()
->maxLength(255),
Toggle::make('is_public')
->label('Is public?')
->required(),
DateTimePicker::make('public_until')
->label('Public until')
->nullable(),
Forms\Components\Select::make('organization_id')
->label('Organization')
->relationship(name: 'organization', titleAttribute: 'name')
->searchable(['name'])
->disabled()
->required(),
Forms\Components\TextInput::make('share_secret')
->label('Share Secret')
->nullable(),
PrettyJsonField::make('properties')
->formatStateUsing(function (ReportPropertiesDto $state, Report $record): string {
return $record->getRawOriginal('properties');
})
->disabled(),
Forms\Components\DateTimePicker::make('created_at')
->label('Created At')
->hiddenOn(['create'])
->disabled(),
Forms\Components\DateTimePicker::make('updated_at')
->label('Updated At')
->hiddenOn(['create'])
->disabled(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('description')
->searchable()
->sortable(),
ToggleColumn::make('is_public')
->label('Is public?')
->sortable(),
TextColumn::make('organization.name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('created_at', 'desc')
->filters([
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->actions([
Action::make('public-view')
->label('Public')
->icon('heroicon-o-eye')
->color('gray')
->hidden(fn (Report $record): bool => $record->getShareableLink() === null)
->url(fn (Report $record): string => $record->getShareableLink(), true),
Tables\Actions\ViewAction::make(),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make(),
])
->bulkActions([
]);
}
public static function getRelations(): array
{
return [
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListReports::route('/'),
'edit' => Pages\EditReport::route('/{record}/edit'),
'view' => Pages\ViewReport::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Resources/TagResource/Pages/CreateTag.php
================================================
icon('heroicon-m-trash'),
];
}
}
================================================
FILE: app/Filament/Resources/TagResource/Pages/ListTags.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/TagResource.php
================================================
schema([
TextInput::make('name')
->label('Name')
->required(),
Forms\Components\Select::make('organization_id')
->relationship(name: 'organization', titleAttribute: 'name')
->label('Organization')
->searchable(['name'])
->required(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->label('Name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('organization.name')
->sortable()
->label('Organization'),
Tables\Columns\TextColumn::make('created_at')
->label('Created at')
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->label('Updated at')
->sortable(),
])
->defaultSort('created_at', 'desc')
->filters([
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListTags::route('/'),
'create' => Pages\CreateTag::route('/create'),
'edit' => Pages\EditTag::route('/{record}/edit'),
];
}
}
================================================
FILE: app/Filament/Resources/TaskResource/Pages/CreateTask.php
================================================
icon('heroicon-m-trash'),
];
}
}
================================================
FILE: app/Filament/Resources/TaskResource/Pages/ListTasks.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/TaskResource.php
================================================
schema([
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
Select::make('project_id')
->relationship(name: 'project', titleAttribute: 'name')
->searchable(['name'])
->required(),
Select::make('organization_id')
->relationship(name: 'organization', titleAttribute: 'name')
->searchable(['name'])
->required(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('project.name')
->sortable(),
Tables\Columns\TextColumn::make('organization.name')
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->sortable(),
])
->filters([
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->defaultSort('created_at', 'desc')
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListTasks::route('/'),
'create' => Pages\CreateTask::route('/create'),
'edit' => Pages\EditTask::route('/{record}/edit'),
];
}
}
================================================
FILE: app/Filament/Resources/TimeEntryResource/Pages/CreateTimeEntry.php
================================================
$data
* @return array
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
if (isset($data['member_id'])) {
/** @var Member|null $member */
$member = Member::query()->find($data['member_id']);
if ($member !== null) {
$data['user_id'] = $member->user_id;
$data['organization_id'] = $member->organization_id;
}
}
return $data;
}
}
================================================
FILE: app/Filament/Resources/TimeEntryResource/Pages/EditTimeEntry.php
================================================
icon('heroicon-m-trash'),
];
}
/**
* @param array $data
* @return array
*/
protected function mutateFormDataBeforeSave(array $data): array
{
if (isset($data['member_id'])) {
/** @var Member|null $member */
$member = Member::query()->find($data['member_id']);
if ($member !== null) {
$data['user_id'] = $member->user_id;
$data['organization_id'] = $member->organization_id;
}
}
return $data;
}
}
================================================
FILE: app/Filament/Resources/TimeEntryResource/Pages/ListTimeEntries.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/TimeEntryResource.php
================================================
schema([
TextInput::make('id')
->label('ID')
->readOnly()
->disabled(),
TextInput::make('description')
->label('Description')
->required()
->maxLength(255),
Toggle::make('billable')
->label('Is Billable?')
->required(),
DateTimePicker::make('start')
->label('Start')
->required(),
DateTimePicker::make('end')
->label('End')
->nullable()
->rules([
'after_or_equal:start',
]),
Select::make('member_id')
->relationship(
name: 'member',
titleAttribute: 'id',
modifyQueryUsing: fn (Builder $query) => $query->with(['user', 'organization'])
)
->getOptionLabelFromRecordUsing(fn (Member $record): string => $record->user->email.' ('.$record->organization->name.')')
->searchable()
->required(),
Select::make('project_id')
->relationship(name: 'project', titleAttribute: 'name')
->searchable(['name'])
->nullable(),
Select::make('task_id')
->relationship(name: 'task', titleAttribute: 'name')
->searchable(['name'])
->nullable(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('description')
->searchable()
->label('Description'),
TextColumn::make('user.email')
->label('User'),
TextColumn::make('project.name')
->label('Project'),
TextColumn::make('task.name')
->label('Task'),
TextColumn::make('time')
->getStateUsing(function (TimeEntry $record): string {
return ($record->getDuration()?->cascade()?->forHumans() ?? '-').' '.
' ('.$record->start->toDateTimeString('minute').' - '.
($record->end?->toDateTimeString('minute') ?? '...').')';
})
->label('Time'),
Tables\Columns\TextColumn::make('organization.name')
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->sortable(),
])
->filters([
SelectFilter::make('organization')
->label('Organization')
->relationship('organization', 'name')
->searchable(),
SelectFilter::make('organization_id')
->label('Organization ID')
->relationship('organization', 'id')
->searchable(),
])
->defaultSort('created_at', 'desc')
->actions([
Tables\Actions\EditAction::make(),
])
->bulkActions([
Tables\Actions\BulkActionGroup::make([
Tables\Actions\DeleteBulkAction::make(),
]),
]);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListTimeEntries::route('/'),
'create' => Pages\CreateTimeEntry::route('/create'),
'edit' => Pages\EditTimeEntry::route('/{record}/edit'),
];
}
}
================================================
FILE: app/Filament/Resources/TokenResource/Pages/ListTokens.php
================================================
columns(1)
->schema([
Forms\Components\TextInput::make('id')
->label('ID')
->disabled()
->visibleOn(['update', 'show'])
->readOnly()
->maxLength(255),
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
Forms\Components\Select::make('owner_id')
->label('User')
->relationship(name: 'user', titleAttribute: 'name')
->searchable(['name'])
->disabled()
->required(),
Forms\Components\Select::make('client_id')
->label('Client')
->relationship(name: 'client', titleAttribute: 'name')
->searchable(['name'])
->required(),
Forms\Components\Toggle::make('revoked')
->label('Revoked')
->required(),
Forms\Components\DateTimePicker::make('expires_at')
->label('Expires At')
->disabled(),
Forms\Components\DateTimePicker::make('created_at')
->label('Created At')
->disabled(),
Forms\Components\DateTimePicker::make('updated_at')
->label('Updated At')
->disabled(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('user.name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('client.name')
->searchable()
->sortable(),
Tables\Columns\IconColumn::make('personal_access_client')
->state(function (Token $token): bool {
return in_array('personal_access', $token->client->grant_types ?? [], true);
})
->boolean()
->label('API token?'),
Tables\Columns\IconColumn::make('revoked')
->boolean()
->label('Revoked?')
->sortable(),
Tables\Columns\TextColumn::make('expires_at')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('created_at', 'desc')
->filters([
TernaryFilter::make('is_personal_access_client')
->queries(
true: function (Builder $query) {
/** @var Builder $query */
return $query->isApiToken();
},
false: function (Builder $query) {
/** @var Builder $query */
return $query->isApiToken(false);
},
blank: function (Builder $query) {
/** @var Builder $query */
return $query;
},
)
->label('API token?'),
TernaryFilter::make('revoked')
->label('Revoked?'),
])
->actions([
Tables\Actions\ViewAction::make(),
])
->bulkActions([
]);
}
public static function getRelations(): array
{
return [
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListTokens::route('/'),
'view' => Pages\ViewToken::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Resources/UserResource/Actions/DeleteUser.php
================================================
icon('heroicon-m-trash');
$this->action(function (): void {
$result = $this->process(function (User $record): bool {
try {
$deletionService = app(DeletionService::class);
$deletionService->deleteUser($record);
return true;
} catch (ApiException $exception) {
$this->failureNotificationTitle($exception->getTranslatedMessage());
report($exception);
} catch (Throwable $exception) {
$this->failureNotificationTitle(__('exceptions.unknown_error_in_admin_panel'));
report($exception);
}
return false;
});
if (! $result) {
$this->failure();
return;
}
$this->success();
});
}
}
================================================
FILE: app/Filament/Resources/UserResource/Pages/CreateUser.php
================================================
createUser(
$data['name'],
$data['email'],
$data['password_create'],
$data['timezone'],
Weekday::from($data['week_start']),
$data['currency'],
verifyEmail: (bool) $data['is_email_verified']
);
return $user;
}
}
================================================
FILE: app/Filament/Resources/UserResource/Pages/EditUser.php
================================================
record($this->getRecord()),
UserResource\Actions\DeleteUser::make(),
];
}
}
================================================
FILE: app/Filament/Resources/UserResource/Pages/ListUsers.php
================================================
icon('heroicon-s-plus'),
];
}
}
================================================
FILE: app/Filament/Resources/UserResource/Pages/ViewUser.php
================================================
record($this->getRecord()),
EditAction::make('edit')
->icon('heroicon-s-pencil'),
];
}
}
================================================
FILE: app/Filament/Resources/UserResource/RelationManagers/OrganizationsRelationManager.php
================================================
schema([
Select::make('role')
->options(Role::class),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('name')
->columns([
TextColumn::make('name'),
TextColumn::make('role'),
TextColumn::make('membership.billable_rate')
->label('Billable rate')
->money(fn (Organization $resource) => $resource->currency, divideBy: 100),
])
->headerActions([
])
->actions([
Action::make('view')
->icon('heroicon-o-eye')
->color('gray')
->url(fn (Organization $record): string => OrganizationResource::getUrl('view', [
'record' => $record->getKey(),
])),
Tables\Actions\EditAction::make()
->using(function (Organization $record, array $data): Organization {
/** @var Member $member */
$member = $record->getRelation('membership');
if ($data['role'] !== $member->role) {
try {
app(MemberService::class)->changeRole($member, $record, Role::from($data['role']), true);
} catch (ApiException $exception) {
Notification::make()
->danger()
->title('Update failed')
->body($exception->getTranslatedMessage())
->persistent()
->send();
}
}
$member->save();
return $record;
}),
Tables\Actions\DetachAction::make()
->using(function (Organization $record): void {
/** @var User $user */
$user = $this->getOwnerRecord();
$member = Member::query()
->whereBelongsTo($user, 'user')
->whereBelongsTo($record, 'organization')
->firstOrFail();
try {
app(MemberService::class)->removeMember($member, $record);
} catch (ApiException $exception) {
Notification::make()
->danger()
->title('Delete failed')
->body($exception->getTranslatedMessage())
->persistent()
->send();
}
}),
])
->bulkActions([
]);
}
}
================================================
FILE: app/Filament/Resources/UserResource/RelationManagers/OwnedOrganizationsRelationManager.php
================================================
schema([
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('name')
->columns([
Tables\Columns\TextColumn::make('name'),
])
->filters([
//
])
->headerActions([
])
->actions([
Action::make('view')
->icon('heroicon-o-eye')
->color('gray')
->url(fn (Organization $record): string => OrganizationResource::getUrl('view', [
'record' => $record->getKey(),
])),
Action::make('edit')
->icon('heroicon-o-pencil')
->url(fn (Organization $record): string => OrganizationResource::getUrl('edit', [
'record' => $record->getKey(),
]))
->openUrlInNewTab(),
])
->bulkActions([
]);
}
}
================================================
FILE: app/Filament/Resources/UserResource.php
================================================
getRecord();
return $form
->columns(1)
->schema([
Forms\Components\TextInput::make('id')
->label('ID')
->disabled()
->visibleOn(['update', 'show'])
->readOnly()
->maxLength(255),
Forms\Components\TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
Forms\Components\TextInput::make('email')
->label('Email')
->required()
->rules($record?->is_placeholder ? [] : [
UniqueEloquent::make(User::class, 'email')
->ignore($record?->getKey()),
])
->rule([
'email',
])
->maxLength(255),
Forms\Components\Toggle::make('is_placeholder')
->label('Is Placeholder?')
->hiddenOn(['create'])
->disabledOn(['edit']),
Forms\Components\DateTimePicker::make('email_verified_at')
->label('Email Verified At')
->hiddenOn(['create'])
->nullable(),
Forms\Components\Toggle::make('is_email_verified')
->label('Email Verified?')
->visibleOn(['create']),
Forms\Components\Select::make('timezone')
->label('Timezone')
->options(fn (): array => app(TimezoneService::class)->getSelectOptions())
->searchable()
->required(),
Forms\Components\Select::make('week_start')
->label('Week Start')
->options(Weekday::class)
->required(),
TextInput::make('password')
->password()
->label('Password')
->dehydrateStateUsing(fn ($state) => Hash::make($state))
->dehydrated(fn ($state) => filled($state))
->hiddenOn(['create'])
->required(fn (string $context): bool => $context === 'create')
->maxLength(255),
TextInput::make('password_create')
->password()
->label('Password')
->visibleOn(['create'])
->required(fn (string $context): bool => $context === 'create')
->maxLength(255),
Forms\Components\Select::make('currency')
->label('Currency (Personal Organization)')
->options(function (): array {
$currencies = ISOCurrencyProvider::getInstance()->getAvailableCurrencies();
$select = [];
foreach ($currencies as $currency) {
$select[$currency->getCurrencyCode()] = $currency->getName().' ('.$currency->getCurrencyCode().')';
}
return $select;
})
->required()
->visibleOn(['create'])
->searchable(),
Forms\Components\DateTimePicker::make('created_at')
->label('Created At')
->hiddenOn(['create'])
->disabled(),
Forms\Components\DateTimePicker::make('updated_at')
->label('Updated At')
->hiddenOn(['create'])
->disabled(),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->searchable()
->sortable(),
Tables\Columns\TextColumn::make('email')
->icon('heroicon-m-envelope')
->searchable()
->sortable(),
Tables\Columns\IconColumn::make('is_real_user')
->getStateUsing(fn (User $record): bool => ! $record->is_placeholder)
->label('Real user?')
->boolean(),
Tables\Columns\IconColumn::make('email_verified')
->getStateUsing(fn (User $record): bool => $record->email_verified_at !== null)
->label('Email verified?')
->boolean(),
Tables\Columns\TextColumn::make('created_at')
->dateTime()
->sortable(),
Tables\Columns\TextColumn::make('updated_at')
->dateTime()
->sortable()
->toggleable(isToggledHiddenByDefault: true),
])
->defaultSort('created_at', 'desc')
->filters([
TernaryFilter::make('real_user')
->queries(
true: function (Builder $query): Builder {
/** @var Builder $query */
return $query->where('is_placeholder', '=', false);
},
false: function (Builder $query): Builder {
/** @var Builder $query */
return $query->where('is_placeholder', '=', true);
},
blank: function (Builder $query): Builder {
/** @var Builder $query */
return $query;
},
)
->label('Real User?'),
TernaryFilter::make('email_verified')
->label('Email Verified?')
->attribute('email_verified_at')
->nullable(),
])
->actions([
Impersonate::make()->before(function (User $record): void {
if ($record->currentTeam === null) {
$organization = $record->organizations()->where('personal_team', '=', true)->first();
if ($organization === null) {
$organization = $record->organizations()->first();
}
if ($organization === null) {
throw new Exception('User has no organization');
}
$record->currentTeam()->associate($organization);
$record->save();
}
}),
Tables\Actions\EditAction::make(),
Tables\Actions\DeleteAction::make()
->hidden(fn (User $record) => $record->is(Auth::user()))
->using(function (User $record): void {
try {
app(DeletionService::class)->deleteUser($record);
} catch (ApiException $exception) {
Notification::make()
->danger()
->title('Delete failed')
->body($exception->getTranslatedMessage())
->persistent()
->send();
}
}),
])
->bulkActions([
Tables\Actions\BulkAction::make('Resend verification email')
->icon('heroicon-o-paper-airplane')
->action(function (Collection $records): void {
foreach ($records as $user) {
/** @var User $user */
$user->sendEmailVerificationNotification();
}
}),
]);
}
public static function getRelations(): array
{
return [
OrganizationsRelationManager::class,
OwnedOrganizationsRelationManager::class,
];
}
public static function getPages(): array
{
return [
'index' => Pages\ListUsers::route('/'),
'create' => Pages\CreateUser::route('/create'),
'edit' => Pages\EditUser::route('/{record}/edit'),
'view' => Pages\ViewUser::route('/{record}'),
];
}
}
================================================
FILE: app/Filament/Widgets/ActiveUserOverview.php
================================================
where('is_placeholder', '=', false)->count();
$placeholderUserCount = User::query()->where('is_placeholder', '=', true)->count();
$activeInLastWeek = User::query()
->where('is_placeholder', '=', false)
->whereHas('timeEntries', function (Builder $query): void {
/** @var Builder $query */
$query->where('created_at', '>=', now()->subWeek())
->orWhere('updated_at', '>=', now()->subWeek());
})
->count();
return [
Stat::make('Total', $usersCount)
->color('primary')
->description('Total real users'),
Stat::make('Placeholder', $placeholderUserCount)
->color('danger')
->description('Placeholder users'),
Stat::make('Active', $activeInLastWeek)
->color('success')
->description('Active users in the last seven days'),
];
}
}
================================================
FILE: app/Filament/Widgets/ServerOverview.php
================================================
*/
protected function getViewData(): array
{
/** @var string|null $currentVersion */
$currentVersion = config('app.version');
/** @var string|null $build */
$build = config('app.build');
$latestVersion = Cache::get('latest_version', null);
$needsUpdate = false;
if ($latestVersion !== null && $currentVersion !== null && version_compare($latestVersion, $currentVersion) > 0) {
$needsUpdate = true;
}
return [
'version' => $currentVersion,
'build' => $build,
'environment' => config('app.env'),
'currentVersion' => $latestVersion,
'needsUpdate' => $needsUpdate,
];
}
}
================================================
FILE: app/Filament/Widgets/TimeEntriesCreated.php
================================================
filter;
if ($filter === 'week') {
$start = now()->subWeek();
} elseif ($filter === 'month') {
$start = now()->subMonth();
} elseif ($filter === 'year') {
$start = now()->subYear();
} else {
$start = now()->subWeek();
}
$trend = Trend::query(
TimeEntry::query()->where('is_imported', '=', false)
)
->between(
start: $start,
end: now(),
)
->perDay();
if ($filter === 'week') {
$trend->perDay();
} elseif ($filter === 'month') {
$trend->perDay();
} elseif ($filter === 'year') {
$trend->perMonth();
} else {
$trend->perDay();
}
$data = $trend->count();
return [
'datasets' => [
[
'label' => self::$heading,
'data' => $data->map(fn (TrendValue $value) => $value->aggregate),
],
],
'labels' => $data->map(fn (TrendValue $value) => $value->date),
];
}
protected function getFilters(): ?array
{
return [
'week' => 'Last week',
'month' => 'Last month',
'year' => 'Last year',
];
}
protected function getType(): string
{
return 'line';
}
}
================================================
FILE: app/Filament/Widgets/TimeEntriesImported.php
================================================
filter;
if ($filter === 'week') {
$start = now()->subWeek();
} elseif ($filter === 'month') {
$start = now()->subMonth();
} elseif ($filter === 'year') {
$start = now()->subYear();
} else {
$start = now()->subWeek();
}
$trend = Trend::query(
TimeEntry::query()->where('is_imported', '=', true)
)
->between(
start: $start,
end: now(),
)
->perDay();
if ($filter === 'week') {
$trend->perDay();
} elseif ($filter === 'month') {
$trend->perDay();
} elseif ($filter === 'year') {
$trend->perMonth();
} else {
$trend->perDay();
}
$data = $trend->count();
return [
'datasets' => [
[
'label' => self::$heading,
'data' => $data->map(fn (TrendValue $value) => $value->aggregate),
],
],
'labels' => $data->map(fn (TrendValue $value) => $value->date),
];
}
protected function getFilters(): ?array
{
return [
'week' => 'Last week',
'month' => 'Last month',
'year' => 'Last year',
];
}
protected function getType(): string
{
return 'line';
}
}
================================================
FILE: app/Filament/Widgets/UserRegistrations.php
================================================
filter;
if ($filter === 'week') {
$start = now()->subWeek();
} elseif ($filter === 'month') {
$start = now()->subMonth();
} elseif ($filter === 'year') {
$start = now()->subYear();
} else {
$start = now()->subWeek();
}
$trend = Trend::query(
User::query()
->where('is_placeholder', '=', false)
)
->between(
start: $start,
end: now(),
)
->perDay();
if ($filter === 'week') {
$trend->perDay();
} elseif ($filter === 'month') {
$trend->perDay();
} elseif ($filter === 'year') {
$trend->perMonth();
} else {
$trend->perDay();
}
$data = $trend->count();
return [
'datasets' => [
[
'label' => self::$heading,
'data' => $data->map(fn (TrendValue $value) => $value->aggregate),
],
],
'labels' => $data->map(fn (TrendValue $value) => $value->date),
];
}
protected function getFilters(): ?array
{
return [
'week' => 'Last week',
'month' => 'Last month',
'year' => 'Last year',
];
}
protected function getType(): string
{
return 'line';
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ApiTokenController.php
================================================
user();
$tokens = $user->tokens()
->whereHas('client', function (Builder $query): void {
/** @var Builder $query */
$query->whereJsonContains('grant_types', 'personal_access');
})
->orderBy('created_at', 'desc')
->get();
return new ApiTokenCollection($tokens);
}
/**
* Create a new api token for the currently authenticated user
*
* The response will contain the access token that can be used to send authenticated API requests.
* Please note that the access token is only shown in this response and cannot be retrieved later.
*
* @operationId createApiToken
*
* @throws AuthorizationException|PersonalAccessClientIsNotConfiguredException
*/
public function store(ApiTokenStoreRequest $request): ApiTokenWithAccessTokenResource
{
$user = $this->user();
try {
$token = $user->createToken($request->getName(), ['*']);
/** @var Token $tokenModel */
$tokenModel = $token->getToken();
return new ApiTokenWithAccessTokenResource($tokenModel, $token->accessToken);
} catch (\RuntimeException $exception) {
report($exception);
if (Str::contains($exception->getMessage(), ['Personal access client not found'])) {
throw new PersonalAccessClientIsNotConfiguredException;
}
throw $exception;
}
}
/**
* Revoke an api token
*
* @operationId revokeApiToken
*
* @throws AuthorizationException
* @throws PersonalAccessClientIsNotConfiguredException
*/
public function revoke(Token $apiToken): JsonResponse
{
$user = $this->user();
if ($apiToken->user_id !== $user->getKey()) {
throw new AuthorizationException('API token does not belong to user');
}
if (! ($apiToken->client?->hasGrantType('personal_access') ?? false)) {
throw new AuthorizationException('API token is not a personal access token');
}
$apiToken->revoke();
return response()->json(null, 204);
}
/**
* Delete an api token
*
* @operationId deleteApiToken
*
* @throws AuthorizationException|PersonalAccessClientIsNotConfiguredException
*/
public function destroy(Token $apiToken): JsonResponse
{
$user = $this->user();
if ($apiToken->user_id !== $user->getKey()) {
throw new AuthorizationException('API token does not belong to user');
}
if (! ($apiToken->client?->hasGrantType('personal_access') ?? false)) {
throw new AuthorizationException('API token is not a personal access token');
}
$apiToken->delete();
return response()->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ChartController.php
================================================
*/
public function weeklyProjectOverview(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$weeklyProjectOverview = $dashboardService->weeklyProjectOverview($user, $organization);
return response()->json($weeklyProjectOverview);
}
/**
* Get chart data for the latest tasks.
*
* @throws AuthorizationException
*
* @operationId latestTasks
*
* @response array
*/
public function latestTasks(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$latestTasks = $dashboardService->latestTasks($user, $organization);
return response()->json($latestTasks);
}
/**
* Get chart data for the last seven days.
*
* @throws AuthorizationException
*
* @operationId lastSevenDays
*
* @response array }>
*/
public function lastSevenDays(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$lastSevenDays = $dashboardService->lastSevenDays($user, $organization);
return response()->json($lastSevenDays);
}
/**
* Get chart data for the latest team activity.
*
* @throws AuthorizationException
*
* @operationId latestTeamActivity
*
* @response array
*/
public function latestTeamActivity(Organization $organization, DashboardService $dashboardService, PermissionStore $permissionStore): JsonResponse
{
$this->checkPermission($organization, 'charts:view:all');
$latestTeamActivity = $dashboardService->latestTeamActivity($organization);
return response()->json($latestTeamActivity);
}
/**
* Get chart data for daily tracked hours.
*
* @throws AuthorizationException
*
* @operationId dailyTrackedHours
*
* @response array
*/
public function dailyTrackedHours(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$dailyTrackedHours = $dashboardService->getDailyTrackedHours($user, $organization, 100);
return response()->json($dailyTrackedHours);
}
/**
* Get chart data for total weekly time.
*
* @throws AuthorizationException
*
* @operationId totalWeeklyTime
*
* @response int
*/
public function totalWeeklyTime(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$totalWeeklyTime = $dashboardService->totalWeeklyTime($user, $organization);
return response()->json($totalWeeklyTime);
}
/**
* Get chart data for total weekly billable time.
*
* @throws AuthorizationException
*
* @operationId totalWeeklyBillableTime
*
* @response int
*/
public function totalWeeklyBillableTime(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$totalWeeklyBillableTime = $dashboardService->totalWeeklyBillableTime($user, $organization);
return response()->json($totalWeeklyBillableTime);
}
/**
* Get chart data for total weekly billable amount.
*
* @throws AuthorizationException
*
* @operationId totalWeeklyBillableAmount
*
* @response array{value: int, currency: string}
*/
public function totalWeeklyBillableAmount(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
if (! $showBillableRate) {
throw new AuthorizationException('You do not have permission to view billable rates.');
}
$totalWeeklyBillableAmount = $dashboardService->totalWeeklyBillableAmount($user, $organization);
return response()->json($totalWeeklyBillableAmount);
}
/**
* Get chart data for weekly history.
*
* @throws AuthorizationException
*
* @operationId weeklyHistory
*
* @response array
*/
public function weeklyHistory(Organization $organization, DashboardService $dashboardService): JsonResponse
{
$this->checkPermission($organization, 'charts:view:own');
$user = $this->user();
$weeklyHistory = $dashboardService->getWeeklyHistory($user, $organization);
return response()->json($weeklyHistory);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ClientController.php
================================================
organization_id !== $organization->getKey()) {
throw new AuthorizationException('Tag does not belong to organization');
}
}
/**
* Get clients
*
* @return ClientCollection
*
* @throws AuthorizationException
*
* @operationId getClients
*/
public function index(Organization $organization, ClientIndexRequest $request): ClientCollection
{
$this->checkPermission($organization, 'clients:view');
$canViewAllClients = $this->hasPermission($organization, 'clients:view:all');
$user = $this->user();
$clientsQuery = Client::query()
->whereBelongsTo($organization, 'organization')
->orderBy('created_at', 'desc');
if (! $canViewAllClients) {
$clientsQuery->visibleByEmployee($user);
}
$filterArchived = $request->getFilterArchived();
if ($filterArchived === 'true') {
$clientsQuery->whereNotNull('archived_at');
} elseif ($filterArchived === 'false') {
$clientsQuery->whereNull('archived_at');
}
$clients = $clientsQuery->paginate(config('app.pagination_per_page_default'));
return new ClientCollection($clients);
}
/**
* Create client
*
* @throws AuthorizationException
*
* @operationId createClient
*/
public function store(Organization $organization, ClientStoreRequest $request): ClientResource
{
$this->checkPermission($organization, 'clients:create');
$client = new Client;
$client->name = $request->input('name');
$client->organization()->associate($organization);
$client->save();
return new ClientResource($client);
}
/**
* Update client
*
* @throws AuthorizationException
*
* @operationId updateClient
*/
public function update(Organization $organization, Client $client, ClientUpdateRequest $request): ClientResource
{
$this->checkPermission($organization, 'clients:update', $client);
$client->name = $request->input('name');
if ($request->has('is_archived')) {
$client->archived_at = $request->getIsArchived() ? Carbon::now() : null;
}
$client->save();
return new ClientResource($client);
}
/**
* Delete client
*
* @throws AuthorizationException|EntityStillInUseApiException
*
* @operationId deleteClient
*/
public function destroy(Organization $organization, Client $client): JsonResponse
{
$this->checkPermission($organization, 'clients:delete', $client);
if ($client->projects()->exists()) {
throw new EntityStillInUseApiException('client', 'project');
}
$client->delete();
return response()->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/Controller.php
================================================
permissionStore->has($organization, $permission)) {
throw new AuthorizationException;
}
}
/**
* @param array $permissions
*
* @throws AuthorizationException
*/
protected function checkAnyPermission(Organization $organization, array $permissions): void
{
foreach ($permissions as $permission) {
if ($this->permissionStore->has($organization, $permission)) {
return;
}
}
throw new AuthorizationException;
}
protected function hasPermission(Organization $organization, string $permission): bool
{
return $this->permissionStore->has($organization, $permission);
}
protected function canAccessPremiumFeatures(Organization $organization): bool
{
return app(BillingContract::class)->hasSubscription($organization) || app(BillingContract::class)->hasTrial($organization);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/CurrencyController.php
================================================
[
'code' => $currency->getCurrencyCode(),
'name' => $currency->getName(),
'symbol' => $currencyService->getCurrencySymbol($currency->getCurrencyCode()),
],
ISOCurrencyProvider::getInstance()->getAvailableCurrencies()
));
return response()->json($currencies);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ExportController.php
================================================
checkPermission($organization, 'export');
$filepath = $exportService->export($organization);
$downloadUrl = Storage::disk(config('filesystems.private'))
->temporaryUrl($filepath, Carbon::now()->addMinutes(10));
return new JsonResponse([
'success' => true,
'download_url' => $downloadUrl,
], 200);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ImportController.php
================================================
}
*/
public function index(Organization $organization, ImporterProvider $importerProvider): JsonResponse
{
$this->checkPermission($organization, 'import');
$importers = $importerProvider->getImporters();
/** @var array $importersResponse */
$importersResponse = [];
foreach ($importers as $key => $importerClass) {
/** @var ImporterContract $importer */
$importer = new $importerClass;
$importersResponse[] = [
'key' => $key,
'name' => $importer->getName(),
'description' => $importer->getDescription(),
];
}
return new JsonResponse([
'data' => $importersResponse,
], 200);
}
/**
* Import data into the organization
*
* @throws AuthorizationException
*
* @operationId importData
*/
public function import(Organization $organization, ImportRequest $request, ImportService $importService): JsonResponse
{
$this->checkPermission($organization, 'import');
try {
$importData = base64_decode($request->input('data'), true);
if ($importData === false) {
return new JsonResponse([
'message' => 'Invalid base64 encoded data',
], 400);
}
$timezone = $this->user()->timezone;
$report = $importService->import(
$organization,
$request->input('type'),
$importData,
$timezone
);
return new JsonResponse([
/** @var array{
* clients: array{
* created: int,
* },
* projects: array{
* created: int,
* },
* tasks: array{
* created: int,
* },
* time_entries: array{
* created: int,
* },
* tags: array{
* created: int,
* },
* users: array{
* created: int,
* }
* } $report Import report */
'report' => $report->toArray(),
], 200);
} catch (ImportException $exception) {
report($exception);
return new JsonResponse([
'message' => $exception->getMessage(),
], 400);
}
}
}
================================================
FILE: app/Http/Controllers/Api/V1/InvitationController.php
================================================
organization_id !== $organization->id) {
throw new AuthorizationException('Invitation does not belong to organization');
}
}
/**
* List all invitations of an organization
*
* @return InvitationCollection
*
* @throws AuthorizationException
*
* @operationId getInvitations
*/
public function index(Organization $organization, InvitationIndexRequest $request): InvitationCollection
{
$this->checkPermission($organization, 'invitations:view');
$invitations = $organization->teamInvitations()
->orderBy('created_at', 'desc')
->paginate(config('app.pagination_per_page_default'));
return InvitationCollection::make($invitations);
}
/**
* Invite a user to the organization
*
* @throws AuthorizationException
* @throws UserIsAlreadyMemberOfOrganizationApiException
* @throws InvitationForTheEmailAlreadyExistsApiException
*
* @operationId invite
*/
public function store(Organization $organization, InvitationStoreRequest $request, InvitationService $invitationService): JsonResponse
{
$this->checkPermission($organization, 'invitations:create');
$email = $request->getEmail();
$role = $request->getRole();
$invitationService->inviteUser($organization, $email, $role);
return response()->json(null, 204);
}
/**
* Resend email for a pending invitation
*
* @throws AuthorizationException
*
* @operationId resendInvitationEmail
*/
public function resend(Organization $organization, OrganizationInvitation $invitation, OrganizationInvitationService $organizationInvitationService): JsonResponse
{
$this->checkPermission($organization, 'invitations:resend', $invitation);
$organizationInvitationService->resend($invitation);
return response()->json(null, 204);
}
/**
* Remove a pending invitation
*
* @throws AuthorizationException
*
* @operationId removeInvitation
*/
public function destroy(Organization $organization, OrganizationInvitation $invitation): JsonResponse
{
$this->checkPermission($organization, 'invitations:remove', $invitation);
$invitation->delete();
return response()->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/MemberController.php
================================================
organization_id !== $organization->id) {
throw new AuthorizationException('Member does not belong to organization');
}
}
/**
* List all members of an organization
*
* @return MemberCollection
*
* @throws AuthorizationException
*
* @operationId getMembers
*/
public function index(Organization $organization, MemberIndexRequest $request): MemberCollection
{
$this->checkPermission($organization, 'members:view');
$members = Member::query()
->whereBelongsTo($organization, 'organization')
->with(['user'])
->orderBy('created_at', 'desc')
->paginate(config('app.pagination_per_page_default'));
return MemberCollection::make($members);
}
/**
* Update a member of the organization
*
* @throws AuthorizationException
* @throws OrganizationNeedsAtLeastOneOwner
* @throws OnlyOwnerCanChangeOwnership
* @throws ChangingRoleToPlaceholderIsNotAllowed
* @throws ChangingRoleOfPlaceholderIsNotAllowed
*
* @operationId updateMember
*/
public function update(Organization $organization, Member $member, MemberUpdateRequest $request, BillableRateService $billableRateService, MemberService $memberService): JsonResource
{
$this->checkPermission($organization, 'members:update', $member);
if ($request->has('billable_rate') && $member->billable_rate !== $request->getBillableRate()) {
$member->billable_rate = $request->getBillableRate();
$billableRateService->updateTimeEntriesBillableRateForMember($member);
}
if ($request->has('role') && $member->role !== $request->getRole()->value) {
$newRole = $request->getRole();
$allowOwnerChange = $this->hasPermission($organization, 'members:change-ownership');
$memberService->changeRole($member, $organization, $newRole, $allowOwnerChange);
}
$member->save();
return new MemberResource($member);
}
/**
* Remove a member of the organization.
*
* @throws AuthorizationException|EntityStillInUseApiException|CanNotRemoveOwnerFromOrganization
*
* @operationId removeMember
*/
public function destroy(MemberDestroyRequest $request, Organization $organization, Member $member, MemberService $memberService): JsonResponse
{
$this->checkPermission($organization, 'members:delete', $member);
$deleteRelated = $request->getDeleteRelated();
$memberService->removeMember($member, $organization, $deleteRelated);
return response()
->json(null, 204);
}
/**
* Make a member a placeholder member
*
* @throws AuthorizationException|CanNotRemoveOwnerFromOrganization|ChangingRoleOfPlaceholderIsNotAllowed
*
* @operationId makePlaceholder
*/
public function makePlaceholder(Organization $organization, Member $member, MemberService $memberService): JsonResponse
{
$this->checkPermission($organization, 'members:make-placeholder', $member);
if ($member->role === Role::Owner->value) {
throw new CanNotRemoveOwnerFromOrganization;
}
if ($member->role === Role::Placeholder->value) {
throw new ChangingRoleOfPlaceholderIsNotAllowed;
}
$memberService->makeMemberToPlaceholder($member);
MemberMadeToPlaceholder::dispatch($member, $organization);
return response()->json(null, 204);
}
/**
* Merge one member into another
*
* @throws AuthorizationException
* @throws OnlyPlaceholdersCanBeMergedIntoAnotherMember
* @throws \Throwable
*
* @operationId mergeMember
*/
public function mergeInto(Organization $organization, Member $member, MemberMergeIntoRequest $request, MemberService $memberService): JsonResponse
{
$this->checkPermission($organization, 'members:merge-into', $member);
$user = $member->user;
if ($member->role !== Role::Placeholder->value || ! $user->is_placeholder) {
throw new OnlyPlaceholdersCanBeMergedIntoAnotherMember;
}
$memberTo = Member::findOrFail($request->getMemberId());
DB::transaction(function () use ($organization, $member, $user, $memberTo, $memberService): void {
$memberService->assignOrganizationEntitiesToDifferentMember($organization, $member, $memberTo);
$member->delete();
$user->delete();
});
return response()->json(null, 204);
}
/**
* Invite a placeholder member to become a real member of the organization
*
* @throws AuthorizationException
* @throws UserNotPlaceholderApiException
* @throws UserIsAlreadyMemberOfOrganizationApiException
* @throws ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException
* @throws InvitationForTheEmailAlreadyExistsApiException
*
* @operationId invitePlaceholder
*/
public function invitePlaceholder(Organization $organization, Member $member, InvitationService $invitationService): JsonResponse
{
$this->checkPermission($organization, 'members:invite-placeholder', $member);
$user = $member->user;
if (! $user->is_placeholder) {
throw new UserNotPlaceholderApiException;
}
if (Str::endsWith($user->email, '@solidtime-import.test')) {
throw new ThisPlaceholderCanNotBeInvitedUseTheMergeToolInsteadException;
}
$invitationService->inviteUser($organization, $user->email, Role::Employee);
return response()->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/OrganizationController.php
================================================
checkPermission($organization, 'organizations:view');
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
return new OrganizationResource($organization, $showBillableRate);
}
/**
* Update organization
*
* @operationId updateOrganization
*
* @throws AuthorizationException
*/
public function update(Organization $organization, OrganizationUpdateRequest $request, BillableRateService $billableRateService): OrganizationResource
{
$this->checkPermission($organization, 'organizations:update');
if ($request->getName() !== null) {
$organization->name = $request->getName();
}
if ($request->getEmployeesCanSeeBillableRates() !== null) {
$organization->employees_can_see_billable_rates = $request->getEmployeesCanSeeBillableRates();
}
if ($request->getEmployeesCanManageTasks() !== null) {
$organization->employees_can_manage_tasks = $request->getEmployeesCanManageTasks();
}
if ($request->getNumberFormat() !== null) {
$organization->number_format = $request->getNumberFormat();
}
if ($request->getCurrencyFormat() !== null) {
$organization->currency_format = $request->getCurrencyFormat();
}
if ($request->getDateFormat() !== null) {
$organization->date_format = $request->getDateFormat();
}
if ($request->getIntervalFormat() !== null) {
$organization->interval_format = $request->getIntervalFormat();
}
if ($request->getTimeFormat() !== null) {
$organization->time_format = $request->getTimeFormat();
}
if ($request->getPreventOverlappingTimeEntries() !== null) {
$organization->prevent_overlapping_time_entries = $request->getPreventOverlappingTimeEntries();
}
$hasBillableRate = $request->has('billable_rate');
if ($hasBillableRate) {
$oldBillableRate = $organization->billable_rate;
$organization->billable_rate = $request->getBillableRate();
}
$organization->save();
if ($hasBillableRate && $oldBillableRate !== $request->getBillableRate()) {
$billableRateService->updateTimeEntriesBillableRateForOrganization($organization);
}
return new OrganizationResource($organization, true);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ProjectController.php
================================================
organization_id !== $organization->id) {
throw new AuthorizationException('Project does not belong to organization');
}
}
/**
* Get projects visible to the current user
*
* @return ProjectCollection
*
* @throws AuthorizationException
*
* @operationId getProjects
*/
public function index(Organization $organization, ProjectIndexRequest $request): ProjectCollection
{
$this->checkPermission($organization, 'projects:view');
$canViewAllProjects = $this->hasPermission($organization, 'projects:view:all');
$user = $this->user();
$projectsQuery = Project::query()
->whereBelongsTo($organization, 'organization');
if (! $canViewAllProjects) {
$projectsQuery->visibleByEmployee($user);
}
$filterArchived = $request->getFilterArchived();
if ($filterArchived === 'true') {
$projectsQuery->whereNotNull('archived_at');
} elseif ($filterArchived === 'false') {
$projectsQuery->whereNull('archived_at');
}
$projects = $projectsQuery
->orderBy('created_at', 'desc')
->paginate(config('app.pagination_per_page_default'));
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
return new ProjectCollection($projects, $showBillableRate);
}
/**
* Get project
*
* @throws AuthorizationException
*
* @operationId getProject
*/
public function show(Organization $organization, Project $project): JsonResource
{
$this->checkPermission($organization, 'projects:view:all', $project);
// Note: There is currently no need to check if a user is a member of the project,
// since this is only relevant for users with the role "employee" and they can not access this endpoint.
$project->load('organization');
return new ProjectResource($project, true);
}
/**
* Create project
*
* @throws AuthorizationException
*
* @operationId createProject
*/
public function store(Organization $organization, ProjectStoreRequest $request): JsonResource
{
$this->checkPermission($organization, 'projects:create');
$project = new Project;
$project->name = $request->input('name');
$project->color = $request->input('color');
$project->is_billable = (bool) $request->input('is_billable');
$project->billable_rate = $request->getBillableRate();
$project->client_id = $request->input('client_id');
$project->is_public = $request->getIsPublic();
if ($this->canAccessPremiumFeatures($organization) && $request->has('estimated_time')) {
$project->estimated_time = $request->getEstimatedTime();
}
$project->organization()->associate($organization);
$project->save();
return new ProjectResource($project, true);
}
/**
* Update project
*
* @throws AuthorizationException
*
* @operationId updateProject
*/
public function update(Organization $organization, Project $project, ProjectUpdateRequest $request, BillableRateService $billableRateService): JsonResource
{
$this->checkPermission($organization, 'projects:update', $project);
$project->name = $request->input('name');
$project->color = $request->input('color');
$project->is_billable = (bool) $request->input('is_billable');
if ($request->has('is_archived')) {
$project->archived_at = $request->getIsArchived() ? Carbon::now() : null;
}
if ($request->has('is_public')) {
$project->is_public = $request->boolean('is_public');
}
if ($this->canAccessPremiumFeatures($organization) && $request->has('estimated_time')) {
$project->estimated_time = $request->getEstimatedTime();
}
$oldBillableRate = $project->billable_rate;
$clientIdChanged = false;
$project->billable_rate = $request->getBillableRate();
if ($project->client_id !== $request->input('client_id')) {
$project->client_id = $request->input('client_id');
$clientIdChanged = true;
}
$project->save();
if ($oldBillableRate !== $request->getBillableRate()) {
$billableRateService->updateTimeEntriesBillableRateForProject($project);
}
if ($clientIdChanged) {
TimeEntry::query()
->whereBelongsTo($organization, 'organization')
->whereBelongsTo($project, 'project')
->update(['client_id' => $project->client_id]);
}
return new ProjectResource($project, true);
}
/**
* Delete project
*
* @throws AuthorizationException|EntityStillInUseApiException
*
* @operationId deleteProject
*/
public function destroy(Organization $organization, Project $project): JsonResponse
{
$this->checkPermission($organization, 'projects:delete', $project);
if ($project->tasks()->exists()) {
throw new EntityStillInUseApiException('project', 'task');
}
if ($project->timeEntries()->exists()) {
throw new EntityStillInUseApiException('project', 'time_entry');
}
DB::transaction(function () use (&$project): void {
$project->members->each(function (ProjectMember $member): void {
$member->delete();
});
$project->delete();
});
return response()
->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ProjectMemberController.php
================================================
organization_id !== $organization->id) {
throw new AuthorizationException('Project does not belong to organization');
}
if ($projectMember !== null && $projectMember->project->organization_id !== $organization->id) {
throw new AuthorizationException('Project member does not belong to organization');
}
}
/**
* Get project members for project
*
* @return ProjectMemberCollection
*
* @throws AuthorizationException
*
* @operationId getProjectMembers
*/
public function index(Organization $organization, Project $project, ProjectMemberIndexRequest $request): ProjectMemberCollection
{
$this->checkPermission($organization, 'project-members:view', $project);
$projectMembers = ProjectMember::query()
->whereBelongsTo($project, 'project')
->orderBy('created_at', 'desc')
->paginate(config('app.pagination_per_page_default'));
return new ProjectMemberCollection($projectMembers);
}
/**
* Add project member to project
*
* @throws AuthorizationException|InactiveUserCanNotBeUsedApiException|UserIsAlreadyMemberOfProjectApiException
*
* @operationId createProjectMember
*/
public function store(Organization $organization, Project $project, ProjectMemberStoreRequest $request, BillableRateService $billableRateService): JsonResource
{
$this->checkPermission($organization, 'project-members:create', $project);
$member = Member::findOrFail((string) $request->input('member_id'));
if ($member->user->is_placeholder) {
throw new InactiveUserCanNotBeUsedApiException;
}
if (ProjectMember::whereBelongsTo($project, 'project')->whereBelongsTo($member, 'member')->exists()) {
throw new UserIsAlreadyMemberOfProjectApiException;
}
$projectMember = new ProjectMember;
$projectMember->billable_rate = $request->getBillableRate();
$projectMember->member()->associate($member);
$projectMember->user()->associate($member->user);
$projectMember->project()->associate($project);
$projectMember->save();
if ($request->getBillableRate() !== null) {
$billableRateService->updateTimeEntriesBillableRateForProjectMember($projectMember);
}
return new ProjectMemberResource($projectMember);
}
/**
* Update project member
*
* @throws AuthorizationException
*
* @operationId updateProjectMember
*/
public function update(Organization $organization, ProjectMember $projectMember, ProjectMemberUpdateRequest $request, BillableRateService $billableRateService): JsonResource
{
$this->checkPermission($organization, 'project-members:update', projectMember: $projectMember);
$oldBillableRate = $projectMember->billable_rate;
$projectMember->billable_rate = $request->getBillableRate();
$projectMember->save();
if ($oldBillableRate !== $request->getBillableRate()) {
$billableRateService->updateTimeEntriesBillableRateForProjectMember($projectMember);
}
return new ProjectMemberResource($projectMember);
}
/**
* Delete project member
*
* @throws AuthorizationException
*
* @operationId deleteProjectMember
*/
public function destroy(Organization $organization, ProjectMember $projectMember, BillableRateService $billableRateService): JsonResponse
{
$this->checkPermission($organization, 'project-members:delete', projectMember: $projectMember);
$hadBillableRate = $projectMember->billable_rate !== null;
$project = $projectMember->project;
$member = $projectMember->member;
$projectMember->delete();
if ($hadBillableRate) {
$billableRateService->updateTimeEntriesBillableRateForMember($member);
$billableRateService->updateTimeEntriesBillableRateForProject($project);
$billableRateService->updateTimeEntriesBillableRateForOrganization($organization);
}
return response()
->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/Public/ReportController.php
================================================
header('X-Api-Key');
if (! is_string($shareSecret)) {
throw new ModelNotFoundException;
}
$report = Report::query()
->with([
'organization',
])
->where('share_secret', '=', $shareSecret)
->where('is_public', '=', true)
->where(function (Builder $builder): void {
/** @var Builder $builder */
$builder->whereNull('public_until')
->orWhere('public_until', '>', now());
})
->firstOrFail();
/** @var ReportPropertiesDto $properties */
$properties = $report->properties;
$timeEntriesQuery = TimeEntry::query()
->whereBelongsTo($report->organization, 'organization');
$filter = new TimeEntryFilter($timeEntriesQuery);
$filter->addStart($properties->start);
$filter->addEnd($properties->end);
$filter->addActive($properties->active);
$filter->addBillable($properties->billable);
$filter->addMemberIdsFilter($properties->memberIds?->toArray());
$filter->addProjectIdsFilter($properties->projectIds?->toArray());
$filter->addTagIdsFilter($properties->tagIds?->toArray());
$filter->addTaskIdsFilter($properties->taskIds?->toArray());
$filter->addClientIdsFilter($properties->clientIds?->toArray());
$timeEntriesQuery = $filter->get();
$data = $timeEntryAggregationService->getAggregatedTimeEntriesWithDescriptions(
$timeEntriesQuery->clone(),
$report->properties->group,
$report->properties->subGroup,
$report->properties->timezone,
$report->properties->weekStart,
false,
$report->properties->start,
$report->properties->end,
true,
$report->properties->roundingType,
$report->properties->roundingMinutes,
);
$historyData = $timeEntryAggregationService->getAggregatedTimeEntriesWithDescriptions(
$timeEntriesQuery->clone(),
TimeEntryAggregationType::fromInterval($report->properties->historyGroup),
null,
$report->properties->timezone,
$report->properties->weekStart,
true,
$report->properties->start,
$report->properties->end,
true,
$report->properties->roundingType,
$report->properties->roundingMinutes,
);
return new DetailedWithDataReportResource($report, $data, $historyData);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/ReportController.php
================================================
organization_id !== $organization->id) {
throw new AuthorizationException('Report does not belong to organization');
}
}
/**
* Get reports
*
* @return ReportCollection
*
* @throws AuthorizationException
*
* @operationId getReports
*/
public function index(Organization $organization, ReportIndexRequest $request): ReportCollection
{
$this->checkPermission($organization, 'reports:view');
$reports = Report::query()
->orderBy('created_at', 'desc')
->whereBelongsTo($organization, 'organization')
->paginate(config('app.pagination_per_page_default'));
return new ReportCollection($reports);
}
/**
* Get report
*
* @throws AuthorizationException
*
* @operationId getReport
*/
public function show(Organization $organization, Report $report): DetailedReportResource
{
$this->checkPermission($organization, 'reports:view', $report);
return new DetailedReportResource($report);
}
/**
* Create report
*
* @throws AuthorizationException
*
* @operationId createReport
*/
public function store(Organization $organization, ReportStoreRequest $request, TimezoneService $timezoneService, ReportService $reportService): DetailedReportResource
{
$this->checkPermission($organization, 'reports:create');
$user = $this->user();
$report = new Report;
$report->name = $request->getName();
$report->description = $request->getDescription();
$isPublic = $request->getIsPublic();
$report->is_public = $isPublic;
$properties = new ReportPropertiesDto;
$properties->group = $request->getPropertyGroup();
$properties->subGroup = $request->getPropertySubGroup();
$properties->historyGroup = $request->getPropertyHistoryGroup();
$properties->start = $request->getPropertyStart();
$properties->end = $request->getPropertyEnd();
$properties->active = $request->getPropertyActive();
$properties->setMemberIds($request->input('properties.member_ids', null));
$properties->billable = $request->getPropertyBillable();
$properties->setClientIds($request->input('properties.client_ids', null));
$properties->setProjectIds($request->input('properties.project_ids', null));
$properties->setTagIds($request->input('properties.tag_ids', null));
$properties->setTaskIds($request->input('properties.task_ids', null));
$properties->weekStart = $request->has('properties.week_start') ? Weekday::from($request->input('properties.week_start')) : $user->week_start;
$timezone = $user->timezone;
if ($request->has('properties.timezone')) {
if ($timezoneService->isValid($request->input('properties.timezone'))) {
$timezone = $request->input('properties.timezone');
}
if ($timezoneService->mapLegacyTimezone($request->input('properties.timezone')) !== null) {
$timezone = $timezoneService->mapLegacyTimezone($request->input('properties.timezone'));
}
}
$properties->timezone = $timezone;
$properties->roundingType = $request->getPropertyRoundingType();
$properties->roundingMinutes = $request->getPropertyRoundingMinutes();
$report->properties = $properties;
if ($isPublic) {
$report->share_secret = $reportService->generateSecret();
$report->public_until = $request->getPublicUntil();
} else {
$report->share_secret = null;
$report->public_until = null;
}
$report->organization()->associate($organization);
$report->save();
return new DetailedReportResource($report);
}
/**
* Update report
*
* @throws AuthorizationException
*
* @operationId updateReport
*/
public function update(Organization $organization, Report $report, ReportUpdateRequest $request, ReportService $reportService): DetailedReportResource
{
$this->checkPermission($organization, 'reports:update', $report);
if ($request->has('name')) {
$report->name = $request->getName();
}
if ($request->has('description')) {
$report->description = $request->getDescription();
}
if ($request->has('is_public') && $request->getIsPublic() !== $report->is_public) {
$isPublic = $request->getIsPublic();
$report->is_public = $isPublic;
if ($isPublic) {
$report->share_secret = $reportService->generateSecret();
$report->public_until = $request->getPublicUntil();
} else {
$report->share_secret = null;
$report->public_until = null;
}
} elseif ($report->is_public && $request->has('public_until')) {
// Allow updating expiration date on already-public reports
$report->public_until = $request->getPublicUntil();
}
$report->save();
return new DetailedReportResource($report);
}
/**
* Delete report
*
* @throws AuthorizationException
*
* @operationId deleteReport
*/
public function destroy(Organization $organization, Report $report): JsonResponse
{
$this->checkPermission($organization, 'reports:delete', $report);
$report->delete();
return response()->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/TagController.php
================================================
organization_id !== $organization->getKey()) {
throw new AuthorizationException('Tag does not belong to organization');
}
}
/**
* Get tags
*
* @return TagCollection
*
* @operationId getTags
*
* @throws AuthorizationException
*/
public function index(Organization $organization, TagIndexRequest $request): TagCollection
{
$this->checkPermission($organization, 'tags:view');
$tags = Tag::query()
->whereBelongsTo($organization, 'organization')
->orderBy('created_at', 'desc')
->paginate(config('app.pagination_per_page_default'));
return new TagCollection($tags);
}
/**
* Create tag
*
* @throws AuthorizationException
*
* @operationId createTag
*/
public function store(Organization $organization, TagStoreRequest $request): TagResource
{
$this->checkPermission($organization, 'tags:create');
$tag = new Tag;
$tag->name = $request->input('name');
$tag->organization()->associate($organization);
$tag->save();
return new TagResource($tag);
}
/**
* Update tag
*
* @throws AuthorizationException
*
* @operationId updateTag
*/
public function update(Organization $organization, Tag $tag, TagUpdateRequest $request): TagResource
{
$this->checkPermission($organization, 'tags:update', $tag);
$tag->name = $request->input('name');
$tag->save();
return new TagResource($tag);
}
/**
* Delete tag
*
* @throws AuthorizationException|EntityStillInUseApiException
*
* @operationId deleteTag
*/
public function destroy(Organization $organization, Tag $tag): JsonResponse
{
$this->checkPermission($organization, 'tags:delete', $tag);
if (TimeEntry::query()->hasTag($tag)->whereBelongsTo($organization, 'organization')->exists()) {
throw new EntityStillInUseApiException('tag', 'time_entry');
}
$tag->delete();
return response()->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/TaskController.php
================================================
organization_id !== $organization->id) {
throw new AuthorizationException('Task does not belong to organization');
}
}
/**
* Check scoped permission and verify user has access to the project
*
* @throws AuthorizationException
*/
private function checkScopedPermissionForProject(Organization $organization, Project $project, string $permission): void
{
$this->checkPermission($organization, $permission);
$user = $this->user();
$hasAccess = Project::query()
->where('id', $project->id)
->visibleByEmployee($user)
->exists();
if (! $hasAccess) {
throw new AuthorizationException('You do not have permission to '.$permission.' in this project.');
}
}
/**
* Get tasks
*
* @return TaskCollection
*
* @throws AuthorizationException
*
* @operationId getTasks
*/
public function index(Organization $organization, TaskIndexRequest $request): TaskCollection
{
$this->checkPermission($organization, 'tasks:view');
$canViewAllTasks = $this->hasPermission($organization, 'tasks:view:all');
$user = $this->user();
$projectId = $request->input('project_id');
$query = Task::query()
->whereBelongsTo($organization, 'organization');
if ($projectId !== null) {
$query->where('project_id', '=', $projectId);
}
if (! $canViewAllTasks) {
$query->visibleByEmployee($user);
}
$doneFilter = $request->getFilterDone();
if ($doneFilter === 'true') {
$query->whereNotNull('done_at');
} elseif ($doneFilter === 'false') {
$query->whereNull('done_at');
}
$tasks = $query
->orderBy('created_at', 'desc')
->paginate(config('app.pagination_per_page_default'));
return new TaskCollection($tasks);
}
/**
* Create task
*
* @throws AuthorizationException
*
* @operationId createTask
*/
public function store(Organization $organization, TaskStoreRequest $request): JsonResource
{
/** @var Project $project */
$project = Project::query()->findOrFail($request->input('project_id'));
if ($this->hasPermission($organization, 'tasks:create:all')) {
$this->checkPermission($organization, 'tasks:create:all');
} else {
$this->checkScopedPermissionForProject($organization, $project, 'tasks:create');
}
$task = new Task;
$task->name = $request->input('name');
$task->project_id = $request->input('project_id');
if ($this->canAccessPremiumFeatures($organization) && $request->has('estimated_time')) {
$task->estimated_time = $request->getEstimatedTime();
}
$task->organization()->associate($organization);
$task->save();
return new TaskResource($task);
}
/**
* Update task
*
* @throws AuthorizationException
*
* @operationId updateTask
*/
public function update(Organization $organization, Task $task, TaskUpdateRequest $request): JsonResource
{
// Check task belongs to organization
if ($task->organization_id !== $organization->id) {
throw new AuthorizationException('Task does not belong to organization');
}
if ($this->hasPermission($organization, 'tasks:update:all')) {
$this->checkPermission($organization, 'tasks:update:all');
} else {
$this->checkScopedPermissionForProject($organization, $task->project, 'tasks:update');
}
$task->name = $request->input('name');
if ($this->canAccessPremiumFeatures($organization) && $request->has('estimated_time')) {
$task->estimated_time = $request->getEstimatedTime();
}
if ($request->has('is_done')) {
$task->done_at = $request->getIsDone() ? Carbon::now() : null;
}
$task->save();
return new TaskResource($task);
}
/**
* Delete task
*
* @throws AuthorizationException|EntityStillInUseApiException
*
* @operationId deleteTask
*/
public function destroy(Organization $organization, Task $task): JsonResponse
{
// Check task belongs to organization
if ($task->organization_id !== $organization->id) {
throw new AuthorizationException('Task does not belong to organization');
}
if ($this->hasPermission($organization, 'tasks:delete:all')) {
$this->checkPermission($organization, 'tasks:delete:all');
} else {
$this->checkScopedPermissionForProject($organization, $task->project, 'tasks:delete');
}
if ($task->timeEntries()->exists()) {
throw new EntityStillInUseApiException('task', 'time_entry');
}
$task->delete();
return response()
->json(null, 204);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/TimeEntryController.php
================================================
prevent_overlapping_time_entries) {
return;
}
$query = TimeEntry::query()
->where('organization_id', $organization->getKey())
->where('user_id', $member->user_id)
->when($exclude !== null, function (Builder $q) use ($exclude): void {
$q->where('id', '!=', $exclude->getKey());
})
->where(function (Builder $q) use ($start, $end): void {
$q->where(function (Builder $q2) use ($start): void {
$q2->where('end', '>', $start)
->where('start', '<', $start);
});
if ($end !== null) {
$q->orWhere(function (Builder $q4) use ($end): void {
$q4->where('start', '<', $end)
->where('end', '>', $end);
});
// Check if the new entry completely surrounds an existing entry
$q->orWhere(function (Builder $q6) use ($start, $end): void {
$q6->where('start', '>=', $start)
->where('end', '<=', $end);
});
}
});
if ($query->exists()) {
throw new OverlappingTimeEntryApiException;
}
}
protected function checkPermission(Organization $organization, string $permission, ?TimeEntry $timeEntry = null): void
{
parent::checkPermission($organization, $permission);
if ($timeEntry !== null && $timeEntry->organization_id !== $organization->getKey()) {
throw new AuthorizationException('Time entry does not belong to organization');
}
}
/**
* Get time entries in organization
*
* 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
*
* @throws AuthorizationException
*
* @operationId getTimeEntries
*/
public function index(Organization $organization, TimeEntryIndexRequest $request): JsonResource
{
/** @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, $member, $canAccessPremiumFeatures);
$totalCount = $timeEntriesQuery->count();
$limit = $request->getLimit();
if ($limit > 1000) {
$limit = 1000;
}
$timeEntriesQuery->limit($limit);
$timeEntriesQuery->skip($request->getOffset());
$timeEntries = $timeEntriesQuery->get();
if ($timeEntries->count() === $limit && $request->getOnlyFullDates()) {
$user = $this->user();
$timezone = app(TimezoneService::class)->getTimezoneFromUser($user);
$lastDate = null;
/** @var TimeEntry $timeEntry */
foreach ($timeEntries as $timeEntry) {
if ($lastDate === null || abs($lastDate->diffInDays($timeEntry->start->toImmutable()->timezone($timezone)->startOfDay())) > 0) {
$lastDate = $timeEntry->start->toImmutable()->timezone($timezone)->startOfDay();
}
}
$timeEntries = $timeEntries->filter(function (TimeEntry $timeEntry) use ($lastDate, $timezone): bool {
return $timeEntry->start->toImmutable()->timezone($timezone)->toDateString() !== $lastDate->toDateString();
});
if ($timeEntries->count() === 0) {
Log::warning('User has has more than '.$limit.' time entries on one date', [
'date' => $lastDate->toDateString(),
'user_id' => $request->input('user_id'),
'auth_user_id' => Auth::id(),
'limit' => $limit,
]);
$timeEntries = $timeEntriesQuery
->limit(5000)
->where('start', '>=', $lastDate->copy()->startOfDay()->utc())
->where('start', '<=', $lastDate->copy()->endOfDay()->utc())
->get();
}
}
return (new TimeEntryCollection($timeEntries))
->additional([
'meta' => [
'total' => $totalCount,
],
]);
}
/**
* @return Builder
*/
private function getTimeEntriesQuery(Organization $organization, TimeEntryIndexRequest|TimeEntryIndexExportRequest $request, ?Member $member, bool $canAccessPremiumFeatures): Builder
{
$select = TimeEntry::SELECT_COLUMNS;
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
if ($roundingType !== null && $roundingMinutes !== null) {
$select = array_diff($select, ['start', 'end']);
$select[] = DB::raw(app(TimeEntryService::class)->getStartSelectRawForRounding($roundingType, $roundingMinutes).' as start');
$select[] = DB::raw(app(TimeEntryService::class)->getEndSelectRawForRounding($roundingType, $roundingMinutes).' as end');
}
$timeEntriesQuery = TimeEntry::query()
->whereBelongsTo($organization, 'organization')
->select($select)
->orderBy('start', 'desc');
$filter = new TimeEntryFilter($timeEntriesQuery);
$filter->addStartFilter($request->input('start'));
$filter->addEndFilter($request->input('end'));
$filter->addActiveFilter($request->input('active'));
$filter->addMemberIdFilter($member);
$filter->addMemberIdsFilter($request->input('member_ids'));
$filter->addProjectIdsFilter($request->input('project_ids'));
$filter->addTagIdsFilter($request->input('tag_ids'));
$filter->addTaskIdsFilter($request->input('task_ids'));
$filter->addClientIdsFilter($request->input('client_ids'));
$filter->addBillableFilter($request->input('billable'));
return $filter->get();
}
/**
* Export time entries in organization
*
* @throws AuthorizationException|PdfRendererIsNotConfiguredException|FeatureIsNotAvailableInFreePlanApiException
*
* @operationId exportTimeEntries
*/
public function indexExport(Organization $organization, TimeEntryIndexExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService): JsonResponse
{
/** @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);
$debug = $request->getDebug();
$format = $request->getFormatValue();
if ($format === ExportFormat::PDF && ! $canAccessPremiumFeatures) {
throw new FeatureIsNotAvailableInFreePlanApiException;
}
$user = $this->user();
$timezone = $user->timezone;
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
$timeEntriesQuery = $this->getTimeEntriesQuery($organization, $request, $member, $canAccessPremiumFeatures);
$timeEntriesQuery->with([
'task',
'client',
'project',
'user',
'tagsRelation',
]);
$filename = 'time-entries-export-'.now()->format('Y-m-d_H-i-s').'.'.$format->getFileExtension();
$folderPath = 'exports';
$path = $folderPath.'/'.$filename;
$localizationService = LocalizationService::forOrganization($organization);
if ($format === ExportFormat::CSV) {
$export = new TimeEntriesDetailedCsvExport(config('filesystems.private'), $folderPath, $filename, $timeEntriesQuery, 1000, $timezone);
$export->export();
} elseif ($format === ExportFormat::PDF) {
if (config('services.gotenberg.url') === null && ! $debug) {
throw new PdfRendererIsNotConfiguredException;
}
$viewFile = file_get_contents(resource_path('views/reports/time-entry-index/pdf.blade.php'));
if ($viewFile === false) {
throw new \LogicException('View file not found');
}
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
$aggregatedData = $timeEntryAggregationService->getAggregatedTimeEntries(
$timeEntriesAggregateQuery,
null,
null,
$user->timezone,
$user->week_start,
false,
null,
null,
$showBillableRate,
$roundingType,
$roundingMinutes,
);
$html = Blade::render($viewFile, [
'timeEntries' => $timeEntriesQuery->get(),
'aggregatedData' => $aggregatedData,
'timezone' => $timezone,
'currency' => $organization->currency,
'start' => $request->getStart()->timezone($timezone),
'end' => $request->getEnd()->timezone($timezone),
'localization' => $localizationService,
'showBillableRate' => $showBillableRate,
]);
$footerViewFile = file_get_contents(resource_path('views/reports/time-entry-index/pdf-footer.blade.php'));
if ($footerViewFile === false) {
throw new \LogicException('View file not found');
}
$footerHtml = Blade::render($footerViewFile);
if ($debug) {
return response()->json([
'html' => $html,
'footer_html' => $footerHtml,
]);
}
$client = new Client([
'auth' => config('services.gotenberg.basic_auth_username') !== null && config('services.gotenberg.basic_auth_password') !== null ? [
config('services.gotenberg.basic_auth_username'),
config('services.gotenberg.basic_auth_password'),
] : null,
]);
$request = Gotenberg::chromium(config('services.gotenberg.url'))
->pdf()
->assets(
Stream::path(resource_path('pdf/Outfit-VariableFont_wght.ttf'), 'outfit.ttf'),
)
->margins(0.39, 0.78, 0.39, 0.39)
->paperSize('8.27', '11.7') // A4
->footer(Stream::string('footer', $footerHtml))
->html(Stream::string('body', $html));
$tempFolder = TemporaryDirectory::make();
$filenameTemp = Gotenberg::save($request, $tempFolder->path(), $client);
Storage::disk(config('filesystems.private'))
->putFileAs($folderPath, new File($tempFolder->path($filenameTemp)), $filename);
} else {
Excel::store(
new TimeEntriesDetailedExport($timeEntriesQuery, $format, $timezone, $localizationService),
$path,
config('filesystems.private'),
$format->getExportPackageType(),
[
'visibility' => 'private',
]
);
}
return response()->json([
'download_url' => Storage::disk(config('filesystems.private'))
->temporaryUrl($path, now()->addMinutes(5)),
]);
}
/**
* Get aggregated time entries in organization
*
* This endpoint allows you to filter time entries and aggregate them by different criteria.
* The parameters `group` and `sub_group` allow you to group the time entries by different criteria.
* If the group parameters are all set to `null` or are all missing, the endpoint will aggregate all filtered time entries.
*
* @operationId getAggregatedTimeEntries
*
* @return array{
* data: array{
* grouped_type: string|null,
* grouped_data: null|array
* }>,
* seconds: int,
* cost: int|null
* }
* }
*
* @throws AuthorizationException
*/
public function aggregate(Organization $organization, TimeEntryAggregateRequest $request, TimeEntryAggregationService $timeEntryAggregationService): array
{
/** @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);
$user = $this->user();
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
$group1Type = $request->getGroup();
$group2Type = $request->getSubGroup();
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
$aggregatedData = $timeEntryAggregationService->getAggregatedTimeEntries(
$timeEntriesAggregateQuery,
$group1Type,
$group2Type,
$user->timezone,
$user->week_start,
$request->getFillGapsInTimeGroups(),
$request->getStart(),
$request->getEnd(),
$showBillableRate,
$roundingType,
$roundingMinutes
);
return [
'data' => $aggregatedData,
];
}
/**
* Export aggregated time entries in organization
*
* @operationId exportAggregatedTimeEntries
*
* @throws AuthorizationException
* @throws PdfRendererIsNotConfiguredException
* @throws GotenbergApiErrored
* @throws NoOutputFileInResponse
* @throws FeatureIsNotAvailableInFreePlanApiException
*/
public function aggregateExport(Organization $organization, TimeEntryAggregateExportRequest $request, TimeEntryAggregationService $timeEntryAggregationService): JsonResponse
{
/** @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);
$format = $request->getFormatValue();
if ($format === ExportFormat::PDF && ! $this->canAccessPremiumFeatures($organization)) {
throw new FeatureIsNotAvailableInFreePlanApiException;
}
$debug = $request->getDebug();
$user = $this->user();
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
$group = $request->getGroup();
$subGroup = $request->getSubGroup();
$timeEntriesAggregateQuery = $this->getTimeEntriesAggregateQuery($organization, $request, $member);
$roundingType = $canAccessPremiumFeatures ? $request->getRoundingType() : null;
$roundingMinutes = $canAccessPremiumFeatures ? $request->getRoundingMinutes() : null;
$aggregatedData = $timeEntryAggregationService->getAggregatedTimeEntriesWithDescriptions(
$timeEntriesAggregateQuery->clone(),
$group,
$subGroup,
$user->timezone,
$user->week_start,
false,
$request->getStart(),
$request->getEnd(),
$showBillableRate,
$roundingType,
$roundingMinutes
);
$dataHistoryChart = $timeEntryAggregationService->getAggregatedTimeEntries(
$timeEntriesAggregateQuery->clone(),
$request->getHistoryGroup(),
null,
$user->timezone,
$user->week_start,
true,
$request->getStart(),
$request->getEnd(),
$showBillableRate,
$roundingType,
$roundingMinutes
);
$currency = $organization->currency;
$timezone = app(TimezoneService::class)->getTimezoneFromUser($this->user());
$localizationService = LocalizationService::forOrganization($organization);
$filename = 'time-entries-report-'.now()->format('Y-m-d_H-i-s').'.'.$format->getFileExtension();
$folderPath = 'exports';
$path = $folderPath.'/'.$filename;
if ($format === ExportFormat::PDF) {
if (config('services.gotenberg.url') === null && ! $debug) {
throw new PdfRendererIsNotConfiguredException;
}
$client = new Client([
'auth' => config('services.gotenberg.basic_auth_username') !== null && config('services.gotenberg.basic_auth_password') !== null ? [
config('services.gotenberg.basic_auth_username'),
config('services.gotenberg.basic_auth_password'),
] : null,
]);
$viewFile = file_get_contents(resource_path('views/reports/time-entry-aggregate/pdf.blade.php'));
if ($viewFile === false) {
throw new \LogicException('View file not found');
}
$html = Blade::render($viewFile, [
'aggregatedData' => $aggregatedData,
'dataHistoryChart' => $dataHistoryChart,
'currency' => $currency,
'group' => $group,
'subGroup' => $subGroup,
'timezone' => $timezone,
'start' => $request->getStart()->timezone($timezone),
'end' => $request->getEnd()->timezone($timezone),
'debug' => $debug,
'localization' => $localizationService,
'showBillableRate' => $showBillableRate,
]);
$footerViewFile = file_get_contents(resource_path('views/reports/time-entry-aggregate/pdf-footer.blade.php'));
if ($footerViewFile === false) {
throw new \LogicException('View file not found');
}
$footerHtml = Blade::render($footerViewFile);
if ($debug) {
return response()->json([
'html' => $html,
'footer_html' => $footerHtml,
]);
}
$request = Gotenberg::chromium(config('services.gotenberg.url'))
->pdf()
->waitForExpression("window.status === 'ready'")
->margins(0.39, 0.78, 0.39, 0.39)
->paperSize('8.27', '11.7') // A4
->footer(Stream::string('footer', $footerHtml))
->assets(Stream::path(resource_path('pdf/echarts.min.js'), 'echarts.min.js'),
Stream::path(resource_path('pdf/Outfit-VariableFont_wght.ttf'), 'outfit.ttf'),
)
->html(Stream::string('body', $html));
$tempFolder = TemporaryDirectory::make();
$filenameTemp = Gotenberg::save($request, $tempFolder->path(), $client);
Storage::disk(config('filesystems.private'))
->putFileAs($folderPath, new File($tempFolder->path($filenameTemp)), $filename);
} else {
Excel::store(
new TimeEntriesReportExport($aggregatedData, $format, $currency, $group, $subGroup, $showBillableRate),
$path,
config('filesystems.private'),
$format->getExportPackageType(),
[
'visibility' => 'private',
]
);
}
return response()->json([
'download_url' => Storage::disk(config('filesystems.private'))
->temporaryUrl($path, now()->addMinutes(5)),
]);
}
/**
* @return Builder
*/
private function getTimeEntriesAggregateQuery(Organization $organization, TimeEntryAggregateRequest|TimeEntryAggregateExportRequest|TimeEntryIndexExportRequest $request, ?Member $member): Builder
{
$timeEntriesQuery = TimeEntry::query()
->whereBelongsTo($organization, 'organization');
$filter = new TimeEntryFilter($timeEntriesQuery);
$filter->addEndFilter($request->input('end'));
$filter->addStartFilter($request->input('start'));
$filter->addActiveFilter($request->input('active'));
$filter->addMemberIdFilter($member);
$filter->addMemberIdsFilter($request->input('member_ids'));
$filter->addProjectIdsFilter($request->input('project_ids'));
$filter->addTagIdsFilter($request->input('tag_ids'));
$filter->addTaskIdsFilter($request->input('task_ids'));
$filter->addClientIdsFilter($request->input('client_ids'));
$filter->addBillableFilter($request->input('billable'));
return $filter->get();
}
/**
* Create time entry
*
* @throws AuthorizationException
* @throws TimeEntryStillRunningApiException
*
* @operationId createTimeEntry
*/
public function store(Organization $organization, TimeEntryStoreRequest $request): JsonResource
{
/** @var Member $member */
$member = Member::query()->findOrFail($request->input('member_id'));
if ($member->user_id === Auth::id()) {
$this->checkPermission($organization, 'time-entries:create:own');
} else {
$this->checkPermission($organization, 'time-entries:create:all');
}
if ($request->input('end') === null && TimeEntry::query()->whereBelongsTo($member, 'member')->where('end', null)->exists()) {
throw new TimeEntryStillRunningApiException;
}
// Overlap check for create
$start = Carbon::parse($request->input('start'));
$end = $request->input('end') !== null ? Carbon::parse($request->input('end')) : null;
$this->assertNoOverlap($organization, $member, $start, $end);
$project = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id')) : null;
$client = $project?->client;
$task = $request->input('task_id') !== null ? $project->tasks()->findOrFail((string) $request->input('task_id')) : null;
$timeEntry = new TimeEntry;
$timeEntry->fill($request->validated());
$timeEntry->client()->associate($client);
$timeEntry->user_id = $member->user_id;
$timeEntry->description = $request->input('description') ?? '';
$timeEntry->organization()->associate($organization);
$timeEntry->setComputedAttributeValue('billable_rate');
$timeEntry->save();
if ($project !== null) {
RecalculateSpentTimeForProject::dispatch($project);
}
if ($task !== null) {
RecalculateSpentTimeForTask::dispatch($task);
}
return new TimeEntryResource($timeEntry);
}
/**
* Update time entry
*
* @throws AuthorizationException|TimeEntryCanNotBeRestartedApiException
*
* @operationId updateTimeEntry
*/
public function update(Organization $organization, TimeEntry $timeEntry, TimeEntryUpdateRequest $request): JsonResource
{
/** @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');
} else {
$this->checkPermission($organization, 'time-entries:update:all');
}
if ($timeEntry->end !== null && $request->has('end') && $request->input('end') === null) {
throw new TimeEntryCanNotBeRestartedApiException;
}
// Overlap check for update (exclude current)
/** @var Member $effectiveMember */
$effectiveMember = $request->has('member_id') ? Member::query()->findOrFail($request->input('member_id')) : $timeEntry->member;
$effectiveStart = $request->has('start') ? Carbon::parse($request->input('start')) : $timeEntry->start;
$effectiveEnd = $request->has('end') ? ($request->input('end') !== null ? Carbon::parse($request->input('end')) : null) : $timeEntry->end;
$this->assertNoOverlap($organization, $effectiveMember, $effectiveStart, $effectiveEnd, $timeEntry);
$oldProject = $timeEntry->project;
$oldTask = $timeEntry->task;
$project = null;
if ($request->has('project_id')) {
$project = $request->input('project_id') !== null ? Project::findOrFail((string) $request->input('project_id')) : null;
$client = $project?->client;
$timeEntry->client()->associate($client);
}
$task = null;
if ($request->has('task_id')) {
$task = $request->input('task_id') !== null ? Task::findOrFail((string) $request->input('task_id')) : null;
}
$timeEntry->fill($request->validated());
$timeEntry->description = $request->input('description', $timeEntry->description) ?? '';
$timeEntry->setComputedAttributeValue('billable_rate');
$timeEntry->save();
if ($oldProject !== null) {
RecalculateSpentTimeForProject::dispatch($oldProject);
}
if ($oldTask !== null) {
RecalculateSpentTimeForTask::dispatch($oldTask);
}
if ($project !== null && ($oldProject === null || $project->isNot($oldProject))) {
RecalculateSpentTimeForProject::dispatch($project);
}
if ($task !== null && ($oldTask === null || $task->isNot($oldTask))) {
RecalculateSpentTimeForTask::dispatch($task);
}
return new TimeEntryResource($timeEntry);
}
/**
* Update multiple time entries
*
* @operationId updateMultipleTimeEntries
*
* @throws AuthorizationException
*/
public function updateMultiple(Organization $organization, TimeEntryUpdateMultipleRequest $request): JsonResponse
{
$this->checkAnyPermission($organization, ['time-entries:update:all', 'time-entries:update:own']);
$canAccessAll = $this->hasPermission($organization, 'time-entries:update:all');
$ids = $request->validated('ids');
$timeEntries = TimeEntry::query()
->whereBelongsTo($organization, 'organization')
->with([
'project',
'task',
])
->whereIn('id', $ids)
->get();
$changes = $request->validated('changes');
if ($request->has('changes.description')) {
$changes['description'] = $request->input('changes.description') ?? '';
}
if (isset($changes['member_id']) && ! $canAccessAll && $this->member($organization)->getKey() !== $changes['member_id']) {
throw new AuthorizationException;
}
$project = null;
$client = null;
$overwriteClient = false;
if ($request->has('changes.project_id')) {
$project = $request->input('changes.project_id') !== null ? Project::findOrFail((string) $request->input('changes.project_id')) : null;
$client = $project?->client;
$overwriteClient = true;
}
$task = null;
if ($request->has('changes.task_id')) {
$task = $request->input('changes.task_id') !== null ? Task::findOrFail((string) $request->input('changes.task_id')) : null;
}
$success = new Collection;
$error = new Collection;
foreach ($ids as $id) {
/** @var TimeEntry|null $timeEntry */
$timeEntry = $timeEntries->firstWhere('id', $id);
if ($timeEntry === null) {
// Note: ID wrong or time entry in different organization
$error->push($id);
continue;
}
if (! $canAccessAll && $timeEntry->user_id !== Auth::id()) {
$error->push($id);
continue;
}
$oldProject = $timeEntry->project;
$oldTask = $timeEntry->task;
$timeEntry->fill($changes);
// 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();
}
if ($overwriteClient) {
$timeEntry->client()->associate($client);
}
$timeEntry->setComputedAttributeValue('billable_rate');
$timeEntry->save();
if ($oldTask !== null) {
RecalculateSpentTimeForTask::dispatch($oldTask);
}
if ($oldProject !== null) {
RecalculateSpentTimeForProject::dispatch($oldProject);
}
if ($project !== null && ($oldProject === null || $project->isNot($oldProject))) {
RecalculateSpentTimeForProject::dispatch($project);
}
if ($task !== null && ($oldTask === null || $task->isNot($oldTask))) {
RecalculateSpentTimeForTask::dispatch($task);
}
$success->push($id);
}
return response()->json([
'success' => $success->toArray(),
'error' => $error->toArray(),
]);
}
/**
* Delete time entry
*
* @throws AuthorizationException
*
* @operationId deleteTimeEntry
*/
public function destroy(Organization $organization, TimeEntry $timeEntry): JsonResponse
{
if ($timeEntry->member->user_id === Auth::id()) {
$this->checkPermission($organization, 'time-entries:delete:own', $timeEntry);
} else {
$this->checkPermission($organization, 'time-entries:delete:all', $timeEntry);
}
$project = $timeEntry->project;
$task = $timeEntry->task;
$timeEntry->delete();
if ($project !== null) {
RecalculateSpentTimeForProject::dispatch($project);
}
if ($task !== null) {
RecalculateSpentTimeForTask::dispatch($task);
}
return response()
->json(null, 204);
}
/**
* Delete multiple time entries
*
* @throws AuthorizationException
*
* @operationId deleteTimeEntries
*/
public function destroyMultiple(Organization $organization, TimeEntryDestroyMultipleRequest $request): JsonResponse
{
$this->checkAnyPermission($organization, ['time-entries:delete:all', 'time-entries:delete:own']);
$canDeleteAll = $this->hasPermission($organization, 'time-entries:delete:all');
$ids = $request->validated('ids');
$timeEntries = TimeEntry::query()
->whereBelongsTo($organization, 'organization')
->with([
'project',
'task',
])
->whereIn('id', $ids)
->get();
$success = new Collection;
$error = new Collection;
foreach ($ids as $id) {
/** @var TimeEntry|null $timeEntry */
$timeEntry = $timeEntries->firstWhere('id', $id);
if ($timeEntry === null) {
// Note: ID wrong or time entry in different organization
$error->push($id);
continue;
}
if (! $canDeleteAll && $timeEntry->user_id !== Auth::id()) {
$error->push($id);
continue;
}
$project = $timeEntry->project;
$task = $timeEntry->task;
$timeEntry->delete();
if ($project !== null) {
RecalculateSpentTimeForProject::dispatch($project);
}
if ($task !== null) {
RecalculateSpentTimeForTask::dispatch($task);
}
$success->push($id);
}
return response()->json([
'success' => $success->toArray(),
'error' => $error->toArray(),
]);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/UserController.php
================================================
user();
return new UserResource($user);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/UserMembershipController.php
================================================
user();
$members = Member::query()
->whereBelongsTo($user, 'user')
->with(['organization'])
->get();
return new PersonalMembershipCollection($members);
}
}
================================================
FILE: app/Http/Controllers/Api/V1/UserTimeEntryController.php
================================================
user();
$activeTimeEntriesOfUser = TimeEntry::query()
->whereBelongsTo($user, 'user')
->whereNull('end')
->orderBy('start', 'desc')
->get();
if ($activeTimeEntriesOfUser->count() > 1) {
Log::warning('User has more than one active time entry.', [
'user' => $user->getKey(),
]);
}
$activeTimeEntry = $activeTimeEntriesOfUser->first();
if ($activeTimeEntry !== null) {
return new TimeEntryResource($activeTimeEntry);
} else {
throw new ModelNotFoundException('No active time entry');
}
}
}
================================================
FILE: app/Http/Controllers/Controller.php
================================================
user();
/** @var Member|null $member */
$member = Member::query()->whereBelongsTo($organization, 'organization')->whereBelongsTo($user, 'user')->first();
if ($member === null) {
Log::error('This function should only be called in authenticated context after checking the user is a member of the organization', [
'user' => $user->getKey(),
'organization' => $organization->getKey(),
]);
throw new AuthorizationException;
}
return $member;
}
/**
* @throws AuthorizationException
*/
protected function currentOrganization(): Organization
{
$user = $this->user();
$organization = $user->currentTeam;
if ($organization === null) {
$organization = $user->organizations()->first();
}
return $organization;
}
}
================================================
FILE: app/Http/Controllers/Web/Controller.php
================================================
user();
$organization = $this->currentOrganization();
$latestTeamActivity = null;
if ($permissionStore->has($organization, 'time-entries:view:all')) {
$latestTeamActivity = $dashboardService->latestTeamActivity($organization);
}
$showBillableRate = $this->member($organization)->role !== Role::Employee->value || $organization->employees_can_see_billable_rates;
return Inertia::render('Dashboard');
}
}
================================================
FILE: app/Http/Controllers/Web/HealthCheckController.php
================================================
json([
'success' => true,
]);
}
/**
* Debug information for the application
* This check checks the database and cache connectivity
*/
public function debug(Request $request): JsonResponse
{
// Check database connectivity
User::query()->count();
// Check cache connectivity
Cache::put('health-check', Carbon::now()->timestamp);
// Check ip address correct behind load balancer
$ipAddress = $request->ip();
$hostname = $request->getHost();
$secure = $request->secure();
$isTrustedProxy = $request->isFromTrustedProxy();
$dbTimezone = DB::select('show timezone;');
$response = [
'ip_address' => $ipAddress,
'url' => $request->url(),
'path' => $request->path(),
'hostname' => $hostname,
'timestamp' => Carbon::now()->timestamp,
'date_time_utc' => Carbon::now('UTC')->toDateTimeString(),
'date_time_app' => Carbon::now()->toDateTimeString(),
'timezone' => $dbTimezone[0]->TimeZone,
'secure' => $secure,
'is_trusted_proxy' => $isTrustedProxy,
];
if (app()->hasDebugModeEnabled()) {
$response['app_debug'] = true;
$response['app_url'] = config('app.url');
$response['app_env'] = app()->environment();
$response['app_timezone'] = config('app.timezone');
$response['app_force_https'] = config('app.force_https');
$response['session_secure'] = config('session.secure');
$response['trusted_proxies'] = config('trustedproxy.proxies');
$headers = $request->headers->all();
if (isset($headers['cookie'])) {
$headers['cookie'] = '***';
}
$response['headers'] = $headers;
}
return response()
->json($response);
}
}
================================================
FILE: app/Http/Controllers/Web/HomeController.php
================================================
route('dashboard');
} else {
return redirect('login');
}
}
}
================================================
FILE: app/Http/Kernel.php
================================================
*/
protected $middleware = [
\App\Http\Middleware\ForceHttps::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\HandleInertiaRequests::class,
\App\Http\Middleware\ShareInertiaData::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
'api' => [
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
ForceJsonResponse::class,
],
'health-check' => [
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
*
* @var array
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \App\Http\Middleware\EnsureEmailIsVerified::class,
'check-organization-blocked' => CheckOrganizationBlocked::class,
];
}
================================================
FILE: app/Http/Middleware/Authenticate.php
================================================
expectsJson() ? null : route('login');
}
}
================================================
FILE: app/Http/Middleware/CheckOrganizationBlocked.php
================================================
route('organization');
if (! ($organization instanceof Organization)) {
throw new \LogicException('The organization must be loaded before this middleware.');
}
/** @var BillingContract $billing */
$billing = app(BillingContract::class);
if ($billing->isBlocked($organization)) {
throw new OrganizationHasNoSubscriptionButMultipleMembersException;
}
return $next($request);
}
}
================================================
FILE: app/Http/Middleware/EncryptCookies.php
================================================
*/
protected $except = [
//
];
}
================================================
FILE: app/Http/Middleware/EnsureEmailIsVerified.php
================================================
isLocal()) {
if ($request->user() === null ||
(! $request->user()->hasVerifiedEmail())) {
return $request->expectsJson()
? abort(403, 'Your email address is not verified.')
: Redirect::guest(URL::route($redirectToRoute ?: 'verification.notice'));
}
}
return $next($request);
}
}
================================================
FILE: app/Http/Middleware/ForceHttps.php
================================================
server->set('HTTPS', 'on');
$request->headers->set('X-Forwarded-Proto', 'https');
}
return $next($request);
}
}
================================================
FILE: app/Http/Middleware/ForceJsonResponse.php
================================================
headers->set('Accept', 'application/json');
return $next($request);
}
}
================================================
FILE: app/Http/Middleware/HandleInertiaRequests.php
================================================
*/
public function share(Request $request): array
{
$hasBilling = Module::has('Billing') && Module::isEnabled('Billing');
$hasInvoicing = Module::has('Invoicing') && Module::isEnabled('Invoicing');
$hasServices = Module::has('Services') && Module::isEnabled('Services');
/** @var BillingContract $billing */
$billing = app(BillingContract::class);
$currentOrganization = $request->user()?->currentTeam;
return array_merge(parent::share($request), [
'has_billing_extension' => $hasBilling,
'has_invoicing_extension' => $hasInvoicing,
'has_services_extension' => $hasServices,
'billing' => $currentOrganization !== null ? [
'has_subscription' => $billing->hasSubscription($currentOrganization),
'has_trial' => $billing->hasTrial($currentOrganization),
'trial_until' => $billing->getTrialUntil($currentOrganization)?->toIso8601ZuluString(),
'is_blocked' => $billing->isBlocked($currentOrganization),
] : null,
'flash' => [
'message' => fn () => $request->session()->get('message'),
],
]);
}
}
================================================
FILE: app/Http/Middleware/PreventRequestsDuringMaintenance.php
================================================
*/
protected $except = [
//
];
}
================================================
FILE: app/Http/Middleware/RedirectIfAuthenticated.php
================================================
check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
================================================
FILE: app/Http/Middleware/ShareInertiaData.php
================================================
function () use ($request) {
/** @var User|null $user */
$user = $request->user();
return [
'canCreateTeams' => $user !== null &&
Jetstream::userHasTeamFeatures($user) &&
Gate::forUser($user)->check('create', Jetstream::newTeamModel()),
'canManageTwoFactorAuthentication' => Features::canManageTwoFactorAuthentication(),
'canUpdatePassword' => Features::enabled(Features::updatePasswords()),
'canUpdateProfileInformation' => Features::canUpdateProfileInformation(),
'hasEmailVerification' => Features::enabled(Features::emailVerification()),
'flash' => $request->session()->get('flash', []),
'hasAccountDeletionFeatures' => Jetstream::hasAccountDeletionFeatures(),
'hasApiFeatures' => Jetstream::hasApiFeatures(),
'hasTeamFeatures' => Jetstream::hasTeamFeatures(),
'hasTermsAndPrivacyPolicyFeature' => Jetstream::hasTermsAndPrivacyPolicyFeature(),
'managesProfilePhotos' => Jetstream::managesProfilePhotos(),
];
},
'auth' => [
'permissions' => $request->user() !== null && $request->user()->currentTeam !== null ? $permissions->getPermissions($request->user()->currentTeam) : [],
'user' => function () use ($request): array {
/** @var User|null $user */
$user = $request->user();
if ($user === null) {
return [];
}
return array_merge([
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'email_verified_at' => $user->email_verified_at,
'current_team_id' => $user->current_team_id,
'profile_photo_path' => $user->profile_photo_path,
'timezone' => $user->timezone,
'week_start' => $user->week_start,
'profile_photo_url' => $user->profile_photo_url,
'two_factor_enabled' => Features::enabled(Features::twoFactorAuthentication())
&& ! is_null($user->two_factor_secret),
'current_team' => $user->currentTeam !== null ? [
'id' => $user->currentTeam->id,
'user_id' => $user->currentTeam->user_id,
'name' => $user->currentTeam->name,
'personal_team' => $user->currentTeam->personal_team,
'currency' => $user->currentTeam->currency,
] : null,
], array_filter([
'all_teams' => $user->organizations->map(function (Organization $organization): array {
return [
'id' => $organization->id,
'name' => $organization->name,
'personal_team' => $organization->personal_team,
'currency' => $organization->currency,
'membership' => [
'role' => $organization->membership->role,
'id' => $organization->membership->id,
],
];
})->all(),
]));
},
],
'errorBags' => function () {
/** @var array|null $bags */
$bags = Session::get('errors')?->getBags();
$bagsCollection = collect($bags ?: []);
return $bagsCollection->mapWithKeys(function (MessageBag $bag, string $key) {
return [$key => $bag->messages()];
})->all();
},
]);
return $next($request);
}
}
================================================
FILE: app/Http/Middleware/TrimStrings.php
================================================
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
================================================
FILE: app/Http/Middleware/TrustProxies.php
================================================
|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB |
Request::HEADER_X_FORWARDED_TRAEFIK;
}
================================================
FILE: app/Http/Middleware/ValidateSignature.php
================================================
*/
protected array $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}
================================================
FILE: app/Http/Middleware/VerifyCsrfToken.php
================================================
*/
protected $except = [
//
];
}
================================================
FILE: app/Http/Requests/V1/ApiToken/ApiTokenStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'min:1',
'max:255',
],
];
}
public function getName(): string
{
return $this->input('name');
}
}
================================================
FILE: app/Http/Requests/V1/BaseFormRequest.php
================================================
*/
protected function moneyRules(bool $bigInt = false): array
{
$rules = [
'integer',
'min:0',
];
if ($bigInt) {
$rules[] = 'max:9223372036854775807';
} else {
$rules[] = 'max:2147483647';
}
return $rules;
}
}
================================================
FILE: app/Http/Requests/V1/Client/ClientIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
'archived' => [
'string',
'in:true,false,all',
],
];
}
public function getFilterArchived(): string
{
return $this->input('archived', 'false');
}
}
================================================
FILE: app/Http/Requests/V1/Client/ClientStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'min:1',
'max:255',
UniqueEloquent::make(Client::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->withCustomTranslation('validation.client_name_already_exists'),
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Client/ClientUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
// Name of the client
'name' => [
'required',
'string',
'min:1',
'max:255',
UniqueEloquent::make(Client::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->ignore($this->client?->getKey())->withCustomTranslation('validation.client_name_already_exists'),
],
'is_archived' => [
'boolean',
],
];
}
public function getIsArchived(): bool
{
assert($this->has('is_archived'));
return (bool) $this->input('is_archived');
}
}
================================================
FILE: app/Http/Requests/V1/Import/ImportRequest.php
================================================
>
*/
public function rules(): array
{
return [
'type' => [
'required',
'string',
],
'data' => [
'required',
'string',
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Invitation/InvitationIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Invitation/InvitationStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
'email' => [
'required',
'email',
],
'role' => [
'required',
'string',
Rule::enum(Role::class)
->except([Role::Owner, Role::Placeholder]),
],
];
}
public function getRole(): Role
{
return Role::from($this->input('role'));
}
public function getEmail(): string
{
return $this->input('email');
}
}
================================================
FILE: app/Http/Requests/V1/Member/MemberDestroyRequest.php
================================================
>
*/
public function rules(): array
{
return [
'delete_related' => [
'string',
'in:true,false',
],
];
}
public function getDeleteRelated(): bool
{
return $this->input('delete_related', 'false') === 'true';
}
}
================================================
FILE: app/Http/Requests/V1/Member/MemberIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Member/MemberMergeIntoRequest.php
================================================
>
*/
public function rules(): array
{
return [
// ID of the member to which the data should be transferred (destination)
'member_id' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
];
}
public function getMemberId(): string
{
return (string) $this->input('member_id');
}
}
================================================
FILE: app/Http/Requests/V1/Member/MemberUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
'role' => [
'string',
Rule::enum(Role::class),
],
'billable_rate' => array_merge(
[
'nullable',
],
$this->moneyRules()
),
];
}
public function getBillableRate(): ?int
{
$input = $this->input('billable_rate');
return $input !== null && $input !== 0 ? (int) $this->input('billable_rate') : null;
}
public function getRole(): Role
{
return Role::from($this->input('role'));
}
}
================================================
FILE: app/Http/Requests/V1/Organization/OrganizationUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'string',
'max:255',
],
'billable_rate' => array_merge(
[
'nullable',
],
$this->moneyRules()
),
'employees_can_see_billable_rates' => [
'boolean',
],
'employees_can_manage_tasks' => [
'boolean',
],
'prevent_overlapping_time_entries' => [
'boolean',
],
'number_format' => [
Rule::enum(NumberFormat::class),
],
'currency_format' => [
Rule::enum(CurrencyFormat::class),
],
'date_format' => [
Rule::enum(DateFormat::class),
],
'interval_format' => [
Rule::enum(IntervalFormat::class),
],
'time_format' => [
Rule::enum(TimeFormat::class),
],
];
}
public function getName(): ?string
{
return $this->has('name') ? (string) $this->input('name') : null;
}
public function getNumberFormat(): ?NumberFormat
{
return $this->has('number_format') ? NumberFormat::from($this->input('number_format')) : null;
}
public function getCurrencyFormat(): ?CurrencyFormat
{
return $this->has('currency_format') ? CurrencyFormat::from($this->input('currency_format')) : null;
}
public function getDateFormat(): ?DateFormat
{
return $this->has('date_format') ? DateFormat::from($this->input('date_format')) : null;
}
public function getIntervalFormat(): ?IntervalFormat
{
return $this->has('interval_format') ? IntervalFormat::from($this->input('interval_format')) : null;
}
public function getTimeFormat(): ?TimeFormat
{
return $this->has('time_format') ? TimeFormat::from($this->input('time_format')) : null;
}
public function getBillableRate(): ?int
{
$input = $this->input('billable_rate');
return $input !== null && $input !== 0 ? (int) $this->input('billable_rate') : null;
}
public function getEmployeesCanSeeBillableRates(): ?bool
{
return $this->has('employees_can_see_billable_rates') ? $this->boolean('employees_can_see_billable_rates') : null;
}
public function getEmployeesCanManageTasks(): ?bool
{
return $this->has('employees_can_manage_tasks') ? $this->boolean('employees_can_manage_tasks') : null;
}
public function getPreventOverlappingTimeEntries(): ?bool
{
return $this->has('prevent_overlapping_time_entries') ? $this->boolean('prevent_overlapping_time_entries') : null;
}
}
================================================
FILE: app/Http/Requests/V1/Project/ProjectIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
'archived' => [
'string',
'in:true,false,all',
],
];
}
public function getFilterArchived(): string
{
return $this->input('archived', 'false');
}
}
================================================
FILE: app/Http/Requests/V1/Project/ProjectStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
// Name of the project, the name needs to be unique per client and organization
'name' => [
'required',
'string',
'min:1',
'max:255',
UniqueEloquent::make(Project::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
$clientId = $this->input('client_id');
if (! is_string($clientId) || ! Str::isUuid($clientId)) {
$clientId = null;
}
return $builder->whereBelongsTo($this->organization, 'organization')
->where('client_id', $clientId);
})->withCustomTranslation('validation.project_name_already_exists'),
],
'color' => [
'required',
'string',
'max:255',
new ColorRule,
],
'is_billable' => [
'required',
'boolean',
],
'billable_rate' => array_merge(
[
'nullable',
],
$this->moneyRules()
),
// ID of the client
'client_id' => [
'present',
'nullable',
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Estimated time in seconds
'estimated_time' => [
'nullable',
'integer',
'min:0',
'max:2147483647',
],
// Whether the project is public
'is_public' => [
'boolean',
],
];
}
public function getIsPublic(): bool
{
return $this->has('is_public') && $this->boolean('is_public');
}
public function getBillableRate(): ?int
{
$input = $this->input('billable_rate');
return $input !== null && $input !== 0 ? (int) $this->input('billable_rate') : null;
}
public function getEstimatedTime(): ?int
{
$input = $this->input('estimated_time');
return $input !== null && $input !== 0 ? (int) $this->input('estimated_time') : null;
}
}
================================================
FILE: app/Http/Requests/V1/Project/ProjectUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'max:255',
UniqueEloquent::make(Project::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
$clientId = $this->input('client_id');
if (! is_string($clientId) || ! Str::isUuid($clientId)) {
$clientId = null;
}
return $builder->whereBelongsTo($this->organization, 'organization')
->where('client_id', $clientId);
})->ignore($this->project?->getKey())->withCustomTranslation('validation.project_name_already_exists'),
],
'color' => [
'required',
'string',
'max:255',
new ColorRule,
],
'is_billable' => [
'required',
'boolean',
],
'is_archived' => [
'boolean',
],
'is_public' => [
'boolean',
],
'client_id' => [
'present',
'nullable',
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
'billable_rate' => array_merge([
'nullable',
],
$this->moneyRules()
),
// Estimated time in seconds
'estimated_time' => [
'nullable',
'integer',
'min:0',
'max:2147483647',
],
];
}
public function getIsArchived(): bool
{
assert($this->has('is_archived'));
return (bool) $this->input('is_archived');
}
public function getBillableRate(): ?int
{
$input = $this->input('billable_rate');
return $input !== null && $input !== 0 ? (int) $this->input('billable_rate') : null;
}
public function getEstimatedTime(): ?int
{
$input = $this->input('estimated_time');
return $input !== null && $input !== 0 ? (int) $this->input('estimated_time') : null;
}
}
================================================
FILE: app/Http/Requests/V1/ProjectMember/ProjectMemberIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}
================================================
FILE: app/Http/Requests/V1/ProjectMember/ProjectMemberStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
'member_id' => [
'required',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
'billable_rate' => array_merge(
[
'nullable',
],
$this->moneyRules()
),
];
}
public function getBillableRate(): ?int
{
$input = $this->input('billable_rate');
return $input !== null && $input !== 0 ? (int) $this->input('billable_rate') : null;
}
}
================================================
FILE: app/Http/Requests/V1/ProjectMember/ProjectMemberUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
'billable_rate' => array_merge(
[
'nullable',
],
$this->moneyRules()
),
];
}
public function getBillableRate(): ?int
{
$input = $this->input('billable_rate');
return $input !== null && $input !== 0 ? (int) $this->input('billable_rate') : null;
}
}
================================================
FILE: app/Http/Requests/V1/Report/ReportIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Report/ReportStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'max:255',
],
'description' => [
'nullable',
'string',
],
'is_public' => [
'required',
'boolean',
],
// After this date the report will be automatically set to private (is_public=false) (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
'public_until' => [
'nullable',
'date_format:Y-m-d\TH:i:s\Z',
'after:now',
],
'properties' => [
'required',
'array',
],
'properties.start' => [
'required',
'date_format:Y-m-d\TH:i:s\Z',
],
'properties.end' => [
'required',
'date_format:Y-m-d\TH:i:s\Z',
],
'properties.active' => [
'nullable',
'boolean',
],
'properties.member_ids' => [
'nullable',
'array',
],
'properties.member_ids.*' => [
'string',
'uuid',
],
'properties.billable' => [
'nullable',
'boolean',
],
'properties.client_ids' => [
'nullable',
'array',
],
'properties.client_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
if (! Str::isUuid($value)) {
$fail('The '.$attribute.' must be a valid UUID.');
}
},
],
// Filter by project IDs, project IDs are OR combined
'properties.project_ids' => [
'nullable',
'array',
],
'properties.project_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
if (! Str::isUuid($value)) {
$fail('The '.$attribute.' must be a valid UUID.');
}
},
],
// Filter by tag IDs, tag IDs are OR combined
'properties.tag_ids' => [
'nullable',
'array',
],
'properties.tag_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
if (! Str::isUuid($value)) {
$fail('The '.$attribute.' must be a valid UUID.');
}
},
],
'properties.task_ids' => [
'nullable',
'array',
],
'properties.task_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
if (! Str::isUuid($value)) {
$fail('The '.$attribute.' must be a valid UUID.');
}
},
],
'properties.group' => [
'required',
Rule::enum(TimeEntryAggregationType::class),
],
'properties.sub_group' => [
'required',
Rule::enum(TimeEntryAggregationType::class),
],
'properties.history_group' => [
'required',
Rule::enum(TimeEntryAggregationTypeInterval::class),
],
'properties.week_start' => [
'nullable',
Rule::enum(Weekday::class),
],
'properties.timezone' => [
'nullable',
'timezone:all',
],
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
'properties.rounding_type' => [
'nullable',
'string',
Rule::enum(TimeEntryRoundingType::class),
],
// Defines the length of the interval that the time entry rounding rounds to.
'properties.rounding_minutes' => [
'nullable',
'numeric',
'integer',
],
];
}
public function getName(): string
{
return (string) $this->input('name');
}
public function getDescription(): ?string
{
return $this->input('description');
}
public function getIsPublic(): bool
{
return (bool) $this->input('is_public');
}
public function getPublicUntil(): ?Carbon
{
$publicUntil = $this->input('public_until');
return $publicUntil === null ? null : Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $publicUntil);
}
public function getPropertyStart(): Carbon
{
$start = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('properties.start'));
if ($start === null) {
throw new \LogicException('Start date validation is not working');
}
return $start;
}
public function getPropertyEnd(): Carbon
{
$end = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('properties.end'));
if ($end === null) {
throw new \LogicException('End date validation is not working');
}
return $end;
}
public function getPropertyActive(): ?bool
{
if ($this->has('properties.active') && $this->input('properties.active') !== null) {
return (bool) $this->input('properties.active');
}
return null;
}
public function getPropertyBillable(): ?bool
{
if ($this->has('properties.billable') && $this->input('properties.billable') !== null) {
return (bool) $this->input('properties.billable');
}
return null;
}
public function getPropertyGroup(): TimeEntryAggregationType
{
return TimeEntryAggregationType::from($this->input('properties.group'));
}
public function getPropertySubGroup(): TimeEntryAggregationType
{
return TimeEntryAggregationType::from($this->input('properties.sub_group'));
}
public function getPropertyHistoryGroup(): TimeEntryAggregationTypeInterval
{
return TimeEntryAggregationTypeInterval::from($this->input('properties.history_group'));
}
public function getPropertyRoundingType(): ?TimeEntryRoundingType
{
if (! $this->has('properties.rounding_type') || $this->input('properties.rounding_type') === null) {
return null;
}
return TimeEntryRoundingType::from($this->input('properties.rounding_type'));
}
public function getPropertyRoundingMinutes(): ?int
{
if (! $this->has('properties.rounding_minutes') || $this->input('properties.rounding_minutes') === null) {
return null;
}
return (int) $this->input('properties.rounding_minutes');
}
}
================================================
FILE: app/Http/Requests/V1/Report/ReportUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'string',
'max:255',
],
'description' => [
'nullable',
'string',
],
'is_public' => [
'boolean',
],
'public_until' => [
'nullable',
'date_format:Y-m-d\TH:i:s\Z',
'after:now',
],
];
}
public function getName(): string
{
return (string) $this->input('name');
}
public function getDescription(): ?string
{
return $this->input('description');
}
public function getIsPublic(): bool
{
return (bool) $this->input('is_public');
}
public function getPublicUntil(): ?Carbon
{
$publicUntil = $this->input('public_until');
return $publicUntil === null ? null : Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $publicUntil);
}
}
================================================
FILE: app/Http/Requests/V1/Tag/TagIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Tag/TagStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'min:1',
'max:255',
UniqueEloquent::make(Tag::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->withCustomTranslation('validation.tag_name_already_exists'),
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Tag/TagUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'min:1',
'max:255',
UniqueEloquent::make(Tag::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->ignore($this->tag?->getKey())->withCustomTranslation('validation.tag_name_already_exists'),
],
];
}
}
================================================
FILE: app/Http/Requests/V1/Task/TaskIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
'page' => [
'integer',
'min:1',
'max:2147483647',
],
'project_id' => [
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
$builder = $builder->whereBelongsTo($this->organization, 'organization');
if (! app(PermissionStore::class)->has($this->organization, 'tasks:view:all')) {
$builder = $builder->visibleByEmployee(Auth::user());
}
return $builder;
})->uuid(),
],
'done' => [
'string',
'in:true,false,all',
],
];
}
public function getFilterDone(): string
{
return $this->input('done', 'false');
}
}
================================================
FILE: app/Http/Requests/V1/Task/TaskStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'min:1',
'max:255',
UniqueEloquent::make(Task::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->where('project_id', '=', $this->input('project_id'));
})->withCustomTranslation('validation.task_name_already_exists'),
],
'project_id' => [
'required',
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Estimated time in seconds
'estimated_time' => [
'nullable',
'integer',
'min:0',
'max:2147483647',
],
];
}
public function getEstimatedTime(): ?int
{
$input = $this->input('estimated_time');
return $input !== null && $input !== 0 ? (int) $this->input('estimated_time') : null;
}
}
================================================
FILE: app/Http/Requests/V1/Task/TaskUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
'min:1',
'max:255',
UniqueEloquent::make(Task::class, 'name', function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->where('project_id', '=', $this->task->project_id);
})->ignore($this->task?->getKey())->withCustomTranslation('validation.task_name_already_exists'),
],
'is_done' => [
'boolean',
],
// Estimated time in seconds
'estimated_time' => [
'nullable',
'integer',
'min:0',
'max:2147483647',
],
];
}
public function getIsDone(): bool
{
assert($this->has('is_done'));
return $this->boolean('is_done');
}
public function getEstimatedTime(): ?int
{
$input = $this->input('estimated_time');
return $input !== null && $input !== 0 ? (int) $this->input('estimated_time') : null;
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryAggregateExportRequest.php
================================================
>
*/
public function rules(): array
{
return [
// Data format of the export
'format' => [
'required',
'string',
Rule::enum(ExportFormat::class),
],
// Type of first grouping
'group' => [
'required',
Rule::enum(TimeEntryAggregationType::class),
],
// Type of second grouping
'sub_group' => [
'required',
Rule::enum(TimeEntryAggregationType::class),
],
// Type of grouping of the historic aggregation (time chart)
'history_group' => [
'required',
'nullable',
Rule::enum(TimeEntryAggregationTypeInterval::class),
],
// Filter by member ID
'member_id' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Filter by multiple member IDs, member IDs are OR combined, but AND combined with the member_id parameter
'member_ids' => [
'array',
'min:1',
],
'member_ids.*' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Filter by user ID
'user_id' => [
'string',
ExistsEloquent::make(User::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->belongsToOrganization($this->organization);
})->uuid(),
],
// Filter by project IDs, project IDs are OR combined
'project_ids' => [
'array',
'min:1',
],
'project_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by client IDs, client IDs are OR combined
'client_ids' => [
'array',
'min:1',
],
'client_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by tag IDs, tag IDs are OR combined
'tag_ids' => [
'array',
'min:1',
],
'tag_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by task IDs, task IDs are OR combined
'task_ids' => [
'array',
'min:1',
],
'task_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'start' => [
'required',
'string',
'date_format:Y-m-d\TH:i:s\Z',
'before:end',
],
// Filter only time entries that have a start date before the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'end' => [
'required',
'string',
'date_format:Y-m-d\TH:i:s\Z',
],
// Filter by active status (active means has no end date, is still running)
'active' => [
'string',
'in:true,false',
],
// Filter by billable status
'billable' => [
'string',
'in:true,false',
],
'fill_gaps_in_time_groups' => [
'string',
'in:true,false',
],
'debug' => [
'string',
'in:true,false',
],
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
'rounding_type' => [
'nullable',
'string',
Rule::enum(TimeEntryRoundingType::class),
],
// Defines the length of the interval that the time entry rounding rounds to.
'rounding_minutes' => [
'nullable',
'numeric',
'integer',
],
];
}
public function getDebug(): bool
{
return $this->input('debug') === 'true';
}
public function getGroup(): TimeEntryAggregationType
{
return TimeEntryAggregationType::from($this->input('group'));
}
public function getSubGroup(): TimeEntryAggregationType
{
return TimeEntryAggregationType::from($this->input('sub_group'));
}
public function getHistoryGroup(): TimeEntryAggregationType
{
return TimeEntryAggregationType::fromInterval(TimeEntryAggregationTypeInterval::from($this->input('history_group')));
}
public function getStart(): Carbon
{
$start = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('start'), 'UTC');
if ($start === null) {
throw new \LogicException('Start date validation is not working');
}
return $start;
}
public function getEnd(): Carbon
{
$end = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('end'), 'UTC');
if ($end === null) {
throw new \LogicException('End date validation is not working');
}
return $end;
}
public function getFormatValue(): ExportFormat
{
return ExportFormat::from($this->validated('format'));
}
public function getRoundingType(): ?TimeEntryRoundingType
{
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
return null;
}
return TimeEntryRoundingType::from($this->validated('rounding_type'));
}
public function getRoundingMinutes(): ?int
{
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
return null;
}
return (int) $this->validated('rounding_minutes');
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryAggregateRequest.php
================================================
>
*/
public function rules(): array
{
return [
// Type of first grouping
'group' => [
'nullable',
'required_with:sub_group',
Rule::enum(TimeEntryAggregationType::class),
],
// Type of second grouping
'sub_group' => [
'nullable',
Rule::enum(TimeEntryAggregationType::class),
],
// Filter by member ID
'member_id' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Filter by multiple member IDs, member IDs are OR combined, but AND combined with the member_id parameter
'member_ids' => [
'array',
'min:1',
],
'member_ids.*' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Filter by user ID
'user_id' => [
'string',
ExistsEloquent::make(User::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->belongsToOrganization($this->organization);
})->uuid(),
],
// Filter by project IDs, project IDs are OR combined
'project_ids' => [
'array',
'min:1',
],
'project_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by client IDs, client IDs are OR combined
'client_ids' => [
'array',
'min:1',
],
'client_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by tag IDs, tag IDs are OR combined
'tag_ids' => [
'array',
'min:1',
],
'tag_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by task IDs, task IDs are OR combined
'task_ids' => [
'array',
'min:1',
],
'task_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'start' => [
'nullable',
'string',
'date_format:Y-m-d\TH:i:s\Z',
'before:end',
],
// Filter only time entries that have a start date before the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'end' => [
'nullable',
'string',
'date_format:Y-m-d\TH:i:s\Z',
],
// Filter by active status (active means has no end date, is still running)
'active' => [
'string',
'in:true,false',
],
// Filter by billable status
'billable' => [
'string',
'in:true,false',
],
'fill_gaps_in_time_groups' => [
'string',
'in:true,false',
],
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
'rounding_type' => [
'nullable',
'string',
Rule::enum(TimeEntryRoundingType::class),
],
// Defines the length of the interval that the time entry rounding rounds to.
'rounding_minutes' => [
'nullable',
'numeric',
'integer',
],
];
}
public function getGroup(): ?TimeEntryAggregationType
{
return $this->input('group') !== null ? TimeEntryAggregationType::from($this->input('group')) : null;
}
public function getSubGroup(): ?TimeEntryAggregationType
{
return $this->input('sub_group') !== null ? TimeEntryAggregationType::from($this->input('sub_group')) : null;
}
public function getFillGapsInTimeGroups(): bool
{
return $this->has('fill_gaps_in_time_groups') && $this->input('fill_gaps_in_time_groups') === 'true';
}
public function getStart(): ?Carbon
{
return $this->input('start') !== null ? Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('start'), 'UTC') : null;
}
public function getEnd(): ?Carbon
{
return $this->input('end') !== null ? Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('end'), 'UTC') : null;
}
public function getRoundingType(): ?TimeEntryRoundingType
{
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
return null;
}
return TimeEntryRoundingType::from($this->validated('rounding_type'));
}
public function getRoundingMinutes(): ?int
{
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
return null;
}
return (int) $this->validated('rounding_minutes');
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryDestroyMultipleRequest.php
================================================
>
*/
public function rules(): array
{
return [
'ids' => [
'required',
'array',
],
'ids.*' => [
'string',
'uuid',
],
];
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryIndexExportRequest.php
================================================
>
*/
public function rules(): array
{
return [
'format' => [
'required',
'string',
Rule::enum(ExportFormat::class),
],
// Filter by member ID
'member_id' => [
'string',
'uuid',
new ExistsEloquent(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
// Filter by multiple member IDs, member IDs are OR combined, but AND combined with the member_id parameter
'member_ids' => [
'array',
'min:1',
],
'member_ids.*' => [
'string',
'uuid',
new ExistsEloquent(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
}),
],
// Filter by client IDs, client IDs are OR combined
'client_ids' => [
'array',
'min:1',
],
'client_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by project IDs, project IDs are OR combined
'project_ids' => [
'array',
'min:1',
],
'project_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by tag IDs, tag IDs are OR combined
'tag_ids' => [
'array',
'min:1',
],
'tag_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by task IDs, task IDs are OR combined
'task_ids' => [
'array',
'min:1',
],
'task_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'start' => [
'required',
'string',
'date_format:Y-m-d\TH:i:s\Z',
'before:end',
],
// Filter only time entries that have a start date before the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'end' => [
'required',
'string',
'date_format:Y-m-d\TH:i:s\Z',
],
// Filter by active status (active means has no end date, is still running)
'active' => [
'string',
'in:true,false',
],
// Filter by billable status
'billable' => [
'string',
'in:true,false',
],
// Limit the number of returned time entries (default: 150)
'limit' => [
'integer',
'min:1',
'max:500',
],
// Filter makes sure that only time entries of a whole date are returned
'only_full_dates' => [
'string',
'in:true,false',
],
'debug' => [
'string',
'in:true,false',
],
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
'rounding_type' => [
'nullable',
'string',
Rule::enum(TimeEntryRoundingType::class),
],
// Defines the length of the interval that the time entry rounding rounds to.
'rounding_minutes' => [
'nullable',
'numeric',
'integer',
],
];
}
public function getDebug(): bool
{
return $this->input('debug', 'false') === 'true';
}
public function getStart(): Carbon
{
$start = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('start'), 'UTC');
if ($start === null) {
throw new \LogicException('Start date validation is not working');
}
return $start;
}
public function getEnd(): Carbon
{
$end = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $this->input('end'), 'UTC');
if ($end === null) {
throw new \LogicException('End date validation is not working');
}
return $end;
}
public function getOnlyFullDates(): bool
{
return $this->input('only_full_dates', 'false') === 'true';
}
public function getFormatValue(): ExportFormat
{
return ExportFormat::from($this->validated('format'));
}
public function getRoundingType(): ?TimeEntryRoundingType
{
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
return null;
}
return TimeEntryRoundingType::from($this->validated('rounding_type'));
}
public function getRoundingMinutes(): ?int
{
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
return null;
}
return (int) $this->validated('rounding_minutes');
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryIndexRequest.php
================================================
>
*/
public function rules(): array
{
return [
// Filter by member ID
'member_id' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Filter by multiple member IDs, member IDs are OR combined, but AND combined with the member_id parameter
'member_ids' => [
'array',
'min:1',
],
'member_ids.*' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// Filter by client IDs, client IDs are OR combined
'client_ids' => [
'array',
'min:1',
],
'client_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Client::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by project IDs, project IDs are OR combined
'project_ids' => [
'array',
'min:1',
],
'project_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by tag IDs, tag IDs are OR combined
'tag_ids' => [
'array',
'min:1',
],
'tag_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter by task IDs, task IDs are OR combined
'task_ids' => [
'array',
'min:1',
],
'task_ids.*' => [
'string',
function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === TimeEntryFilter::NONE_VALUE) {
return;
}
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid()->validate($attribute, $value, $fail);
},
],
// Filter only time entries that have a start date after the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'start' => [
'nullable',
'string',
'date_format:Y-m-d\TH:i:s\Z',
'before:end',
],
// Filter only time entries that have a start date before the given timestamp in UTC (example: 2021-01-01T00:00:00Z)
'end' => [
'nullable',
'string',
'date_format:Y-m-d\TH:i:s\Z',
],
// Filter by active status (active means has no end date, is still running)
'active' => [
'string',
'in:true,false',
],
// Filter by billable status
'billable' => [
'string',
'in:true,false',
],
// Limit the number of returned time entries (default: 150)
'limit' => [
'integer',
'min:1',
'max:500',
],
// Skip the first n time entries (default: 0)
'offset' => [
'integer',
'min:0',
'max:2147483647',
],
// Filter makes sure that only time entries of a whole date are returned
'only_full_dates' => [
'string',
'in:true,false',
],
// Rounding type defined where the end of each time entry should be rounded to. For example: nearest rounds the end to the nearest x minutes group. Rounding per time entry is activated if `rounding_type` and `rounding_minutes` is not null.
'rounding_type' => [
'nullable',
'string',
Rule::enum(TimeEntryRoundingType::class),
],
// Defines the length of the interval that the time entry rounding rounds to.
'rounding_minutes' => [
'nullable',
'numeric',
'integer',
],
];
}
public function getOnlyFullDates(): bool
{
return $this->input('only_full_dates', 'false') === 'true';
}
public function getLimit(): int
{
return $this->has('limit') ? (int) $this->validated('limit', 100) : 100;
}
public function getOffset(): int
{
return $this->has('offset') ? (int) $this->validated('offset', 0) : 0;
}
public function getRoundingType(): ?TimeEntryRoundingType
{
if (! $this->has('rounding_type') || $this->validated('rounding_type') === null) {
return null;
}
return TimeEntryRoundingType::from($this->validated('rounding_type'));
}
public function getRoundingMinutes(): ?int
{
if (! $this->has('rounding_minutes') || $this->validated('rounding_minutes') === null) {
return null;
}
return (int) $this->validated('rounding_minutes');
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryStoreRequest.php
================================================
>
*/
public function rules(): array
{
return [
// ID of the organization member that the time entry should belong to
'member_id' => [
'required',
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
'project_id' => [
'nullable',
'string',
'required_with:task_id',
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
$builder = $builder->whereBelongsTo($this->organization, 'organization');
// If user doesn't have 'all' permission for time entries or projects, only allow access to public projects or projects they're a member of
$permissionStore = app(PermissionStore::class);
if (! $permissionStore->has($this->organization, 'time-entries:create:all')
&& ! $permissionStore->has($this->organization, 'projects:view:all')) {
$builder = $builder->visibleByEmployee(Auth::user());
}
return $builder;
})->uuid(),
],
// ID of the task that the time entry should belong to
'task_id' => [
'nullable',
'string',
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization')
->where('project_id', $this->input('project_id'));
})->uuid()->withMessage(__('validation.task_belongs_to_project')),
],
// Start of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
'start' => [
'required',
'date_format:Y-m-d\TH:i:s\Z',
],
// End of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
'end' => [
'nullable',
'date_format:Y-m-d\TH:i:s\Z',
'after_or_equal:start',
],
// Whether time entry is billable
'billable' => [
'required',
'boolean',
],
// Description of time entry
'description' => [
'nullable',
'string',
'max:5000',
],
// List of tag IDs
'tags' => [
'nullable',
'array',
],
'tags.*' => [
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
];
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryUpdateMultipleRequest.php
================================================
>
*/
public function rules(): array
{
return [
'ids' => [
'required',
'array',
],
'ids.*' => [
'string',
'uuid',
],
'changes' => [
'required',
'array',
],
// ID of the organization member that the time entry should belong to
'changes.member_id' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// ID of the project that the time entry should belong to
'changes.project_id' => [
'nullable',
'string',
'required_with:task_id',
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
$builder = $builder->whereBelongsTo($this->organization, 'organization');
// If user doesn't have 'all' permission for time entries or projects, only allow access to public projects or projects they're a member of
$permissionStore = app(PermissionStore::class);
if (! $permissionStore->has($this->organization, 'time-entries:update:all')
&& ! $permissionStore->has($this->organization, 'projects:view:all')) {
$builder = $builder->visibleByEmployee(Auth::user());
}
return $builder;
})->uuid(),
],
// ID of the task that the time entry should belong to
'changes.task_id' => [
'nullable',
'string',
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization')
->where('project_id', $this->input('changes.project_id'));
})->uuid()->withMessage(__('validation.task_belongs_to_project')),
],
// Whether time entry is billable
'changes.billable' => [
'boolean',
],
// Description of time entry
'changes.description' => [
'nullable',
'string',
'max:5000',
],
// List of tag IDs
'changes.tags' => [
'nullable',
'array',
],
'changes.tags.*' => [
'string',
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
];
}
}
================================================
FILE: app/Http/Requests/V1/TimeEntry/TimeEntryUpdateRequest.php
================================================
>
*/
public function rules(): array
{
return [
// ID of the organization member that the time entry should belong to
'member_id' => [
'string',
ExistsEloquent::make(Member::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
// ID of the project that the time entry should belong to
'project_id' => [
'nullable',
'string',
'required_with:task_id',
ExistsEloquent::make(Project::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
$builder = $builder->whereBelongsTo($this->organization, 'organization');
// If user doesn't have 'all' permission for time entries or projects, only allow access to public projects or projects they're a member of
$permissionStore = app(PermissionStore::class);
if (! $permissionStore->has($this->organization, 'time-entries:update:all')
&& ! $permissionStore->has($this->organization, 'projects:view:all')) {
$builder = $builder->visibleByEmployee(Auth::user());
}
return $builder;
})->uuid(),
],
// ID of the task that the time entry should belong to
'task_id' => [
'nullable',
'string',
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
ExistsEloquent::make(Task::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization')
->where('project_id', $this->input('project_id'));
})->uuid()->withMessage(__('validation.task_belongs_to_project')),
],
// Start of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
'start' => [
'date_format:Y-m-d\TH:i:s\Z',
],
// End of time entry (Format: "Y-m-d\TH:i:s\Z", UTC timezone, Example: "2000-02-22T14:58:59Z")
'end' => [
'nullable',
'date_format:Y-m-d\TH:i:s\Z',
'after_or_equal:start',
],
// Whether time entry is billable
'billable' => [
'boolean',
],
// Description of time entry
'description' => [
'nullable',
'string',
'max:5000',
],
// List of tag IDs
'tags' => [
'nullable',
'array',
],
'tags.*' => [
'string',
ExistsEloquent::make(Tag::class, null, function (Builder $builder): Builder {
/** @var Builder $builder */
return $builder->whereBelongsTo($this->organization, 'organization');
})->uuid(),
],
];
}
}
================================================
FILE: app/Http/Resources/PaginatedResourceCollection.php
================================================
>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of the API token, this ID is NOT a UUID */
'id' => $this->resource->id,
/** @var string $name Name of the API token */
'name' => $this->resource->name,
/** @var bool $revoked Whether the API token is revoked */
'revoked' => $this->resource->revoked,
/** @var array $scopes List of scopes that the API token has */
'scopes' => $this->resource->scopes,
/** @var string $created_at When the API token was created (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string|null $expires_at At what time the API token expires (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
'expires_at' => $this->formatDateTime($this->resource->expires_at),
];
}
}
================================================
FILE: app/Http/Resources/V1/ApiToken/ApiTokenWithAccessTokenResource.php
================================================
accessToken = $accessToken;
parent::__construct($resource);
}
/**
* Transform the resource into an array.
*
* @return array>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of the API token, this ID is NOT a UUID */
'id' => $this->resource->id,
/** @var string $name Name of the API token */
'name' => $this->resource->name,
/** @var bool $revoked Whether the API token is revoked */
'revoked' => $this->resource->revoked,
/** @var array $scopes List of scopes that the API token has */
'scopes' => $this->resource->scopes,
/** @var string $created_at When the API token was created (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string|null $expires_at At what time the API token expires (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z) */
'expires_at' => $this->formatDateTime($this->resource->expires_at),
// Additional fields
/** @var string $access_token Access token that can be used to authenticate requests */
'access_token' => $this->accessToken,
];
}
}
================================================
FILE: app/Http/Resources/V1/BaseResource.php
================================================
toIso8601ZuluString();
}
protected function formatDate(?Carbon $carbon): ?string
{
return $carbon?->format('Y-m-d');
}
}
================================================
FILE: app/Http/Resources/V1/Client/ClientCollection.php
================================================
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID */
'id' => $this->resource->id,
/** @var string $name Name */
'name' => $this->resource->name,
/** @var bool $is_archived Whether the client is archived */
'is_archived' => $this->resource->is_archived,
/** @var string $created_at When the tag was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string $updated_at When the tag was last updated */
'updated_at' => $this->formatDateTime($this->resource->updated_at),
];
}
}
================================================
FILE: app/Http/Resources/V1/Invitation/InvitationCollection.php
================================================
>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of the invitation */
'id' => $this->resource->id,
/** @var string $email Email */
'email' => $this->resource->email,
/** @var string $role Role */
'role' => $this->resource->role,
];
}
}
================================================
FILE: app/Http/Resources/V1/Member/MemberCollection.php
================================================
>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of membership */
'id' => $this->resource->id,
/** @var string $id ID of user */
'user_id' => $this->resource->user->id,
/** @var string $name Name */
'name' => $this->resource->user->name,
/** @var string $email Email */
'email' => $this->resource->user->email,
/** @var string $role Role */
'role' => $this->resource->role,
/** @var bool $is_placeholder Placeholder user for imports, user might not really exist and does not know about this placeholder membership */
'is_placeholder' => $this->resource->user->is_placeholder,
/** @var int|null $billable_rate Billable rate in cents per hour */
'billable_rate' => $this->resource->billable_rate,
];
}
}
================================================
FILE: app/Http/Resources/V1/Member/PersonalMembershipCollection.php
================================================
>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of membership */
'id' => $this->resource->id,
'organization' => [
/** @var string $id ID of organization */
'id' => $this->resource->organization->id,
/** @var string $name Name of organization */
'name' => $this->resource->organization->name,
/** @var string $currency Currency code (ISO 4217) of organization */
'currency' => $this->resource->organization->currency,
],
/** @var string $role Role */
'role' => $this->resource->role,
];
}
}
================================================
FILE: app/Http/Resources/V1/Organization/OrganizationResource.php
================================================
showBillableRate = $showBillableRate;
}
/**
* Transform the resource into an array.
*
* @return array
*/
public function toArray(Request $request): array
{
$currencyService = app(CurrencyService::class);
return [
/** @var string $id ID */
'id' => $this->resource->id,
/** @var string $name Name */
'name' => $this->resource->name,
/** @var bool $color Personal organizations automatically created after registration */
'is_personal' => $this->resource->personal_team,
/** @var int|null $billable_rate Billable rate in cents per hour */
'billable_rate' => $this->showBillableRate ? $this->resource->billable_rate : null,
/** @var bool $employees_can_see_billable_rates Can members of the organization with role "employee" see the billable rates */
'employees_can_see_billable_rates' => $this->resource->employees_can_see_billable_rates,
/** @var bool $employees_can_manage_tasks Can members of the organization with role "employee" manage tasks in public projects and projects they are assigned to */
'employees_can_manage_tasks' => $this->resource->employees_can_manage_tasks,
/** @var bool $prevent_overlapping_time_entries Prevent creating overlapping time entries (only new entries) */
'prevent_overlapping_time_entries' => $this->resource->prevent_overlapping_time_entries,
/** @var string $currency Currency code (ISO 4217) */
'currency' => $this->resource->currency,
/** @var string $currency_symbol Currency symbol */
'currency_symbol' => $currencyService->getCurrencySymbol($this->resource->currency),
/** @var NumberFormat $number_format Number format */
'number_format' => $this->resource->number_format->value,
/** @var CurrencyFormat $currency_format Currency format */
'currency_format' => $this->resource->currency_format->value,
/** @var DateFormat $date_format Date format */
'date_format' => $this->resource->date_format->value,
/** @var IntervalFormat $interval_format Interval format */
'interval_format' => $this->resource->interval_format->value,
/** @var TimeFormat $time_format Time format */
'time_format' => $this->resource->time_format->value,
];
}
}
================================================
FILE: app/Http/Resources/V1/Project/ProjectCollection.php
================================================
showBillableRates = $showBillableRates;
}
protected function collects(): ?string
{
return null;
}
/**
* Transform the resource collection into an array.
*
* @return array>
*/
public function toArray(Request $request): array
{
return $this->collection->map(function (Project $project) use ($request): array {
return (new ProjectResource($project, $this->showBillableRates))
->toArray($request);
})->all();
}
}
================================================
FILE: app/Http/Resources/V1/Project/ProjectResource.php
================================================
showBillableRate = $showBillableRate;
}
/**
* Transform the resource into an array.
*
* @return array
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of project */
'id' => $this->resource->id,
/** @var string $name Name of project */
'name' => $this->resource->name,
/** @var string $color Color of project */
'color' => $this->resource->color,
/** @var string|null $client_id ID of client */
'client_id' => $this->resource->client_id,
/** @var bool $is_archived Whether the client is archived */
'is_archived' => $this->resource->is_archived,
/** @var int|null $billable_rate Billable rate in cents per hour */
'billable_rate' => $this->showBillableRate ? $this->resource->billable_rate : null,
/** @var bool $is_billable Project time entries billable default */
'is_billable' => $this->resource->is_billable,
/** @var int|null $estimated_time Estimated time in seconds */
'estimated_time' => $this->resource->estimated_time,
/** @var int $spent_time Spent time on this project in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
'spent_time' => $this->resource->spent_time,
/** @var bool $is_public Whether the project is public */
'is_public' => $this->resource->is_public,
];
}
}
================================================
FILE: app/Http/Resources/V1/ProjectMember/ProjectMemberCollection.php
================================================
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of project member */
'id' => $this->resource->id,
/** @var int|null $billable_rate Billable rate in cents per hour */
'billable_rate' => $this->resource->billable_rate,
/** @var string $member_id ID of the organization member */
'member_id' => $this->resource->member_id,
/** @var string $project_id ID of the project */
'project_id' => $this->resource->project_id,
];
}
}
================================================
FILE: app/Http/Resources/V1/Report/DetailedReportResource.php
================================================
>>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of the report */
'id' => $this->resource->id,
/** @var string $name Name */
'name' => $this->resource->name,
/** @var string|null $email Description */
'description' => $this->resource->description,
/** @var bool $is_public Whether the report can be accessed via an external link */
'is_public' => $this->resource->is_public,
/** @var string|null $public_until Date until the report is public */
'public_until' => $this->formatDateTime($this->resource->public_until),
/** @var string|null $shareable_link Get link to access the report externally, not set if the report is private */
'shareable_link' => $this->resource->getShareableLink(),
'properties' => [
/** @var string $group Type of first grouping */
'group' => $this->resource->properties->group->value,
/** @var string $sub_group Type of second grouping */
'sub_group' => $this->resource->properties->subGroup->value,
/** @var string $history_group Type of grouping of the historic aggregation (time chart) */
'history_group' => $this->resource->properties->historyGroup->value,
/** @var string $start Start date of the report */
'start' => $this->formatDateTime($this->resource->properties->start),
/** @var string $end End date of the report */
'end' => $this->formatDateTime($this->resource->properties->end),
/** @var bool|null $active Whether the report is active */
'active' => $this->resource->properties->active,
/** @var array|null $member_ids Filter by multiple member IDs, member IDs are OR combined */
'member_ids' => $this->resource->properties->memberIds?->toArray(),
/** @var bool|null $billable Filter by billable status */
'billable' => $this->resource->properties->billable,
/** @var array|null $client_ids Filter by client IDs, client IDs are OR combined */
'client_ids' => $this->resource->properties->clientIds?->toArray(),
/** @var array|null $project_ids Filter by project IDs, project IDs are OR combined */
'project_ids' => $this->resource->properties->projectIds?->toArray(),
/** @var array|null $tags_ids Filter by tag IDs, tag IDs are OR combined */
'tag_ids' => $this->resource->properties->tagIds?->toArray(),
/** @var array|null $task_ids Filter by task IDs, task IDs are OR combined */
'task_ids' => $this->resource->properties->taskIds?->toArray(),
/** @var string|null $rounding_type Rounding type for time entries */
'rounding_type' => $this->resource->properties->roundingType?->value,
/** @var int|null $rounding_minutes Rounding minutes for time entries */
'rounding_minutes' => $this->resource->properties->roundingMinutes,
],
/** @var string $created_at Date when the report was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string $updated_at Date when the report was last updated */
'updated_at' => $this->formatDateTime($this->resource->updated_at),
];
}
}
================================================
FILE: app/Http/Resources/V1/Report/DetailedWithDataReportResource.php
================================================
* }>,
* seconds: int,
* cost: int|null
* }
*/
class DetailedWithDataReportResource extends BaseResource
{
/**
* @var Data
*/
private array $data;
/**
* @var Data
*/
private array $historyData;
/**
* @param Data $data
* @param Data $historyData
*/
public function __construct(Report $resource, array $data, array $historyData)
{
parent::__construct($resource);
$this->data = $data;
$this->historyData = $historyData;
}
/**
* Transform the resource into an array.
*
* @return array>>
*/
public function toArray(Request $request): array
{
$currencyService = app(CurrencyService::class);
return [
/** @var string $name Name */
'name' => $this->resource->name,
/** @var string|null $email Description */
'description' => $this->resource->description,
/** @var string|null $public_until Date until the report is public */
'public_until' => $this->formatDateTime($this->resource->public_until),
/** @var string $currency Currency code (ISO 4217) */
'currency' => $this->resource->organization->currency,
/** @var NumberFormat $number_format Number format */
'number_format' => $this->resource->organization->number_format->value,
/** @var CurrencyFormat $currency_format Currency format */
'currency_format' => $this->resource->organization->currency_format->value,
/** @var string $currency_symbol Currency symbol */
'currency_symbol' => $currencyService->getCurrencySymbol($this->resource->organization->currency),
/** @var DateFormat $date_format Date format */
'date_format' => $this->resource->organization->date_format->value,
/** @var IntervalFormat $interval_format Interval format */
'interval_format' => $this->resource->organization->interval_format->value,
/** @var TimeFormat $time_format Time format */
'time_format' => $this->resource->organization->time_format->value,
'properties' => [
/** @var string $group Type of first grouping */
'group' => $this->resource->properties->group->value,
/** @var string $sub_group Type of second grouping */
'sub_group' => $this->resource->properties->subGroup->value,
/** @var string $history_group Type of grouping of the historic aggregation (time chart) */
'history_group' => $this->resource->properties->historyGroup->value,
/** @var string $start Start date of the report */
'start' => $this->formatDateTime($this->resource->properties->start),
/** @var string $end End date of the report */
'end' => $this->formatDateTime($this->resource->properties->end),
],
/** @var array{
* grouped_type: string|null,
* grouped_data: null|array
* }>,
* seconds: int,
* cost: int
* } $data Aggregated data
*/
'data' => $this->data,
/** @var array{
* grouped_type: string|null,
* grouped_data: null|array
* }>,
* seconds: int,
* cost: int
* } $history_data Historic aggregated data
*/
'history_data' => $this->historyData,
];
}
}
================================================
FILE: app/Http/Resources/V1/Report/ReportCollection.php
================================================
>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of the report */
'id' => $this->resource->id,
/** @var string $name Name */
'name' => $this->resource->name,
/** @var string|null $email Description */
'description' => $this->resource->description,
/** @var bool $is_public Whether the report can be accessed via an external link */
'is_public' => $this->resource->is_public,
/** @var string|null $public_until Date until the report is public */
'public_until' => $this->formatDateTime($this->resource->public_until),
/** @var string|null $shareable_link Get link to access the report externally, not set if the report is private */
'shareable_link' => $this->resource->getShareableLink(),
/** @var string $created_at Date when the report was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string $updated_at Date when the report was last updated */
'updated_at' => $this->formatDateTime($this->resource->updated_at),
];
}
}
================================================
FILE: app/Http/Resources/V1/Tag/TagCollection.php
================================================
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID */
'id' => $this->resource->id,
/** @var string $name Name */
'name' => $this->resource->name,
/** @var string $created_at When the tag was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string $updated_at When the tag was last updated */
'updated_at' => $this->formatDateTime($this->resource->updated_at),
];
}
}
================================================
FILE: app/Http/Resources/V1/Task/TaskCollection.php
================================================
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID */
'id' => $this->resource->id,
/** @var string $name Name */
'name' => $this->resource->name,
/** @var bool $is_done Whether the task is done */
'is_done' => $this->resource->is_done,
/** @var string $project_id ID of the project */
'project_id' => $this->resource->project_id,
/** @var int|null $estimated_time Estimated time in seconds */
'estimated_time' => $this->resource->estimated_time,
/** @var int $spent_time Spent time on this task in seconds (sum of the duration of all associated time entries, excl. still running time entries) */
'spent_time' => $this->resource->spent_time,
/** @var string $created_at When the tag was created */
'created_at' => $this->formatDateTime($this->resource->created_at),
/** @var string $updated_at When the tag was last updated */
'updated_at' => $this->formatDateTime($this->resource->updated_at),
];
}
}
================================================
FILE: app/Http/Resources/V1/TimeEntry/TimeEntryCollection.php
================================================
>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of time entry */
'id' => $this->resource->id,
/**
* @var string $start Start of time entry (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z)
*/
'start' => $this->formatDateTime($this->resource->start),
/**
* @var string|null $end End of time entry (ISO 8601 format, UTC timezone, example: 2024-02-26T17:17:17Z)
*/
'end' => $this->formatDateTime($this->resource->end),
/** @var int|null $duration Duration of time entry in seconds */
'duration' => (int) $this->resource->getDuration()?->totalSeconds,
/** @var string|null $description Description of time entry */
'description' => $this->resource->description,
/** @var string|null $task_id ID of task */
'task_id' => $this->resource->task_id,
/** @var string|null $project_id ID of project */
'project_id' => $this->resource->project_id,
/** @var string $organization_id ID of organization */
'organization_id' => $this->resource->organization_id,
/** @var string $user_id ID of user */
'user_id' => $this->resource->user_id,
/** @var array $tags List of tag IDs */
'tags' => $this->resource->tags ?? [],
/** @var bool $billable Whether time entry is billable */
'billable' => $this->resource->billable,
];
}
}
================================================
FILE: app/Http/Resources/V1/User/UserResource.php
================================================
>
*/
public function toArray(Request $request): array
{
return [
/** @var string $id ID of user */
'id' => $this->resource->id,
/** @var string $name Name of user */
'name' => $this->resource->name,
/** @var string $email Email of user */
'email' => $this->resource->email,
/** @var string $profile_photo_url Profile photo URL */
'profile_photo_url' => $this->resource->profile_photo_url,
/** @var string $timezone Timezone (f.e. Europe/Berlin or America/New_York) */
'timezone' => $this->resource->timezone,
/** @var Weekday $week_start Starting day of the week */
'week_start' => $this->resource->week_start->value,
];
}
}
================================================
FILE: app/Jobs/RecalculateSpentTimeForProject.php
================================================
project = $project;
}
/**
* Execute the job.
*
* @throws Exception
*/
public function handle(): void
{
$this->project->setComputedAttributeValue('spent_time');
if ($this->project->isDirty()) {
$this->project->save();
}
}
}
================================================
FILE: app/Jobs/RecalculateSpentTimeForTask.php
================================================
task = $task;
}
/**
* Execute the job.
*
* @throws Exception
*/
public function handle(): void
{
$this->task->setComputedAttributeValue('spent_time');
if ($this->task->isDirty()) {
$this->task->save();
}
}
}
================================================
FILE: app/Jobs/Test/TestJob.php
================================================
user = $user;
$this->message = $message;
$this->fail = $fail;
}
/**
* Execute the job.
*
* @throws Exception
*/
public function handle(): void
{
Log::debug('TestJob: '.$this->message, [
'user' => $this->user->getKey(),
]);
if ($this->fail) {
throw new Exception('TestJob failed.');
}
}
}
================================================
FILE: app/Listeners/RemovePlaceholder.php
================================================
whereBelongsTo($event->team, 'organization')
->whereBelongsTo($event->user, 'user')
->firstOrFail();
$placeholders = Member::query()
->whereHas('user', function (Builder $query) use ($event): void {
/** @var Builder $query */
$query->where('is_placeholder', '=', true)
->where('email', '=', $event->user->email);
})
->whereBelongsTo($event->team, 'organization')
->with(['user'])
->get();
foreach ($placeholders as $placeholder) {
/** @var Member $placeholder */
$placeholderUser = $placeholder->user;
$memberService->assignOrganizationEntitiesToDifferentMember($event->team, $placeholder, $member);
$placeholder->delete();
$placeholderUser->delete();
}
}
}
================================================
FILE: app/Mail/AuthApiTokenExpirationReminderMail.php
================================================
token = $token;
$this->user = $user;
}
/**
* Build the message.
*/
public function build(): self
{
return $this->markdown('emails.auth-api-expiration-reminder', [
'profileUrl' => URL::to('user/profile'),
'tokenName' => $this->token->name,
])
->subject(__('Your API token will expire in 7 days!'));
}
}
================================================
FILE: app/Mail/AuthApiTokenExpiredMail.php
================================================
token = $token;
$this->user = $user;
}
/**
* Build the message.
*/
public function build(): self
{
return $this->markdown('emails.auth-api-token-expired', [
'profileUrl' => URL::to('user/profile'),
'tokenName' => $this->token->name,
])
->subject(__('Your API token has expired!'));
}
}
================================================
FILE: app/Mail/OrganizationInvitationMail.php
================================================
invitation = $invitation;
}
/**
* Build the message.
*/
public function build(): self
{
return $this->markdown('emails.organization-invitation', [
'acceptUrl' => URL::signedRoute('team-invitations.accept', [
'invitation' => $this->invitation,
]),
])->subject(__('Organization Invitation'));
}
}
================================================
FILE: app/Mail/TimeEntryStillRunningMail.php
================================================
timeEntry = $timeEntry;
$this->user = $user;
}
/**
* Build the message.
*/
public function build(): self
{
return $this->markdown('emails.time-entry-still-running', [
'dashboardUrl' => URL::route('dashboard'),
])
->subject(__('Your Time Tracker is still running!'));
}
}
================================================
FILE: app/Models/Audit.php
================================================
|null $old_values
* @property array|null $new_values
* @property string|null $url
* @property string|null $ip_address
* @property string|null $user_agent
* @property string|null $tags
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*
* @method static AuditFactory factory()
*/
class Audit extends PackageAuditModel
{
/** @use HasFactory */
use HasFactory;
}
================================================
FILE: app/Models/Client.php
================================================
*/
use HasFactory;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'name' => 'string',
'archived_at' => 'datetime',
];
/**
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* @return HasMany
*/
public function projects(): HasMany
{
return $this->hasMany(Project::class, 'client_id');
}
/**
* @param Builder $builder
* @return Builder
*/
public function scopeVisibleByEmployee(Builder $builder, User $user): Builder
{
return $builder->whereHas('projects', function (Builder $builder) use ($user): Builder {
/** @var Builder $builder */
return $builder->visibleByEmployee($user);
});
}
/**
* @return Attribute
*/
protected function isArchived(): Attribute
{
return Attribute::make(
get: fn (mixed $value, array $attributes) => isset($attributes['archived_at']),
);
}
}
================================================
FILE: app/Models/Concerns/CustomAuditable.php
================================================
|null
*/
protected ?array $auditEvents = null;
public function disableAuditing(): void
{
$this->auditEvents = [];
}
}
================================================
FILE: app/Models/Concerns/HasUuids.php
================================================
*/
use HasFactory;
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'failed_at' => 'datetime',
'payload' => 'json',
];
}
================================================
FILE: app/Models/Member.php
================================================
$projectMembers
* @property-read Collection $timeEntries
*
* @method static MemberFactory factory()
*/
class Member extends JetstreamMembership implements AuditableContract
{
use CustomAuditable;
/** @use HasFactory */
use HasFactory;
use HasUuids;
/**
* The table associated with the pivot model.
*
* @var string
*/
protected $table = 'members';
/**
* @return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* @return HasMany
*/
public function timeEntries(): HasMany
{
return $this->hasMany(TimeEntry::class, 'member_id');
}
/**
* @return HasMany
*/
public function projectMembers(): HasMany
{
return $this->hasMany(ProjectMember::class, 'member_id');
}
}
================================================
FILE: app/Models/Organization.php
================================================
$users
* @property Collection $realUsers
* @property-read Collection $teamInvitations
* @property Member $membership
* @property NumberFormat $number_format
* @property CurrencyFormat $currency_format
* @property DateFormat $date_format
* @property IntervalFormat $interval_format
* @property TimeFormat $time_format
*
* @method HasMany teamInvitations()
* @method static OrganizationFactory factory()
*/
class Organization extends JetstreamTeam implements AuditableContract
{
use CustomAuditable;
/** @use HasFactory */
use HasFactory;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'name' => 'string',
'personal_team' => 'boolean',
'currency' => 'string',
'employees_can_see_billable_rates' => 'boolean',
'employees_can_manage_tasks' => 'boolean',
'prevent_overlapping_time_entries' => 'boolean',
'number_format' => NumberFormat::class,
'currency_format' => CurrencyFormat::class,
'date_format' => DateFormat::class,
'interval_format' => IntervalFormat::class,
'time_format' => TimeFormat::class,
];
/**
* The attributes that are mass assignable.
*
* @var list
*/
protected $fillable = [
'name',
'personal_team',
];
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'created' => TeamCreated::class,
'updated' => TeamUpdated::class,
'deleted' => TeamDeleted::class,
];
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
];
/**
* Get all the non-placeholder users of the organization including its owner.
*
* @return Collection
*/
public function allRealUsers(): Collection
{
return $this->realUsers->merge([$this->owner]);
}
public function hasRealUserWithEmail(string $email): bool
{
return $this->allRealUsers()->contains(function (User $user) use ($email): bool {
return $user->email === $email;
});
}
/**
* Get all the users that belong to the team.
*
* @return BelongsToMany
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class, Member::class)
->withPivot([
'id',
'role',
'billable_rate',
])
->withTimestamps()
->as('membership');
}
/**
* Get the owner of the team.
*
* @return BelongsTo
*/
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* @return HasMany
*/
public function members(): HasMany
{
return $this->hasMany(Member::class);
}
/**
* @return BelongsToMany
*/
public function realUsers(): BelongsToMany
{
return $this->users()
->where('is_placeholder', false);
}
/**
* This method prevents an unhandled exception when the ID is not a UUID.
* Normally this can be fixed with a route pattern, but Jetstream does not use route model binding.
*
* @param array $columns
*/
public function findOrFail(string $id, array $columns = ['*']): \Laravel\Jetstream\Team
{
if (! Str::isUuid($id)) {
throw (new ModelNotFoundException)->setModel(
self::class, $id
);
}
return parent::findOrFail($id, $columns);
}
}
================================================
FILE: app/Models/OrganizationInvitation.php
================================================
*/
use HasFactory;
use HasUuids;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'organization_invitations';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'email',
'role',
];
/**
* Get the organization that the invitation belongs to.
*
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* Get the organization that the invitation belongs to.
*
* @return BelongsTo
*/
public function team(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
}
================================================
FILE: app/Models/Passport/AuthCode.php
================================================
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
}
================================================
FILE: app/Models/Passport/Client.php
================================================
$grant_types
* @property array $redirect_uris
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property bool $revoked
*/
class Client extends PassportClient
{
/** @use HasFactory */
use HasFactory;
/**
* Create a new factory instance for the model.
*
* @return ClientFactory
*/
protected static function newFactory(): Factory
{
return ClientFactory::new();
}
}
================================================
FILE: app/Models/Passport/RefreshToken.php
================================================
$scopes
* @property bool $revoked
* @property Carbon|null $reminder_sent_at
* @property Carbon|null $expired_info_sent_at
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property Carbon|null $expires_at
* @property-read Client|null $client
* @property-read User|null $user
*
* @method Builder isApiToken(bool $isApiToken = true)
*/
class Token extends PassportToken
{
/** @use HasFactory */
use HasFactory;
/**
* Get the client that the token belongs to.
*
* @return BelongsTo
*/
// @phpstan-ignore method.childReturnType
public function client(): BelongsTo
{
return $this->belongsTo(Client::class, 'client_id', 'id');
}
/**
* Get the user that the token belongs to.
*
* @deprecated Will be removed in a future Laravel version.
*
* @return BelongsTo
*/
// @phpstan-ignore method.childReturnType
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* Get the attributes that should be cast.
*
* @return array
*/
protected function casts(): array
{
return [
'scopes' => 'array',
'revoked' => 'bool',
'expires_at' => 'datetime',
'reminder_sent_at' => 'datetime',
'expired_info_sent_at' => 'datetime',
];
}
/**
* @param Builder $query
* @return Builder
*/
public function scopeIsApiToken(Builder $query, bool $isApiToken = true): Builder
{
if ($isApiToken) {
return $query->whereHas('client', function (Builder $query): void {
/** @var Builder $query */
$query->whereJsonContains('grant_types', 'personal_access');
});
} else {
return $query->whereHas('client', function (Builder $query): void {
/** @var Builder $query */
$query->whereJsonDoesntContain('grant_types', 'personal_access');
});
}
}
}
================================================
FILE: app/Models/Project.php
================================================
$tasks
* @property-read Collection $members
*
* @method Builder visibleByEmployee(User $user)
* @method static ProjectFactory factory()
*/
class Project extends Model implements AuditableContract
{
use ComputedAttributes;
use CustomAuditable;
/** @use HasFactory */
use HasFactory;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'name' => 'string',
'color' => 'string',
'archived_at' => 'datetime',
'estimated_time' => 'integer',
'spent_time' => 'integer',
];
/**
* Set default values for attributes.
*
* @var array
*/
protected $attributes = [
'is_billable' => false,
];
/**
* The attributes that are computed. (f.e. for performance reasons)
* These attributes can be regenerated at any time.
*
* @var string[]
*/
protected array $computed = [
'spent_time',
];
/**
* Attributes to exclude from the Audit.
*
* @var array
*/
protected array $auditExclude = [
'spent_time',
];
public function getSpentTimeComputed(): ?int
{
if ($this->hasAttribute('spent_time_computed')) {
return $this->attributes['spent_time_computed'] === null ? 0 : (int) $this->attributes['spent_time_computed'];
} else {
/** @var object{ spent_time: string } $result */
$result = $this->timeEntries()
->whereNotNull('end')
->selectRaw('sum(extract(epoch from ("end" - start))) as spent_time')
->first();
return (int) $result->spent_time;
}
}
/**
* This scope will be applied during the computed property generation with artisan computed-attributes:generate.
*
* @param Builder $builder
* @param array $attributes Attributes that will be generated.
* @return Builder
*/
public function scopeComputedAttributesGenerate(Builder $builder, array $attributes): Builder
{
if (in_array('spent_time', $attributes, true)) {
$builder->withAggregate('timeEntries as spent_time_computed', DB::raw('extract(epoch from ("end" - start))'), 'sum');
}
return $builder;
}
/**
* This scope will be applied during the computed property validation with artisan computed-attributes:validate.
*
* @param Builder $builder
* @param array $attributes Attributes that will be validated.
* @return Builder
*/
public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder
{
return $this->scopeComputedAttributesGenerate($builder, $attributes);
}
/**
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* @return BelongsTo
*/
public function client(): BelongsTo
{
return $this->belongsTo(Client::class, 'client_id');
}
/**
* @return HasMany
*/
public function members(): HasMany
{
return $this->hasMany(ProjectMember::class, 'project_id');
}
/**
* @return HasMany
*/
public function tasks(): HasMany
{
return $this->hasMany(Task::class);
}
/**
* @return HasMany
*/
public function timeEntries(): HasMany
{
return $this->hasMany(TimeEntry::class, 'project_id');
}
/**
* @param Builder $builder
*/
public function scopeVisibleByEmployee(Builder $builder, User $user): void
{
$builder->where(function (Builder $builder) use ($user): Builder {
return $builder->where('is_public', '=', true)
->orWhereHas('members', function (Builder $builder) use ($user): Builder {
return $builder->whereBelongsTo($user, 'user');
});
});
}
/**
* @return Attribute
*/
protected function isArchived(): Attribute
{
return Attribute::make(
get: fn (mixed $value, array $attributes) => isset($attributes['archived_at']),
);
}
}
================================================
FILE: app/Models/ProjectMember.php
================================================
whereBelongsToOrganization(Organization $organization)
* @method static ProjectMemberFactory factory()
*/
class ProjectMember extends Model implements AuditableContract
{
use CustomAuditable;
/** @use HasFactory */
use HasFactory;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'billable_rate' => 'int',
];
/**
* @return BelongsTo
*/
public function project(): BelongsTo
{
return $this->belongsTo(Project::class, 'project_id');
}
/**
* @deprecated Use member relationship instead
*
* @return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* @return BelongsTo
*/
public function member(): BelongsTo
{
return $this->belongsTo(Member::class, 'member_id');
}
/**
* @param Builder $builder
*/
public function scopeWhereBelongsToOrganization(Builder $builder, Organization $organization): void
{
$builder->whereHas('project', static function (Builder $query) use ($organization): void {
$query->whereBelongsTo($organization, 'organization');
});
}
}
================================================
FILE: app/Models/Report.php
================================================
*/
use HasFactory;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'is_public' => 'bool',
'public_until' => 'datetime',
'properties' => ReportPropertiesDto::class,
];
public function getShareableLink(): ?string
{
if ($this->is_public && $this->share_secret !== null) {
return route('shared-report').'#'.$this->share_secret;
}
return null;
}
/**
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
}
================================================
FILE: app/Models/Tag.php
================================================
$timeEntries
* @property-read Organization $organization
*
* @method static TagFactory factory()
*/
class Tag extends Model implements AuditableContract
{
use CustomAuditable;
/** @use HasFactory */
use HasFactory;
use HasJsonRelationships;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'name' => 'string',
];
/**
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* Warning: This relation based on a JSON column. Please make sure that there are no performance issues, before using it.
*
* @return HasManyJson
*/
public function timeEntries(): HasManyJson
{
return $this->hasManyJson(TimeEntry::class, 'tags');
}
}
================================================
FILE: app/Models/Task.php
================================================
$timeEntries
* @property-read bool $is_done
*
* @method static TaskFactory factory()
*/
class Task extends Model implements AuditableContract
{
use ComputedAttributes;
use CustomAuditable;
/** @use HasFactory */
use HasFactory;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'name' => 'string',
'estimated_time' => 'integer',
'done_at' => 'datetime',
];
/**
* The attributes that are computed. (f.e. for performance reasons)
* These attributes can be regenerated at any time.
*
* @var string[]
*/
protected array $computed = [
'spent_time',
];
/**
* Attributes to exclude from the Audit.
*
* @var array
*/
protected array $auditExclude = [
'spent_time',
];
public function getSpentTimeComputed(): ?int
{
if ($this->hasAttribute('spent_time_computed')) {
return $this->attributes['spent_time_computed'] === null ? 0 : (int) $this->attributes['spent_time_computed'];
} else {
/** @var object{ spent_time: string } $result */
$result = $this->timeEntries()
->whereNotNull('end')
->selectRaw('sum(extract(epoch from ("end" - start))) as spent_time')
->first();
return (int) $result->spent_time;
}
}
/**
* This scope will be applied during the computed property generation with artisan computed-attributes:generate.
*
* @param Builder $builder
* @param array $attributes Attributes that will be generated.
* @return Builder
*/
public function scopeComputedAttributesGenerate(Builder $builder, array $attributes): Builder
{
if (in_array('spent_time', $attributes, true)) {
$builder->withAggregate('timeEntries as spent_time_computed', DB::raw('extract(epoch from ("end" - start))'), 'sum');
}
return $builder;
}
/**
* This scope will be applied during the computed property validation with artisan computed-attributes:validate.
*
* @param Builder $builder
* @param array $attributes Attributes that will be validated.
* @return Builder
*/
public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder
{
return $this->scopeComputedAttributesGenerate($builder, $attributes);
}
/**
* @return BelongsTo
*/
public function project(): BelongsTo
{
return $this->belongsTo(Project::class);
}
/**
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* @return HasMany
*/
public function timeEntries(): HasMany
{
return $this->hasMany(TimeEntry::class, 'task_id');
}
/**
* @param Builder $builder
* @return Builder
*/
public function scopeVisibleByEmployee(Builder $builder, User $user): Builder
{
return $builder->whereHas('project', function (Builder $builder) use ($user): Builder {
/** @var Builder $builder */
return $builder->visibleByEmployee($user);
});
}
/**
* @return Attribute
*/
public function isDone(): Attribute
{
return Attribute::make(
get: fn (mixed $value, array $attributes) => isset($attributes['done_at']),
);
}
}
================================================
FILE: app/Models/TimeEntry.php
================================================
$tags
* @property string $user_id
* @property string $member_id
* @property bool $is_imported
* @property Carbon|null $still_active_email_sent_at
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property-read User $user
* @property-read Member $member
* @property string $organization_id
* @property-read Organization $organization
* @property string|null $project_id
* @property-read Project|null $project
* @property string|null $client_id
* @property-read Client|null $client
* @property string|null $task_id
* @property-read Task|null $task
* @property-read Collection $tagsRelation
*
* @method Builder hasTag(Tag $tag)
* @method static TimeEntryFactory factory()
*/
class TimeEntry extends Model implements AuditableContract
{
use ComputedAttributes;
use CustomAuditable;
/** @use HasFactory */
use HasFactory;
use HasJsonRelationships;
use HasUuids;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'description' => 'string',
'start' => 'datetime',
'end' => 'datetime',
'billable' => 'bool',
'tags' => 'array',
'billable_rate' => 'int',
'is_imported' => 'bool',
'still_active_email_sent_at' => 'datetime',
];
public const array SELECT_COLUMNS = [
'id',
'description',
'start',
'end',
'billable_rate',
'billable',
'user_id',
'organization_id',
'project_id',
'task_id',
'tags',
'created_at',
'updated_at',
'member_id',
'client_id',
'is_imported',
'still_active_email_sent_at',
];
/**
* The attributes that are computed. (f.e. for performance reasons)
* These attributes can be regenerated at any time.
*
* @var string[]
*/
protected array $computed = [
'billable_rate',
'client_id',
];
/**
* Attributes to exclude from the Audit.
*
* @var array
*/
protected array $auditExclude = [
'billable_rate',
];
public function getBillableRateComputed(): ?int
{
return app(BillableRateService::class)->getBillableRateForTimeEntry($this);
}
public function getClientIdComputed(): ?string
{
return $this->project_id === null || $this->project === null ? null : $this->project->client_id;
}
/**
* This scope will be applied during the computed property generation with artisan computed-attributes:generate.
*
* @param Builder $builder
* @param array $attributes Attributes that will be generated.
* @return Builder
*/
public function scopeComputedAttributesGenerate(Builder $builder, array $attributes): Builder
{
if (in_array('client_id', $attributes, true)) {
$builder->with([
'project' => function (Relation $builder): void {
/** @var Builder $builder */
$builder->select('id', 'client_id');
},
]);
}
return $builder;
}
/**
* This scope will be applied during the computed property validation with artisan computed-attributes:validate.
*
* @param Builder $builder
* @param array $attributes Attributes that will be validated.
* @return Builder
*/
public function scopeComputedAttributesValidate(Builder $builder, array $attributes): Builder
{
return $this->scopeComputedAttributesGenerate($builder, $attributes);
}
public function getDuration(): ?CarbonInterval
{
return $this->end === null ? null : $this->start->diffAsCarbonInterval($this->end);
}
/**
* @param Builder $builder
*/
public function scopeHasTag(Builder $builder, Tag $tag): void
{
$builder->whereJsonContains('tags', $tag->getKey());
}
/**
* @return BelongsTo
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* @return BelongsTo
*/
public function member(): BelongsTo
{
return $this->belongsTo(Member::class, 'member_id');
}
/**
* @return BelongsTo
*/
public function organization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'organization_id');
}
/**
* @return BelongsTo
*/
public function project(): BelongsTo
{
return $this->belongsTo(Project::class, 'project_id');
}
/**
* @return BelongsTo
*/
public function task(): BelongsTo
{
return $this->belongsTo(Task::class, 'task_id');
}
/**
* This relation can be reconstructed via the task relation. It is only here for performance reasons.
*
* @return BelongsTo
*/
public function client(): BelongsTo
{
return $this->belongsTo(Client::class, 'client_id');
}
/**
* Warning: This relation based on a JSON column. Please make sure that there are no performance issues, before using it.
*
* @return BelongsToJson
*/
public function tagsRelation(): BelongsToJson
{
return $this->belongsToJson(Tag::class, 'tags');
}
}
================================================
FILE: app/Models/User.php
================================================
$tokens
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property string|null $current_team_id
* @property Collection $organizations
* @property Collection $timeEntries
* @property Member $membership
*
* @method HasMany ownedTeams()
* @method static UserFactory factory()
* @method static Builder query()
* @method Builder belongsToOrganization(Organization $organization)
* @method Builder active()
*/
class User extends Authenticatable implements AuditableContract, FilamentUser, MustVerifyEmail, OAuthenticatable
{
use CustomAuditable;
use HasApiTokens;
/** @use HasFactory */
use HasFactory;
use HasProfilePhoto;
use HasTeams;
use HasUuids;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* @var list
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'name' => 'string',
'email' => 'string',
'email_verified_at' => 'datetime',
'is_admin' => 'boolean',
'is_placeholder' => 'boolean',
'week_start' => Weekday::class,
];
/**
* The model's default values for attributes.
*
* @var array
*/
protected $attributes = [
'week_start' => Weekday::Monday,
];
/**
* Get the URL to the user's profile photo.
*
* @return Attribute
*/
protected function profilePhotoUrl(): Attribute
{
return Attribute::get(function (): string {
return $this->profile_photo_path
? Storage::disk($this->profilePhotoDisk())->url($this->profile_photo_path)
: $this->defaultProfilePhotoUrl();
});
}
public function canAccessPanel(Panel $panel): bool
{
return in_array($this->email, config('auth.super_admins', []), true) && $this->hasVerifiedEmail();
}
public function canBeImpersonated(): bool
{
return $this->is_placeholder === false;
}
/**
* @return BelongsToMany
*/
public function organizations(): BelongsToMany
{
return $this->belongsToMany(Organization::class, Member::class)
->withPivot([
'id',
'role',
'billable_rate',
])
->withTimestamps()
->as('membership');
}
/**
* @return HasMany
*/
public function timeEntries(): HasMany
{
return $this->hasMany(TimeEntry::class);
}
/**
* @return BelongsTo
*/
public function currentOrganization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'current_team_id');
}
/**
* @return HasMany
*/
public function projectMembers(): HasMany
{
return $this->hasMany(ProjectMember::class, 'user_id');
}
/**
* @return HasMany
*/
public function accessTokens(): HasMany
{
return $this->hasMany(Token::class);
}
/**
* @return HasMany
*/
public function authCodes(): HasMany
{
return $this->hasMany(AuthCode::class);
}
/**
* @param Builder $builder
*/
public function scopeActive(Builder $builder): void
{
$builder->where('is_placeholder', '=', false);
}
/**
* @param Builder $builder
* @return Builder
*/
public function scopeBelongsToOrganization(Builder $builder, Organization $organization): Builder
{
return $builder->where(function (Builder $builder) use ($organization): Builder {
return $builder->whereHas('organizations', function (Builder $query) use ($organization): void {
$query->whereKey($organization->getKey());
})->orWhereHas('ownedTeams', function (Builder $query) use ($organization): void {
$query->whereKey($organization->getKey());
});
});
}
}
================================================
FILE: app/Policies/OrganizationPolicy.php
================================================
belongsToTeam($organization);
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
if (Filament::isServing()) {
return true;
}
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Organization $organization): bool
{
if (Filament::isServing()) {
return true;
}
return app(PermissionStore::class)->userHas($organization, $user, 'organizations:update');
}
/**
* Determine whether the user can add team members.
*/
public function addTeamMember(User $user, Organization $organization): bool
{
if (Filament::isServing()) {
return true;
}
return true;
}
/**
* Determine whether the user can update team member permissions.
*/
public function updateTeamMember(User $user, Organization $organization): bool
{
if (Filament::isServing()) {
return true;
}
// Note: since this policy is only used for jetstream endpoints, we can return false here
return false;
}
/**
* Determine whether the user can remove team members.
*/
public function removeTeamMember(User $user, Organization $organization): bool
{
if (Filament::isServing()) {
return true;
}
// Note: since this policy is only used for jetstream endpoints that are no longer in use, we can return false here
return false;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Organization $organization): bool
{
if (Filament::isServing()) {
return true;
}
return $user->ownsTeam($organization);
}
}
================================================
FILE: app/Providers/AppServiceProvider.php
================================================
app->environment('local')) {
$this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);
$this->app->register(TelescopeServiceProvider::class);
}
// Eloquent
Model::preventLazyLoading(! $this->app->isProduction());
Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction());
Model::preventAccessingMissingAttributes(! $this->app->isProduction());
Relation::enforceMorphMap([
'client' => Client::class,
'failed-job' => FailedJob::class,
'membership' => Member::class,
'organization' => Organization::class,
'organization-invitation' => OrganizationInvitation::class,
'project' => Project::class,
'project-member' => ProjectMember::class,
'tag' => Tag::class,
'task' => Task::class,
'time-entry' => TimeEntry::class,
'user' => User::class,
]);
Model::unguard();
// Filament
Section::configureUsing(function (Section $section): void {
$section->columns(1);
}, null, true);
Table::configureUsing(function (Table $table): void {
$table->paginated([10, 25, 50, 100]);
});
// Scramble
Scramble::extendOpenApi(function (OpenApi $openApi): void {
$openApi->secure(
SecurityScheme::oauth2()
->flow('authorizationCode', function (OAuthFlow $flow): void {
$flow
->authorizationUrl('https://solidtime.test/oauth/authorize');
})
);
});
$this->app->scoped(PermissionStore::class, function (Application $app): PermissionStore {
return new PermissionStore;
});
// Extensions
$this->app->bind(IpLookupServiceContract::class, NoIpLookupService::class);
$this->app->bind(BillingContract::class);
// Routing
Route::model('member', Member::class);
Route::model('invitation', OrganizationInvitation::class);
Route::model('apiToken', Token::class);
}
}
================================================
FILE: app/Providers/AuthServiceProvider.php
================================================
*/
protected $policies = [
Organization::class => OrganizationPolicy::class,
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
// define scopes for passport tokens
Passport::tokensCan([
'create' => 'Create resources',
'read' => 'Read Resources',
'update' => 'Update Resources',
'delete' => 'Delete Resources',
]);
// default scope for passport tokens
Passport::setDefaultScope([
// 'create',
'read',
// 'update',
// 'delete',
]);
Passport::useTokenModel(Token::class);
Passport::useRefreshTokenModel(RefreshToken::class);
Passport::useAuthCodeModel(AuthCode::class);
Passport::useClientModel(Client::class);
Passport::authorizationView('auth.oauth.authorize');
// Passport::tokensExpireIn(now()->addDays(15));
// Passport::refreshTokensExpireIn(now()->addDays(30));
Passport::personalAccessTokensExpireIn(now()->addMonths(12));
// same as passport default above
Jetstream::defaultApiTokenPermissions(['read']);
// use passport scopes for jetstream token permissions
Jetstream::permissions(Passport::scopeIds());
}
}
================================================
FILE: app/Providers/EventServiceProvider.php
================================================
>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
TeamMemberAdded::class => [
RemovePlaceholder::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}
================================================
FILE: app/Providers/Filament/AdminPanelProvider.php
================================================
default()
->id('admin')
->path('admin')
->colors([
'primary' => Color::Amber,
])
->discoverResources(in: app_path('Filament/Resources'), for: 'App\\Filament\\Resources')
->discoverPages(in: app_path('Filament/Pages'), for: 'App\\Filament\\Pages')
->pages([
Pages\Dashboard::class,
])
->discoverWidgets(in: app_path('Filament/Widgets'), for: 'App\\Filament\\Widgets')
->widgets([
ServerOverview::class,
ActiveUserOverview::class,
UserRegistrations::class,
TimeEntriesCreated::class,
TimeEntriesImported::class,
])
->viteTheme('resources/css/filament/admin/theme.css')
->plugins([
EnvironmentIndicatorPlugin::make()
->color(fn () => match (App::environment()) {
'production' => null,
'staging' => Color::Orange,
default => Color::Blue,
}),
])
->navigationGroups([
NavigationGroup::make()
->label('Timetracking'),
NavigationGroup::make()
->label('Users')
->collapsed(),
NavigationGroup::make()
->label('System')
->collapsed(),
NavigationGroup::make()
->label('Auth')
->collapsed(),
])
->middleware([
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
SubstituteBindings::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->authMiddleware([
Authenticate::class,
]);
$modules = Module::allEnabled();
foreach ($modules as $module) {
$panel->discoverResources(
in: module_path($module->getName(), 'app/Filament/Resources'),
for: 'Extensions\\'.$module->getName().'\\App\\Filament\\Resources'
);
$panel->discoverPages(
in: module_path($module->getName(), 'app/Filament/Pages'),
for: 'Extensions\\'.$module->getName().'\\App\\Filament\\Pages'
);
$panel->discoverWidgets(
in: module_path($module->getName(), 'app/Filament/Widgets'),
for: 'Extensions\\'.$module->getName().'\\App\\Filament\\Widgets'
);
}
return $panel;
}
}
================================================
FILE: app/Providers/FortifyServiceProvider.php
================================================
where('email', $request->email)
->where('is_placeholder', '=', false)
->first();
if ($user !== null && Hash::check($request->password, $user->password)) {
return $user;
}
return null;
});
RateLimiter::for('login', function (Request $request) {
$throttleKey = Str::transliterate(Str::lower($request->input(Fortify::username())).'|'.$request->ip());
return Limit::perMinute(5)->by($throttleKey);
});
RateLimiter::for('two-factor', function (Request $request) {
return Limit::perMinute(5)->by($request->session()->get('login.id'));
});
$this->app->instance(LoginResponse::class, new CustomLoginResponse);
$this->app->instance(TwoFactorLoginResponse::class, new CustomTwoFactorLoginResponse);
}
}
================================================
FILE: app/Providers/JetstreamServiceProvider.php
================================================
configurePermissions();
Jetstream::createTeamsUsing(CreateOrganization::class);
Jetstream::updateTeamNamesUsing(UpdateOrganization::class);
Jetstream::addTeamMembersUsing(AddOrganizationMember::class);
Jetstream::inviteTeamMembersUsing(InviteOrganizationMember::class);
Jetstream::removeTeamMembersUsing(RemoveOrganizationMember::class);
Jetstream::deleteTeamsUsing(DeleteOrganization::class);
Jetstream::deleteUsersUsing(DeleteUser::class);
Jetstream::useTeamModel(Organization::class);
Jetstream::useMembershipModel(Member::class);
Jetstream::useTeamInvitationModel(OrganizationInvitation::class);
app()->singleton(UpdateTeamMemberRole::class, UpdateMemberRole::class);
app()->singleton(ValidateTeamDeletion::class, ValidateOrganizationDeletion::class);
Fortify::registerView(function () {
return Inertia::render('Auth/Register', [
'terms_url' => config('auth.terms_url'),
'privacy_policy_url' => config('auth.privacy_policy_url'),
'newsletter_consent' => config('auth.newsletter_consent'),
]);
});
Gate::define('removeTeamMember', function (User $user, Organization $team) {
return false;
});
}
/**
* Configure the roles and permissions that are available within the application.
*/
protected function configurePermissions(): void
{
Jetstream::defaultApiTokenPermissions([]);
Jetstream::role(Role::Owner->value, 'Owner', [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'organizations:update',
'organizations:delete',
'import',
'export',
'invitations:view',
'invitations:create',
'invitations:resend',
'invitations:remove',
'members:view',
'members:invite-placeholder',
'members:change-ownership',
'members:make-placeholder',
'members:merge-into',
'members:update',
'members:delete',
'billing',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
])->description('Owner users can perform any action. There is only one owner per organization.');
Jetstream::role(Role::Admin->value, 'Administrator', [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'organizations:update',
'import',
'export',
'invitations:view',
'invitations:create',
'invitations:resend',
'invitations:remove',
'members:view',
'members:invite-placeholder',
'members:make-placeholder',
'members:merge-into',
'members:delete',
'members:update',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
])->description('Administrator users can perform any action, except accessing the billing dashboard.');
Jetstream::role(Role::Manager->value, 'Manager', [
'charts:view:own',
'charts:view:all',
'projects:view',
'projects:view:all',
'projects:create',
'projects:update',
'projects:delete',
'project-members:view',
'project-members:create',
'project-members:update',
'project-members:delete',
'tasks:view',
'tasks:view:all',
'tasks:create',
'tasks:create:all',
'tasks:update',
'tasks:update:all',
'tasks:delete',
'tasks:delete:all',
'time-entries:view:all',
'time-entries:create:all',
'time-entries:update:all',
'time-entries:delete:all',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'tags:view',
'tags:create',
'tags:update',
'tags:delete',
'clients:view',
'clients:view:all',
'clients:create',
'clients:update',
'clients:delete',
'organizations:view',
'invitations:view',
'members:view',
'reports:view',
'reports:create',
'reports:update',
'reports:delete',
'invoices:view',
'invoices:create',
'invoices:update',
'invoices:download',
'invoices:delete',
'invoice-settings:view',
'invoice-settings:update',
])->description('Managers have full access to all projects, time entries, ect. but cannot manage the organization (add/remove member, edit the organization, ect.).');
Jetstream::role(Role::Employee->value, 'Employee', [
'charts:view:own',
'projects:view',
'tags:view',
'tasks:view',
'clients:view',
'time-entries:view:own',
'time-entries:create:own',
'time-entries:update:own',
'time-entries:delete:own',
'organizations:view',
])->description('Employees have the ability to read, create, and update their own time entries, they can see the projects that they are members of and the clients they are assigned to.');
Jetstream::role(Role::Placeholder->value, 'Placeholder', [
])->description('Placeholders are used for importing data. They cannot log in and have no permissions.');
Jetstream::inertia()
->whenRendering(
'Profile/Show',
function (Request $request, array $data): array {
return array_merge($data, [
'timezones' => $this->app->get(TimezoneService::class)->getSelectOptions(),
'weekdays' => Weekday::toSelectArray(),
]);
}
)
->whenRendering(
'Teams/Show',
function (Request $request, array $data): array {
/** @var Organization $teamModel */
$teamModel = $data['team'];
$owner = $teamModel->owner;
return array_merge($data, [
'team' => [
'id' => $teamModel->getKey(),
'name' => $teamModel->name,
'currency' => $teamModel->currency,
'owner' => [
'id' => $owner->getKey(),
'name' => $owner->name,
'email' => $owner->email,
'profile_photo_url' => $owner->profile_photo_url,
],
'users' => $teamModel->users->map(function (User $user): array {
return [
'id' => $user->getKey(),
'name' => $user->name,
'email' => $user->email,
'profile_photo_url' => $user->profile_photo_url,
'membership' => [
'id' => $user->membership->id,
'role' => $user->membership->role,
],
];
}),
'team_invitations' => $teamModel->teamInvitations->map(function (OrganizationInvitation $invitation): array {
return [
'id' => $invitation->getKey(),
'email' => $invitation->email,
'role' => $invitation->role,
];
}),
],
'currencies' => array_map(function (Currency $currency): string {
return $currency->getName();
}, ISOCurrencyProvider::getInstance()->getAvailableCurrencies()),
]);
}
);
}
}
================================================
FILE: app/Providers/RouteServiceProvider.php
================================================
app->isProduction()) {
return Limit::none();
}
return $request->user()
? Limit::perMinute(200)->by($request->user()->id)
: Limit::perMinute(60)->by($request->ip());
});
$this->routes(function (): void {
Route::middleware('health-check')
->group(function (): void {
Route::get('health-check/up', [HealthCheckController::class, 'up']);
Route::get('health-check/debug', [HealthCheckController::class, 'debug']);
});
Route::middleware('api')
->prefix('api')
->name('api.')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
}
================================================
FILE: app/Providers/TelescopeServiceProvider.php
================================================
hideSensitiveRequestDetails();
Telescope::filter(function (IncomingEntry $entry): bool {
if ($this->app->environment('local')) {
return true;
}
return $entry->isReportableException() ||
$entry->isFailedRequest() ||
$entry->isFailedJob() ||
$entry->isScheduledTask() ||
$entry->hasMonitoredTag();
});
}
/**
* Prevent sensitive request details from being logged by Telescope.
*/
protected function hideSensitiveRequestDetails(): void
{
if ($this->app->environment('local')) {
return;
}
Telescope::hideRequestParameters(['_token']);
Telescope::hideRequestHeaders([
'cookie',
'x-csrf-token',
'x-xsrf-token',
]);
}
/**
* Register the Telescope gate.
*
* This gate determines who can access Telescope in non-local environments.
*/
protected function gate(): void
{
Gate::define('viewTelescope', function (User $user): bool {
// Note: Telescope is only available in local environments, so this should not be relevant.
return false;
});
}
}
================================================
FILE: app/Rules/ColorRule.php
================================================
isValid($value)) {
$fail(__('validation.color'));
return;
}
}
}
================================================
FILE: app/Rules/CurrencyRule.php
================================================
getAvailableCurrencies();
if (array_key_exists($value, $currencies)) {
return;
}
$fail(__('validation.currency'));
}
}
================================================
FILE: app/Service/ApiService.php
================================================
timeout(3)
->connectTimeout(2)
->post(self::API_URL.'/ping/version', [
'version' => config('app.version'),
'build' => config('app.build'),
'url' => config('app.url'),
]);
if ($response->status() === 200 && isset($response->json()['version']) && is_string($response->json()['version'])) {
return $response->json()['version'];
} else {
Log::warning('Failed to check for update', [
'status' => $response->status(),
'body' => $response->body(),
]);
return null;
}
} catch (\Throwable $e) {
Log::warning('Failed to check for update', [
'message' => $e->getMessage(),
]);
return null;
}
}
public function telemetry(): bool
{
try {
$response = Http::asJson()
->timeout(3)
->connectTimeout(2)
->post(self::API_URL.'/ping/telemetry', [
'version' => config('app.version'),
'build' => config('app.build'),
'url' => config('app.url'),
// telemetry data
'user_count' => User::count(),
'organization_count' => Organization::count(),
'audit_count' => Audit::count(),
'project_count' => Project::count(),
'project_member_count' => ProjectMember::count(),
'client_count' => Client::count(),
'task_count' => Task::count(),
'time_entry_count' => TimeEntry::count(),
]);
if ($response->status() === 200) {
return true;
} else {
Log::warning('Failed send telemetry data', [
'status' => $response->status(),
'body' => $response->body(),
]);
return false;
}
} catch (Exception $e) {
Log::warning('Failed send telemetry data', [
'message' => $e->getMessage(),
]);
return false;
}
}
}
================================================
FILE: app/Service/BillableRateService.php
================================================
where('billable', '=', true)
->where('member_id', '=', $projectMember->member_id)
->where('project_id', '=', $projectMember->project_id)
->update(['billable_rate' => $projectMember->billable_rate]);
}
public function updateTimeEntriesBillableRateForProject(Project $project): void
{
TimeEntry::query()
->where('billable', '=', true)
->where('organization_id', '=', $project->organization_id)
->whereBelongsTo($project, 'project')
->whereDoesntHave('member', function (Builder $query) use ($project): void {
/** @var Builder $query */
$query->whereHas('projectMembers', function (Builder $query) use ($project): void {
/** @var Builder $query */
$query->whereBelongsTo($project, 'project')
->whereNotNull('billable_rate');
});
})
->update(['billable_rate' => $project->billable_rate]);
}
public function updateTimeEntriesBillableRateForMember(Member $member): void
{
TimeEntry::query()
->where('billable', '=', true)
->where('organization_id', '=', $member->organization_id)
->where('member_id', '=', $member->getKey())
->whereDoesntHave('project', function (Builder $builder) use ($member): void {
/** @var Builder $builder */
$builder->whereNotNull('billable_rate')
->orWhereHas('members', function (Builder $builder) use ($member): void {
/** @var Builder