OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Revert "Merge remote-tracking branch 'origin/fix/remove_dependency_from_gon' into dev"
Oliver Güntherca97e60e0f9a
diff --git a/app/controllers/forums_controller.rb b/app/controllers/forums_controller.rbindex c6d03c192d1..65a2ccb0884 100644--- a/app/controllers/forums_controller.rb+++ b/app/controllers/forums_controller.rb@@ -38,6 +38,7 @@ class ForumsController < ApplicationControllerinclude SortHelperinclude WatchersHelperinclude PaginationHelper+ include OpenProject::ClientPreferenceExtractordef index@forums = @project.forumsdiff --git a/app/controllers/timelog_controller.rb b/app/controllers/timelog_controller.rbindex 58489ce69ad..ad8cc7d8f67 100644--- a/app/controllers/timelog_controller.rb+++ b/app/controllers/timelog_controller.rb@@ -40,6 +40,7 @@ class TimelogController < ApplicationControllerinclude CustomFieldsHelperinclude PaginationHelperinclude Concerns::Layout+ include OpenProject::ClientPreferenceExtractormenu_item :time_entriesdiff --git a/app/controllers/work_packages_controller.rb b/app/controllers/work_packages_controller.rbindex a748598a343..e86efd714d0 100644--- a/app/controllers/work_packages_controller.rb+++ b/app/controllers/work_packages_controller.rb@@ -31,6 +31,7 @@class WorkPackagesController < ApplicationControllerinclude QueriesHelperinclude PaginationHelper+ include OpenProject::ClientPreferenceExtractorinclude Concerns::Layoutaccept_key_auth :index, :show@@ -39,8 +40,10 @@ class WorkPackagesController < ApplicationControllerbefore_action :find_optional_project,:protect_from_unauthorized_export, only: :index- before_action :load_and_validate_query, only: :index, unless: -> { request.format.html? }- before_action :load_work_packages, only: :index, if: -> { request.format.atom? }+ before_action :load_and_validate_query, only: :index, unless: ->() { request.format.html? }+ before_action :load_work_packages, only: :index, if: ->() { request.format.atom? }++ before_action :set_gon_settingsdef showrespond_to do |format|@@ -81,6 +84,11 @@ class WorkPackagesController < ApplicationControllerprotected+ def set_gon_settings+ gon.settings = client_preferences+ gon.settings[:enabled_modules] = project ? project.enabled_modules.collect(&:name) : []+ end+def export_list(mime_type)exporter = WorkPackage::Exporter.for_list(mime_type)exporter.list(@query, params) do |export|diff --git a/app/models/user_preference.rb b/app/models/user_preference.rbindex 9c6e53706d6..cdfebdc4595 100644--- a/app/models/user_preference.rb+++ b/app/models/user_preference.rb@@ -98,7 +98,9 @@ class UserPreference < ActiveRecord::Basereturn if time_zone.nil?zone = ActiveSupport::TimeZone.new(time_zone)- zone&.tzinfo&.canonical_identifier+ unless zone.nil?+ zone.tzinfo.canonical_identifier+ endendprivatediff --git a/frontend/src/app/components/table-pagination/pagination-instance.ts b/frontend/src/app/components/table-pagination/pagination-instance.tsindex 537f37a679e..b94ca2a4c72 100644--- a/frontend/src/app/components/table-pagination/pagination-instance.ts+++ b/frontend/src/app/components/table-pagination/pagination-instance.ts@@ -27,6 +27,7 @@//+++import {IPaginationOptions} from 'core-components/table-pagination/pagination-service';export class PaginationInstance {constructor(public page:number,diff --git a/frontend/src/app/components/table-pagination/pagination-service.ts b/frontend/src/app/components/table-pagination/pagination-service.tsindex a8442c01e74..d027a38e9c1 100644--- a/frontend/src/app/components/table-pagination/pagination-service.ts+++ b/frontend/src/app/components/table-pagination/pagination-service.ts@@ -27,7 +27,8 @@//++import {Injectable} from '@angular/core';-import {ConfigurationService} from "core-app/modules/common/config/configuration.service";+import {ConfigurationDmService} from 'core-app/modules/hal/dm-services/configuration-dm.service';+import {take} from "rxjs/operators";export const DEFAULT_PAGINATION_OPTIONS = {maxVisiblePageOptions: 6,@@ -45,15 +46,35 @@ export interface IPaginationOptions {export class PaginationService {private paginationOptions:IPaginationOptions;- constructor(private configuration:ConfigurationService) {- this.loadPaginationOptions();+ constructor(private ConfigurationDm:ConfigurationDmService) {+ const gonPaginationOptions = this.getInitialPageOptions();++ this.paginationOptions = {+ perPage: this.getCachedPerPage(gonPaginationOptions),+ perPageOptions: gonPaginationOptions,+ maxVisiblePageOptions: DEFAULT_PAGINATION_OPTIONS.maxVisiblePageOptions,+ optionsTruncationSize: DEFAULT_PAGINATION_OPTIONS.optionsTruncationSize+ };+ }++ public getInitialPageOptions():number[] {+ try {+ return (window as any).gon.settings.pagination.per_page_options;+ } catch (e) {+ console.log("Can't load initial page options from gon: " + e);+ return [];+ }}public getCachedPerPage(initialPageOptions:number[]):number {- const value = this.localStoragePerPage;+ const value = window.OpenProject.guardedLocalStorage('pagination.perPage') as string;++ if (value !== undefined) {+ const perPage = parseInt(value, 10);- if (value !== null && value > 0 && (initialPageOptions.length === 0 || initialPageOptions.indexOf(value) !== -1)) {- return value;+ if (perPage > 0 && (initialPageOptions.length === 0 || initialPageOptions.indexOf(perPage) !== -1)) {+ return perPage;+ }}if (initialPageOptions.length > 0) {@@ -63,26 +84,12 @@ export class PaginationService {return 20;}- private get localStoragePerPage() {- const value = window.OpenProject.guardedLocalStorage('pagination.perPage') as string;-- if (value !== undefined) {- return parseInt(value, 10);- } else {- return null;- }- }-public getPaginationOptions() {return this.paginationOptions;}- public get isPerPageKnown() {- return !!(this.localStoragePerPage || this.paginationOptions);- }-public getPerPage() {- return this.localStoragePerPage || this.paginationOptions.perPage;+ return this.paginationOptions.perPage;}public getMaxVisiblePageOptions() {@@ -107,15 +114,12 @@ export class PaginationService {}public loadPaginationOptions() {- return this.configuration.initialized.then(() => {- this.paginationOptions = {- perPage: this.getCachedPerPage(this.configuration.perPageOptions),- perPageOptions: this.configuration.perPageOptions,- maxVisiblePageOptions: DEFAULT_PAGINATION_OPTIONS.maxVisiblePageOptions,- optionsTruncationSize: DEFAULT_PAGINATION_OPTIONS.optionsTruncationSize- };-- return this.paginationOptions;- });+ return this.ConfigurationDm+ .load()+ .toPromise()+ .then((configuration:any) => {+ this.setPerPageOptions(configuration.perPageOptions);+ return this.paginationOptions;+ });}}diff --git a/frontend/src/app/components/wp-edit-form/work-package-filter-values.spec.ts b/frontend/src/app/components/wp-edit-form/work-package-filter-values.spec.tsindex e9048ec15ae..eb07d40f41f 100644--- a/frontend/src/app/components/wp-edit-form/work-package-filter-values.spec.ts+++ b/frontend/src/app/components/wp-edit-form/work-package-filter-values.spec.ts@@ -56,7 +56,6 @@ import {HalEventsService} from "core-app/modules/hal/services/hal-events.serviceimport {TimezoneService} from "core-components/datetime/timezone.service";import {WorkPackageChangeset} from "core-components/wp-edit/work-package-changeset";import {WorkPackageNotificationService} from "core-app/modules/work_packages/notifications/work-package-notification.service";-import {ConfigurationDmService} from "core-app/modules/hal/dm-services/configuration-dm.service";describe('WorkPackageFilterValues', () => {let resource:WorkPackageResource;@@ -83,7 +82,6 @@ describe('WorkPackageFilterValues', () => {TimezoneService,PathHelperService,ConfigurationService,- ConfigurationDmService,CurrentUserService,HookService,OpenProjectFileUploadService,diff --git a/frontend/src/app/components/wp-list/wp-list.service.ts b/frontend/src/app/components/wp-list/wp-list.service.tsindex 146db518bfa..9f9ca26c1ac 100644--- a/frontend/src/app/components/wp-list/wp-list.service.ts+++ b/frontend/src/app/components/wp-list/wp-list.service.ts@@ -35,6 +35,7 @@ import {WorkPackagesListInvalidQueryService} from './wp-list-invalid-query.serviimport {WorkPackageStatesInitializationService} from './wp-states-initialization.service';import {AuthorisationService} from 'core-app/modules/common/model-auth/model-auth.service';import {StateService} from '@uirouter/core';+import {WorkPackagesListChecksumService} from 'core-components/wp-list/wp-list-checksum.service';import {IsolatedQuerySpace} from "core-app/modules/work_packages/query-space/isolated-query-space";import {Injectable} from '@angular/core';import {QueryFormDmService} from 'core-app/modules/hal/dm-services/query-form-dm.service';@@ -42,12 +43,10 @@ import {PaginationObject, QueryDmService} from 'core-app/modules/hal/dm-servicesimport {UrlParamsHelperService} from 'core-components/wp-query/url-params-helper';import {NotificationsService} from 'core-app/modules/common/notifications/notifications.service';import {I18nService} from "core-app/modules/common/i18n/i18n.service";-import {from, Observable, of} from 'rxjs';+import {BehaviorSubject, from, Observable, of} from 'rxjs';import {input} from "reactivestates";-import {catchError, mergeMap, share, switchMap, take, delay, combineLatest} from "rxjs/operators";+import {catchError, mergeMap, share, switchMap, take, tap} from "rxjs/operators";import {WorkPackageViewPaginationService} from "core-app/modules/work_packages/routing/wp-view-base/view-services/wp-view-pagination.service";-import {ConfigurationService} from "core-app/modules/common/config/configuration.service";-import {PaginationService} from "core-components/table-pagination/pagination-service";export interface QueryDefinition {queryParams:{ query_id?:string, query_props?:string };@@ -64,13 +63,8 @@ export class WorkPackagesListService {private queryLoading = this.queryRequests.values$().pipe(- switchMap((q:QueryDefinition) => {- return from(this.ensurePerPageKnown().then(() => q));- }),// Stream the query request, switchMap will call previous requests to be cancelled- switchMap((q:QueryDefinition) =>- this.streamQueryRequest(q.queryParams, q.projectIdentifier)- ),+ switchMap((q:QueryDefinition) => this.streamQueryRequest(q.queryParams, q.projectIdentifier)),// Map the observable from the stream to a new one that completes when states are loadedmergeMap((query:QueryResource) => {// load the form if needed@@ -94,8 +88,6 @@ export class WorkPackagesListService {protected QueryFormDm:QueryFormDmService,protected states:States,protected querySpace:IsolatedQuerySpace,- protected pagination:PaginationService,- protected configuration:ConfigurationService,protected wpTablePagination:WorkPackageViewPaginationService,protected wpStatesInitialization:WorkPackageStatesInitializationService,protected wpListInvalidQueryService:WorkPackagesListInvalidQueryService) {@@ -359,12 +351,4 @@ export class WorkPackagesListService {.catch(reject);});}-- private async ensurePerPageKnown() {- if (this.pagination.isPerPageKnown) {- return true;- } else {- return this.configuration.initialized;- }- }}diff --git a/frontend/src/app/components/wp-table/table-pagination/wp-table-pagination.component.spec.ts b/frontend/src/app/components/wp-table/table-pagination/wp-table-pagination.component.spec.tsindex 492ef4ce0af..478f91dacef 100644--- a/frontend/src/app/components/wp-table/table-pagination/wp-table-pagination.component.spec.ts+++ b/frontend/src/app/components/wp-table/table-pagination/wp-table-pagination.component.spec.ts@@ -29,6 +29,7 @@import {HttpClientModule} from '@angular/common/http';import {IsolatedQuerySpace} from "core-app/modules/work_packages/query-space/isolated-query-space";+import {ConfigurationDmService} from 'core-app/modules/hal/dm-services/configuration-dm.service';import {async, inject, TestBed} from '@angular/core/testing';import {States} from 'core-components/states.service';import {PaginationInstance} from 'core-components/table-pagination/pagination-instance';@@ -41,26 +42,15 @@ import {I18nService} from "core-app/modules/common/i18n/i18n.service";import {OpenProject} from "core-app/globals/openproject";import {OpIcon} from "core-app/modules/common/icon/op-icon";import {WorkPackageViewSortByService} from "core-app/modules/work_packages/routing/wp-view-base/view-services/wp-view-sort-by.service";-import {ConfigurationService} from "core-app/modules/common/config/configuration.service";-import {ConfigurationDmService} from "core-app/modules/hal/dm-services/configuration-dm.service";function setupMocks(paginationService:PaginationService) {- const options:IPaginationOptions = {- perPage: 0,- perPageOptions: [10, 50],- maxVisiblePageOptions: 1,- optionsTruncationSize: 6- };-- spyOn(paginationService, 'getMaxVisiblePageOptions').and.callFake(() => {- return options.maxVisiblePageOptions;- });-- spyOn(paginationService, 'getOptionsTruncationSize').and.callFake(() => {- return options.optionsTruncationSize;- });-spyOn(paginationService, 'loadPaginationOptions').and.callFake(() => {+ const options:IPaginationOptions = {+ perPage: 0,+ perPageOptions: [10, 100, 500, 1000],+ maxVisiblePageOptions: 0,+ optionsTruncationSize: 0+ };return Promise.resolve(options);});}@@ -73,6 +63,7 @@ describe('wpTablePagination Directive', () => {beforeEach(async(() => {window.OpenProject = new OpenProject();+ (window as any).gon = { settings: { pagination: { per_page_options: [20, 50] } } };// noinspection JSIgnoredPromiseFromCallTestBed.configureTestingModule({@@ -90,7 +81,6 @@ describe('wpTablePagination Directive', () => {PathHelperService,WorkPackageViewPaginationService,HalResourceService,- ConfigurationService,ConfigurationDmService,IsolatedQuerySpace,I18nServicediff --git a/frontend/src/app/modules/attachments/attachments-upload/attachments-upload.component.ts b/frontend/src/app/modules/attachments/attachments-upload/attachments-upload.component.tsindex e14d8929f81..0f54901dc53 100644--- a/frontend/src/app/modules/attachments/attachments-upload/attachments-upload.component.ts+++ b/frontend/src/app/modules/attachments/attachments-upload/attachments-upload.component.ts@@ -65,9 +65,9 @@ export class AttachmentsUploadComponent implements OnInit {ngOnInit() {this.$element = jQuery(this.elementRef.nativeElement);- this.ConfigurationService.initialized.then(() =>- this.maxFileSize = this.ConfigurationService.maximumAttachmentFileSize- );+ this.ConfigurationService.api().then((settings:any) => {+ this.maxFileSize = settings.maximumAttachmentFileSize;+ });}public triggerFileInput(event:MouseEvent) {diff --git a/frontend/src/app/modules/common/config/configuration.service.ts b/frontend/src/app/modules/common/config/configuration.service.tsindex 77e55ec561d..708277c5bec 100644--- a/frontend/src/app/modules/common/config/configuration.service.ts+++ b/frontend/src/app/modules/common/config/configuration.service.ts@@ -26,97 +26,134 @@// See doc/COPYRIGHT.rdoc for more details.// +++import {PathHelperService} from 'core-app/modules/common/path-helper/path-helper.service';import {Injectable} from '@angular/core';import {I18nService} from 'core-app/modules/common/i18n/i18n.service';-import {ConfigurationDmService} from "core-app/modules/hal/dm-services/configuration-dm.service";-import {ConfigurationResource} from "core-app/modules/hal/resources/configuration-resource";+import {HttpClient} from '@angular/common/http';@Injectable()export class ConfigurationService {// fetches configuration from the ApiV3 endpoint// TODO: this currently saves the request between page reloads,// but could easily be stored in localStorage- private configuration:ConfigurationResource;- public initialized:Promise<Boolean>;+ private cache:any;+ private path:string = this.PathHelper.api.v3.configuration.toString();+ public settings = this.initSettings();- public constructor(readonly I18n:I18nService,- readonly configurationDm:ConfigurationDmService) {- this.initialized = this.loadConfiguration().then(() => true).catch(() => false);+ public constructor(readonly http:HttpClient,+ readonly PathHelper:PathHelperService,+ readonly I18n:I18nService) {++ }++ public fetchSettings () {+ return this.http.get<any>(this.path).toPromise();+ }++ public api() {+ return new Promise((resolve, reject) => {+ if (this.cache) {+ resolve(this.cache);+ } else {+ this.fetchSettings()+ .then((data:any) => {+ this.cache = data;+ resolve(data);+ })+ .catch(reject);+ }+ });+ }++ public initSettings() {++ var settings:any = {},+ defaults:any = {+ enabled_modules: [],+ display: {},+ user_preferences: {+ time_zone: '',+ others: {+ comments_sorting: 'asc',+ warn_on_leaving_unsaved: true,+ auto_hide_popups: false+ }+ }+ };++ var gon = (window as any).gon;+ if (gon !== undefined) {+ settings = gon.settings;+ }++ return _.merge(defaults, settings);+ }++ public displaySettingPresent(setting:any) {+ return this.settings.display.hasOwnProperty(setting) &&+ this.settings.display[setting] !== false;}public commentsSortedInDescendingOrder() {- return this.userPreference('commentSortDescending');+ return this.settings.user_preferences.others.comments_sorting === 'desc';}public warnOnLeavingUnsaved() {- return this.userPreference('warnOnLeavingUnsaved');+ return this.settings.user_preferences.others.warn_on_leaving_unsaved === true;}public autoHidePopups() {- return this.userPreference('autoHidePopups');+ return this.settings.user_preferences.others.auto_hide_popups === true;}public isTimezoneSet() {- return !!this.timezone();+ return this.settings.user_preferences.time_zone !== '';}public timezone() {- return this.userPreference('timeZone');- }-- public get maximumAttachmentFileSize() {- return this.systemPreference('maximumAttachmentFileSize');- }-- public get perPageOptions() {- return this.systemPreference('perPageOptions');+ return this.settings.user_preferences.time_zone;}public dateFormatPresent() {- return !!this.systemPreference('dateFormat');+ return this.displaySettingPresent('date_format') &&+ this.settings.display.date_format !== '';}public dateFormat() {- return this.systemPreference('dateFormat');+ return this.settings.display.date_format;}public timeFormatPresent() {- return !!this.systemPreference('timeFormat');+ return this.displaySettingPresent('time_format') &&+ this.settings.display.time_format !== '';}public timeFormat() {- return this.systemPreference('timeFormat');+ return this.settings.display.time_format;+ }++ public isModuleEnabled(module:string) {+ return this.settings.enabled_modules.indexOf(module) >= 0;}public startOfWeekPresent() {- return !!this.systemPreference('startOfWeek');+ return this.displaySettingPresent('start_of_week') &&+ this.settings.display.start_of_week !== '';}public startOfWeek() {if (this.startOfWeekPresent()) {- return this.systemPreference('startOfWeek');- } else if (I18n.locale === 'en') {+ return this.settings.display.start_of_week;+ }++ // This if/else statement is used because+ // jquery regionals have different start day for German locale+ if (I18n.locale === 'en') {return 1;} else if (I18n.locale === 'de') {- // This if/else statement is used because- // jquery regionals have different start day for German localereturn 0;- } else {- return null;}- }-- private loadConfiguration() {- return this.configurationDm.load().toPromise().then((configuration) => {- this.configuration = configuration;- });- }-- private userPreference(pref:string) {- return this.configuration.userPreferences[pref];- }- private systemPreference(pref:string) {- return this.configuration[pref];+ return '';}}diff --git a/lib/api/v3/configuration/configuration_representer.rb b/lib/api/v3/configuration/configuration_representer.rbindex 0b322052255..afdfbc65803 100644--- a/lib/api/v3/configuration/configuration_representer.rb+++ b/lib/api/v3/configuration/configuration_representer.rb@@ -52,20 +52,6 @@ module APIproperty :per_page_options,getter: ->(*) { per_page_options_array }- property :date_format,- exec_context: :decorator,- render_nil: true-- property :time_format,- exec_context: :decorator,- render_nil: true-- property :start_of_week,- getter: ->(*) {- Setting.start_of_week.to_i unless Setting.start_of_week.blank?- },- render_nil: true-property :user_preferences,embedded: true,exec_context: :decorator,@@ -81,58 +67,6 @@ module APIUserPreferences::UserPreferencesRepresenter.new(current_user.pref,current_user: current_user)end-- def date_format- reformated(Setting.date_format) do |directive|- case directive- when '%Y'- 'YYYY'- when '%y'- 'YY'- when '%m'- 'MM'- when '%B'- 'MMMM'- when '%b', '%h'- 'MMM'- when '%d'- 'DD'- when '%e'- 'D'- when '%j'- 'DDDD'- end- end- end-- def time_format- reformated(Setting.time_format) do |directive|- case directive- when '%H'- 'HH'- when '%k'- 'H'- when '%I'- 'hh'- when '%l'- 'h'- when '%P'- 'A'- when '%p'- 'a'- when '%M'- 'mm'- end- end- end-- def reformated(setting)- format = setting.gsub(/%\w/) do |directive|- yield directive- end-- format.blank? ? nil : format- endendendenddiff --git a/lib/open_project/client_preference_extractor.rb b/lib/open_project/client_preference_extractor.rbnew file mode 100644index 00000000000..0dcc609c52f--- /dev/null+++ b/lib/open_project/client_preference_extractor.rb@@ -0,0 +1,106 @@+#-- encoding: UTF-8+#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2017 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# 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 General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module OpenProject+ module ClientPreferenceExtractor+ def client_preferences+ gon.settings = {+ user_preferences: user_preferences,+ display: {+ date_format: momentjstify_date_format(Setting.date_format),+ time_format: momentjstify_time_format(Setting.time_format),+ start_of_week: Setting.start_of_week+ },+ pagination: {+ per_page_options: Setting.per_page_options_array+ }+ }+ end++ def user_preferences(user = User.current)+ pref = user.pref.clone++ pref[:comments_sorting] = user.pref.comments_sorting+ pref[:auto_hide_popups] = user.pref.auto_hide_popups?+ map_timezone_to_tz!(pref)+ end++ def map_timezone_to_tz!(pref)+ unless pref.time_zone.blank?+ pref.time_zone = ActiveSupport::TimeZone::MAPPING[pref.time_zone]+ end++ pref+ end++ def momentjstify_date_format(date_format)+ date_format.gsub(/%\w/) do |directive|+ case directive+ when '%Y'+ 'YYYY'+ when '%y'+ 'YY'+ when '%m'+ 'MM'+ when '%B'+ 'MMMM'+ when '%b', '%h'+ 'MMM'+ when '%d'+ 'DD'+ when '%e'+ 'D'+ when '%j'+ 'DDDD'+ end+ end+ end++ def momentjstify_time_format(time_format)+ time_format.gsub(/%\w/) do |directive|+ case directive+ when '%H'+ 'HH'+ when '%k'+ 'H'+ when '%I'+ 'hh'+ when '%l'+ 'h'+ when '%P'+ 'A'+ when '%p'+ 'a'+ when '%M'+ 'mm'+ end+ end+ end+ end+enddiff --git a/modules/boards/app/controllers/boards/boards_controller.rb b/modules/boards/app/controllers/boards/boards_controller.rbindex f31a61d4a6b..6294e61a1da 100644--- a/modules/boards/app/controllers/boards/boards_controller.rb+++ b/modules/boards/app/controllers/boards/boards_controller.rb@@ -1,5 +1,7 @@module ::Boardsclass BoardsController < BaseController+ include OpenProject::ClientPreferenceExtractor+before_action :find_optional_projectbefore_action :authorize@@ -23,6 +25,10 @@ module ::Boardsprivate+ def pass_gon+ gon.settings = client_preferences+ end+def authorize_work_package_permissionunless current_user.allowed_to?(:view_work_packages, @project, global: @project.nil?)deny_accessdiff --git a/modules/grids/app/controllers/grids/base_in_project_controller.rb b/modules/grids/app/controllers/grids/base_in_project_controller.rbindex 0a10e6ff760..cdf3c6d23d9 100644--- a/modules/grids/app/controllers/grids/base_in_project_controller.rb+++ b/modules/grids/app/controllers/grids/base_in_project_controller.rb@@ -1,9 +1,11 @@module ::Gridsclass BaseInProjectController < ::ApplicationController+ include OpenProject::ClientPreferenceExtractorbefore_action :find_project_by_project_idbefore_action :authorizedef show+ gon.settings = client_preferencesrender layout: 'angular'endenddiff --git a/modules/my_page/app/controllers/my_page/angular_controller.rb b/modules/my_page/app/controllers/my_page/angular_controller.rbindex 010cdf4606c..18f72b0b255 100644--- a/modules/my_page/app/controllers/my_page/angular_controller.rb+++ b/modules/my_page/app/controllers/my_page/angular_controller.rb@@ -30,8 +30,10 @@class MyPage::AngularController < ::ApplicationControllerbefore_action :require_login+ include OpenProject::ClientPreferenceExtractordef no_menu+ gon.settings = client_preferencesrender layout: 'no_menu'endenddiff --git a/spec/lib/api/v3/configuration/configuration_representer_spec.rb b/spec/lib/api/v3/configuration/configuration_representer_spec.rbindex c0f83f95fda..41e05976122 100644--- a/spec/lib/api/v3/configuration/configuration_representer_spec.rb+++ b/spec/lib/api/v3/configuration/configuration_representer_spec.rb@@ -86,132 +86,6 @@ describe ::API::V3::Configuration::ConfigurationRepresenter dois_expected.to be_json_eql([1, 50, 100].to_json).at_path('perPageOptions')end- context 'timeFormat' do- context 'with time format', with_settings: { time_format: '%I:%M %p' } do- it 'indicates the timeFormat' do- is_expected- .to be_json_eql('hh:mm a'.to_json)- .at_path('timeFormat')- end- end-- context 'with time format', with_settings: { time_format: '%H:%M' } do- it 'indicates the timeFormat' do- is_expected- .to be_json_eql('HH:mm'.to_json)- .at_path('timeFormat')- end- end-- context 'with a time format', with_settings: { time_format: '' } do- it 'indicates the timeFormat' do- is_expected- .to be_json_eql(nil.to_json)- .at_path('timeFormat')- end- end- end-- context 'dateFormat' do- context 'without a date format', with_settings: { date_format: '' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql(nil.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%Y-%m-%d)', with_settings: { date_format: '%Y-%m-%d' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('YYYY-MM-DD'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%d/%m/%Y)', with_settings: { date_format: '%Y-%m-%d' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('YYYY-MM-DD'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%d.%m.%Y)', with_settings: { date_format: '%d.%m.%Y' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('DD.MM.YYYY'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%d-%m-%Y)', with_settings: { date_format: '%d-%m-%Y' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('DD-MM-YYYY'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%m/%d/%Y)', with_settings: { date_format: '%m/%d/%Y' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('MM/DD/YYYY'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%d %b %Y)', with_settings: { date_format: '%d %b %Y' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('DD MMM YYYY'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%d %B %Y)', with_settings: { date_format: '%d %B %Y' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('DD MMMM YYYY'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%b %d, %Y)', with_settings: { date_format: '%b %d, %Y' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('MMM DD, YYYY'.to_json)- .at_path('dateFormat')- end- end-- context 'with date format (%B %d, %Y)', with_settings: { date_format: '%B %d, %Y' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql('MMMM DD, YYYY'.to_json)- .at_path('dateFormat')- end- end- end-- context 'startOfWeek' do- context 'without a setting', with_settings: { start_of_week: '' } do- it 'is null' do- is_expected- .to be_json_eql(nil.to_json)- .at_path('startOfWeek')- end- end-- context 'with `Monday` being set', with_settings: { start_of_week: '1' } do- it 'indicates the dateFormat' do- is_expected- .to be_json_eql(1.to_json)- .at_path('startOfWeek')- end- end- end-describe '_embedded' docontext 'userPreferences' docontext 'if embedding' dodiff --git a/spec/lib/open_project/client_preference_extractor_spec.rb b/spec/lib/open_project/client_preference_extractor_spec.rbnew file mode 100644index 00000000000..e6f914b61ed--- /dev/null+++ b/spec/lib/open_project/client_preference_extractor_spec.rb@@ -0,0 +1,79 @@+#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2017 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# 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 General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'++describe OpenProject::ClientPreferenceExtractor do+ let(:extractor) { (Class.new { include OpenProject::ClientPreferenceExtractor }).new }++ describe 'user preferences' do+ let(:user) { FactoryBot.build(:user) }++ shared_examples_for 'preference with timezone' do+ before do+ allow(user).to receive(:pref) { pref }+ end++ subject { extractor.user_preferences(user) }++ it { expect(subject).not_to be_nil }++ it { expect(subject.time_zone).to eq(time_zone) }+ end++ context 'without timezone' do+ let(:pref) { UserPreference.new(time_zone: nil) }++ it_behaves_like 'preference with timezone' do+ let(:time_zone) { nil }+ end+ end++ context 'with timezone' do+ let(:pref) { UserPreference.new(time_zone: 'Berlin') }++ it_behaves_like 'preference with timezone' do+ let(:time_zone) { 'Europe/Berlin' }+ end+ end+ end++ describe 'date format' do+ let(:ruby_date_format) { '%Y-%y-%m-%B-%b-%h ? %d:%e:%j' }+ let(:expected_date_format) { 'YYYY-YY-MM-MMMM-MMM-MMM ? DD:D:DDDD' }++ it { expect(extractor.momentjstify_date_format(ruby_date_format)).to eq(expected_date_format) }+ end++ describe 'time format' do+ let(:ruby_time_format) { '%H:%k:%I:%l ? %P+%p+%M' }+ let(:expected_time_format) { 'HH:H:hh:h ? A+a+mm' }++ it { expect(extractor.momentjstify_time_format(ruby_time_format)).to eq(expected_time_format) }+ end+end