Skip to content

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

Feature/delayed bcf export (#8275)

ulferts4cb0d0ff9198
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index caa740d6bf1..ab3b3b617c4 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -261,6 +261,7 @@ class ApplicationController < ActionController::Base
def reset_i18n_fallbacks
return if I18n.fallbacks.defaults == (fallbacks = [I18n.default_locale] + Setting.available_languages.map(&:to_sym))
+
I18n.fallbacks = nil
I18n.fallbacks.defaults = fallbacks
end
diff --git a/app/controllers/work_packages/exports_controller.rb b/app/controllers/work_packages/exports_controller.rb
new file mode 100644
index 00000000000..cf0ca3c2622
--- /dev/null
+++ b/app/controllers/work_packages/exports_controller.rb
@@ -0,0 +1,56 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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.
+#++
+
+class WorkPackages::ExportsController < ApplicationController
+ self._model_object = WorkPackages::Export
+
+ before_action :find_model_object,
+ :authorize_current_user
+
+ def show
+ if @export.attachments.first
+ redirect_to attachment_content_path
+ else
+ head 202
+ end
+ end
+
+ private
+
+ def authorize_current_user
+ deny_access(not_found: true) unless @export.visible?(current_user)
+ end
+
+ def attachment_content_path
+ # Not including the API PathHelper here as it messes up error rendering probably due to it
+ # including the url helper again.
+ ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(@export.attachments.first.id)
+ end
+end
diff --git a/app/controllers/work_packages/moves_controller.rb b/app/controllers/work_packages/moves_controller.rb
index dba3375f07e..b66d0862846 100644
--- a/app/controllers/work_packages/moves_controller.rb
+++ b/app/controllers/work_packages/moves_controller.rb
@@ -1,4 +1,5 @@
#-- encoding: UTF-8
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
diff --git a/app/controllers/work_packages_controller.rb b/app/controllers/work_packages_controller.rb
index b63b06fe4b1..7f291321b60 100644
--- a/app/controllers/work_packages_controller.rb
+++ b/app/controllers/work_packages_controller.rb
@@ -83,10 +83,12 @@ class WorkPackagesController < ApplicationController
protected
def export_list(mime_type)
- exporter = WorkPackage::Exporter.for_list(mime_type)
- exporter.list(@query, params) do |export|
- render_export_response export, fallback_path: index_redirect_path
- end
+ export_storage = WorkPackages::Exports::ScheduleService
+ .new(user: current_user)
+ .call(query: @query, mime_type: mime_type, params: params)
+ .result
+
+ redirect_to work_packages_export_path(export_storage.id)
end
def export_single(mime_type)
@@ -115,16 +117,6 @@ class WorkPackagesController < ApplicationController
if export.error?
flash[:error] = export.message
redirect_back(fallback_location: fallback_path)
- elsif export.content.is_a? File
- # browsers should not try to guess the content-type
- response.headers['X-Content-Type-Options'] = 'nosniff'
-
- # TODO avoid reading the file in memory here again
- # but currently the tempfile gets removed in between
- send_data(export.content.read,
- type: export.mime_type,
- disposition: 'attachment',
- filename: export.title)
else
send_data(export.content,
type: export.mime_type,
@@ -146,16 +138,16 @@ class WorkPackagesController < ApplicationController
end
def supported_export_formats
- %w[atom rss] + WorkPackage::Exporter.list_formats.map(&:to_s)
+ %w[atom] + WorkPackage::Exporter.list_formats.map(&:to_s)
end
def load_and_validate_query
@query ||= retrieve_query
unless @query.valid?
- # Ensure outputting a html response
+ # Ensure outputting an html response
request.format = 'html'
- return render_400(message: @query.errors.full_messages.join(". "))
+ render_400(message: @query.errors.full_messages.join(". "))
end
rescue ActiveRecord::RecordNotFound
render_404
diff --git a/app/models/work_package/exporter/csv.rb b/app/models/work_package/exporter/csv.rb
index 5302151a946..208b44660e5 100644
--- a/app/models/work_package/exporter/csv.rb
+++ b/app/models/work_package/exporter/csv.rb
@@ -57,7 +57,7 @@ class WorkPackage::Exporter::CSV < WorkPackage::Exporter::Base
private
def success(serialized)
- WorkPackage::Exporter::Success
+ WorkPackage::Exporter::Result::Success
.new format: :csv,
title: title,
content: serialized,
diff --git a/app/models/work_package/exporter/result.rb b/app/models/work_package/exporter/result.rb
index 740c09510f6..3e28bccba14 100644
--- a/app/models/work_package/exporter/result.rb
+++ b/app/models/work_package/exporter/result.rb
@@ -32,4 +32,8 @@ class WorkPackage::Exporter::Result
def error?
false
end
+
+ def delayed?
+ false
+ end
end
diff --git a/app/models/work_package/exporter/error.rb b/app/models/work_package/exporter/result/error.rb
similarity index 94%
rename from app/models/work_package/exporter/error.rb
rename to app/models/work_package/exporter/result/error.rb
index 550f909c507..4c14e6b279e 100644
--- a/app/models/work_package/exporter/error.rb
+++ b/app/models/work_package/exporter/result/error.rb
@@ -28,7 +28,7 @@
# See docs/COPYRIGHT.rdoc for more details.
#++
-class WorkPackage::Exporter::Error < WorkPackage::Exporter::Result
+class WorkPackage::Exporter::Result::Error < WorkPackage::Exporter::Result
attr_accessor :message
def initialize(message)
diff --git a/app/models/work_package/exporter/success.rb b/app/models/work_package/exporter/result/success.rb
similarity index 95%
rename from app/models/work_package/exporter/success.rb
rename to app/models/work_package/exporter/result/success.rb
index 2718d4a2ea2..006f37ea55c 100644
--- a/app/models/work_package/exporter/success.rb
+++ b/app/models/work_package/exporter/result/success.rb
@@ -28,7 +28,7 @@
# See docs/COPYRIGHT.rdoc for more details.
#++
-class WorkPackage::Exporter::Success < WorkPackage::Exporter::Result
+class WorkPackage::Exporter::Result::Success < WorkPackage::Exporter::Result
attr_accessor :format,
:title,
:content,
diff --git a/app/models/work_package/pdf_export/common.rb b/app/models/work_package/pdf_export/common.rb
index 1044c43eff8..282e337764b 100644
--- a/app/models/work_package/pdf_export/common.rb
+++ b/app/models/work_package/pdf_export/common.rb
@@ -51,7 +51,7 @@ module WorkPackage::PDFExport::Common
end
def success(content)
- WorkPackage::Exporter::Success
+ WorkPackage::Exporter::Result::Success
.new format: :csv,
title: title,
content: content,
diff --git a/app/models/work_packages/export.rb b/app/models/work_packages/export.rb
new file mode 100644
index 00000000000..52be14492c7
--- /dev/null
+++ b/app/models/work_packages/export.rb
@@ -0,0 +1,14 @@
+class WorkPackages::Export < ApplicationRecord
+ self.table_name = 'work_package_exports'
+
+ belongs_to :user
+
+ acts_as_attachable view_permission: :export_work_packages,
+ add_permission: :export_work_packages,
+ delete_permission: :export_work_packages,
+ only_user_allowed: true
+
+ def visible?(user)
+ user_id == user.id
+ end
+end
diff --git a/app/services/work_packages/exports/schedule_service.rb b/app/services/work_packages/exports/schedule_service.rb
new file mode 100644
index 00000000000..36082926e4e
--- /dev/null
+++ b/app/services/work_packages/exports/schedule_service.rb
@@ -0,0 +1,63 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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.
+#++
+
+class WorkPackages::Exports::ScheduleService
+ attr_accessor :user
+
+ def initialize(user:)
+ self.user = user
+ end
+
+ def call(query:, mime_type:, params: {})
+ export_storage = WorkPackages::Export.create user: user
+ schedule_export(export_storage, mime_type, params, query)
+
+ ServiceResult.new success: true, result: export_storage
+ end
+
+ private
+
+ def schedule_export(export_storage, mime_type, params, query)
+ WorkPackages::Exports::ExportJob.perform_later(export: export_storage,
+ mime_type: mime_type,
+ options: params,
+ query: serialize_query(query))
+ end
+
+ def serialize_query(query)
+ if query.persisted?
+ query
+ else
+ query.attributes.tap do |attributes|
+ attributes['filters'] = Queries::WorkPackages::FilterSerializer.dump(query.attributes['filters'])
+ end
+ end
+ end
+end
diff --git a/app/workers/scm/delete_local_repository_job.rb b/app/workers/scm/delete_local_repository_job.rb
index f0e5bf6707a..e4f6f1023da 100644
--- a/app/workers/scm/delete_local_repository_job.rb
+++ b/app/workers/scm/delete_local_repository_job.rb
@@ -1,4 +1,5 @@
#-- encoding: UTF-8
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2020 the OpenProject GmbH
diff --git a/app/workers/work_packages/exports/cleanup_outdated_job.rb b/app/workers/work_packages/exports/cleanup_outdated_job.rb
new file mode 100644
index 00000000000..bcd4e36299d
--- /dev/null
+++ b/app/workers/work_packages/exports/cleanup_outdated_job.rb
@@ -0,0 +1,53 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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.
+#++
+
+class WorkPackages::Exports::CleanupOutdatedJob < ApplicationJob
+ queue_with_priority :low
+
+ def self.perform_after_grace
+ set(wait: OpenProject::Configuration.attachments_grace_period.minutes).perform_later
+ end
+
+ def perform
+ WorkPackages::Export
+ .where(too_old)
+ .destroy_all
+ end
+
+ private
+
+ def too_old
+ table = WorkPackages::Export.arel_table
+
+ table[:created_at]
+ .lteq(Time.now - OpenProject::Configuration.attachments_grace_period.minutes)
+ .to_sql
+ end
+end
diff --git a/app/workers/work_packages/exports/export_job.rb b/app/workers/work_packages/exports/export_job.rb
new file mode 100644
index 00000000000..4f676a34e36
--- /dev/null
+++ b/app/workers/work_packages/exports/export_job.rb
@@ -0,0 +1,68 @@
+module WorkPackages
+ module Exports
+ class ExportJob < ::ApplicationJob
+ def perform(export:, mime_type:, query:, options:)
+ User.execute_as export.user do
+ export_work_packages(export, mime_type, query, options)
+
+ schedule_cleanup
+ end
+ end
+
+ private
+
+ def export_work_packages(export, mime_type, query_props, options)
+ exporter = WorkPackage::Exporter.for_list(mime_type)
+ exporter.list(query(query_props), options) do |export_result|
+ if export_result.error?
+ raise export_result.message
+ elsif export_result.content.is_a? File
+ store_attachment(export, export_result.content)
+ else
+ store_from_string(export, export_result)
+ end
+ end
+ end
+
+ def schedule_cleanup
+ ::WorkPackages::Exports::CleanupOutdatedJob.perform_after_grace
+ end
+
+ def query(query_props)
+ if query_props.is_a?(Query)
+ query_props
+ else
+ filters = query_props.delete('filters')
+ filters = Queries::WorkPackages::FilterSerializer.load(filters)
+
+ Query.new(query_props).tap do |q|
+ q.filters = filters
+ q.set_context
+ end
+ end
+ end
+
+ def store_from_string(export, export_result)
+ with_tempfile(export_result.title, export_result.content) do |file|
+ store_attachment(export, file)
+ end
+ end
+
+ def with_tempfile(title, content)
+ name_parts = [title[0..title.rindex('.') - 1], title[title.rindex('.')..-1]]
+
+ Tempfile.create(name_parts, encoding: content.encoding) do |file|
+ file.write content
+
+ yield file
+ end
+ end
+
+ def store_attachment(storage, file)
+ Attachments::CreateService
+ .new(storage, author: storage.user)
+ .call(uploaded_file: file, description: '')
+ end
+ end
+ end
+end
diff --git a/config/locales/js-en.yml b/config/locales/js-en.yml
index d34975ec53b..147104e55d3 100644
--- a/config/locales/js-en.yml
+++ b/config/locales/js-en.yml
@@ -362,6 +362,7 @@ en:
label_expand_all: "Expand all"
label_expand_project_menu: "Expand project menu"
label_export: "Export"
+ label_export_preparing: "The export is being prepared and will be downloaded shortly."
label_filename: "File"
label_filesize: "Size"
label_general: "General"
diff --git a/config/routes.rb b/config/routes.rb
index 41bda7036c5..734b9967283 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -409,6 +409,7 @@ OpenProject::Application.routes.draw do
namespace :work_packages do
match 'auto_complete' => 'auto_completes#index', via: %i[get post]
+ resources :exports, only: [:show]
resources :calendar, controller: 'calendars', only: [:index]
resource :bulk, controller: 'bulk', only: %i[edit update destroy]
# FIXME: this is kind of evil!! We need to remove this soonest and
@@ -422,8 +423,6 @@ OpenProject::Application.routes.draw do
end
resources :work_packages, only: [:index] do
- get :column_data, on: :collection # TODO move to API
-
# move bulk of wps
get 'move/new' => 'work_packages/moves#new', on: :collection, as: 'new_move'
post 'move' => 'work_packages/moves#create', on: :collection, as: 'move'
@@ -443,7 +442,8 @@ OpenProject::Application.routes.draw do
get '/' => 'work_packages#index', on: :collection, as: 'index'
get '/create_new' => 'work_packages#index', on: :collection, as: 'new_split'
get '/new' => 'work_packages#index', on: :collection, as: 'new', state: 'new'
- get '(/*state)' => 'work_packages#show', on: :member, as: ''
+ # We do not want to match the work package export routes
+ get '(/*state)' => 'work_packages#show', on: :member, as: '', constraints: { id: /\d+/ }
get '/edit' => 'work_packages#show', on: :member, as: 'edit'
end
diff --git a/db/migrate/20200415131633_add_work_package_exports.rb b/db/migrate/20200415131633_add_work_package_exports.rb
new file mode 100644
index 00000000000..62c896ca6d5
--- /dev/null
+++ b/db/migrate/20200415131633_add_work_package_exports.rb
@@ -0,0 +1,9 @@
+class AddWorkPackageExports < ActiveRecord::Migration[6.0]
+ def change
+ create_table :work_package_exports do |t|
+ t.references :user
+
+ t.timestamps
+ end
+ end
+end
diff --git a/frontend/src/app/components/modals/export-modal/wp-table-export.modal.html b/frontend/src/app/components/modals/export-modal/wp-table-export.modal.html
index 73f5389880b..3d708146858 100644
--- a/frontend/src/app/components/modals/export-modal/wp-table-export.modal.html
+++ b/frontend/src/app/components/modals/export-modal/wp-table-export.modal.html
@@ -1,6 +1,5 @@
<div class="op-modal--portal ">
- <div class="op-modal--modal-container wp-table--configuration-modal loading-indicator--location"
- data-indicator-name="modal"
+ <div class="op-modal--modal-container wp-table--configuration-modal"
tabindex="0">
<div class="op-modal--modal-header">
<a class="op-modal--modal-close-button">
@@ -14,14 +13,29 @@
<h3 [textContent]="text.title"></h3>
- <ul *ngIf="exportOptions" class="export-options">
+ <ul *ngIf="exportOptions" class="export-options" [ngClass]="{'-hidden': isLoading}">
<li *ngFor="let option of exportOptions">
<a [attr.href]="option.url"
+ (click)="triggerByLink(option.url, $event)"
id="export-{{ option.identifier }}">
<op-icon icon-classes="icon-export-{{ option.identifier }} icon-big"></op-icon>
<span class="export-label" [textContent]="option.label"></span>
</a>
</li>
</ul>
+ <div *ngIf="isLoading">
+ <div class="loading-indicator--location"
+ data-indicator-name="modal">
+ </div>
+ <div [textContent]="text.exportPreparing"></div>
+ </div>
+
+ <a #downloadLink
+ id="download-link"
+ [title]="'Export'"
+ class="button"
+ download
+ [attr.href]="downloadHref">
+ </a>
</div>
</div>
diff --git a/frontend/src/app/components/modals/export-modal/wp-table-export.modal.sass b/frontend/src/app/components/modals/export-modal/wp-table-export.modal.sass
new file mode 100644
index 00000000000..c6677406300
--- /dev/null
+++ b/frontend/src/app/components/modals/export-modal/wp-table-export.modal.sass
@@ -0,0 +1,9 @@
+#download-link
+ display: none
+
+.loading-indicator--location
+ height: 220px
+
+.export-options
+ &.-hidden
+ display: none
diff --git a/frontend/src/app/components/modals/export-modal/wp-table-export.modal.ts b/frontend/src/app/components/modals/export-modal/wp-table-export.modal.ts
index bb377edfe55..1cbc5851f99 100644
--- a/frontend/src/app/components/modals/export-modal/wp-table-export.modal.ts
+++ b/frontend/src/app/components/modals/export-modal/wp-table-export.modal.ts
@@ -1,23 +1,44 @@
-import {ChangeDetectorRef, Component, ElementRef, Inject, OnInit} from '@angular/core';
+import {ChangeDetectorRef, Component, ElementRef, Inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {OpModalLocalsMap} from 'core-components/op-modals/op-modal.types';
import {WorkPackageViewColumnsService} from 'core-app/modules/work_packages/routing/wp-view-base/view-services/wp-view-columns.service';
import {OpModalComponent} from 'core-components/op-modals/op-modal.component';
import {IsolatedQuerySpace} from "core-app/modules/work_packages/query-space/isolated-query-space";
-import {UrlParamsHelperService} from "core-components/wp-query/url-params-helper";
import {WorkPackageCollectionResource} from "core-app/modules/hal/resources/wp-collection-resource";
import {HalLink} from "core-app/modules/hal/hal-link/hal-link";
import {I18nService} from "core-app/modules/common/i18n/i18n.service";
import {OpModalLocalsToken} from "core-components/op-modals/op-modal.service";
import * as URI from 'urijs';
+import {HttpClient, HttpErrorResponse, HttpResponse} from '@angular/common/http';
+import {
+ LoadingIndicatorService,
+ withDelayedLoadingIndicator
+} from "core-app/modules/common/loading-indicator/loading-indicator.service";
+import {switchMap, takeWhile} from 'rxjs/operators';
+import {interval, Observable, Subscription} from 'rxjs';
+import {NotificationsService} from "core-app/modules/common/notifications/notifications.service";
interface ExportLink extends HalLink {
identifier:string;
}
+/*
+Modal for exporting work packages to different formats. The user may choose from a variety of formats (e.g. PDF and CSV).
+
+The backend may choose to provide the export right away (synchronously) or delayed. In the later case, the modal will poll the
+backend until the export is done.
+Because the modal has to deal with both cases, without knowing upfront whether the download will be delayed or not, it needs
+to treat every download expecting it to be delayed. Because of this, the modal cannot simply provide download hrefs which would
+ allow the browser to download the export but rather has to first check whether an export is delayed or not, and if it is delayed,
+ it has to wait until the export is ready. Because of the necessary check, the modal has a hidden link that it clicks on to perform
+ the actual download once the export is ready (delayed or not).
+
+The modal might also be used to only display the progress of an export. This will happen if a link for exporting is provided via the locals.
+ */
@Component({
- templateUrl: './wp-table-export.modal.html'
+ templateUrl: './wp-table-export.modal.html',
+ styleUrls: ['./wp-table-export.modal.sass']
})
-export class WpTableExportModal extends OpModalComponent implements OnInit {
+export class WpTableExportModal extends OpModalComponent implements OnInit, OnDestroy {
/* Close on escape? */
public closeOnEscape = true;
@@ -31,24 +52,43 @@ export class WpTableExportModal extends OpModalComponent implements OnInit {
public text = {
title: this.I18n.t('js.label_export'),
closePopup: this.I18n.t('js.close_popup_title'),
+ exportPreparing: this.I18n.t('js.label_export_preparing')
};
+ public downloadHref:string;
+ public isLoading = false;
+ private subscription?:Subscription;
+ private finished?:Function;
+
+ @ViewChild('downloadLink') downloadLink:ElementRef;
+
constructor(@Inject(OpModalLocalsToken) public locals:OpModalLocalsMap,
readonly I18n:I18nService,
readonly elementRef:ElementRef,
- readonly UrlParamsHelper:UrlParamsHelperService,
readonly querySpace:IsolatedQuerySpace,
readonly cdRef:ChangeDetectorRef,
- readonly wpTableColumns:WorkPackageViewColumnsService) {
+ readonly httpClient:HttpClient,
+ readonly wpTableColumns:WorkPackageViewColumnsService,
+ readonly loadingIndicator:LoadingIndicatorService,
+ readonly notifications:NotificationsService) {
super(locals, cdRef, elementRef);
}
ngOnInit() {
super.ngOnInit();
- this.querySpace.results
- .valuesPromise()
- .then((results) => this.exportOptions = this.buildExportOptions(results!));
+ if (this.locals.link) {
+ this.downloadSwitched(this.locals.link);
+ } else {
+ this.querySpace.results
+ .valuesPromise()
+ .then((results) => this.exportOptions = this.buildExportOptions(results!));
+ }
+ }
+
+ ngOnDestroy() {
+ super.ngOnDestroy();
+ this.safeUnsubscribe();
}
private buildExportOptions(results:WorkPackageCollectionResource) {
@@ -63,6 +103,58 @@ export class WpTableExportModal extends OpModalComponent implements OnInit {
});
}
+ private triggerByLink(url:string, event:MouseEvent) {
+ event.preventDefault();
+
+ this.downloadSwitched(url);
+ }
+
+ private downloadSwitched(url:string) {
+ this
+ .performRequest(url)
+ .subscribe(
+ (data) => {
+ if (data.status === 200) {
+ this.download(data.url!);
+ }
+
+ if (data.status === 202) {
+ this.pollUntilDownload(data.url!);
+ }
+ },
+ (error:HttpErrorResponse) => this.handleError(error));
+ }
+
+ private pollUntilDownload(url:string) {
+ this.isLoading = true;
+
+ interval(1000)
+ .pipe(
+ switchMap(() => this.performRequest(url)),
+ takeWhile(response => response.status === 202, true),
+ withDelayedLoadingIndicator(this.loadingIndicator.getter('modal')),
+ ).subscribe(
+ response => {
+ if (response.status === 200) {
+ this.download(response.url!);
+ }
+ },
+ error => this.handleError(error),
+ () => this.isLoading = false
+ );
+ }
+
+ private performRequest(url:string):Observable<HttpResponse<any>> {
+ return this
+ .httpClient
+ .get(url, { observe: 'response', responseType: 'text' });
+ }
+
+ private handleError(error:HttpErrorResponse) {
+ this.isLoading = false;
+ this.notifications.addError(error.message || this.I18n.t('js.error.internal'));
+ }
+
private addColumnsToHref(href:string) {
let columns = this.wpTableColumns.getColumns();
@@ -82,4 +174,20 @@ export class WpTableExportModal extends OpModalComponent implements OnInit {
return jQuery('#work-packages-settings-button');
}
+ private download(url:string) {
+ this.downloadHref = url;
+ if (this.finished) {
+ this.finished();
+ }
+ setTimeout(() => {
+ this.downloadLink.nativeElement.click();
+ this.service.close();
+ });
+ }
+
+ private safeUnsubscribe() {
+ if (this.subscription) {
+ this.subscription.unsubscribe();
+ }
+ }
}
diff --git a/frontend/src/app/modules/bim/ifc_models/toolbar/import-export-bcf/bcf-export-button.component.ts b/frontend/src/app/modules/bim/ifc_models/toolbar/import-export-bcf/bcf-export-button.component.ts
index 83ce495c4b5..44cc6e55417 100644
--- a/frontend/src/app/modules/bim/ifc_models/toolbar/import-export-bcf/bcf-export-button.component.ts
+++ b/frontend/src/app/modules/bim/ifc_models/toolbar/import-export-bcf/bcf-export-button.component.ts
@@ -26,7 +26,7 @@
// See docs/COPYRIGHT.rdoc for more details.
// ++
-import {Component, OnDestroy, OnInit} from '@angular/core';
+import {Component, OnDestroy, OnInit, Injector} from '@angular/core';
import {I18nService} from 'core-app/modules/common/i18n/i18n.service';
import {CurrentProjectService} from "core-components/projects/current-project.service";
import {BcfPathHelperService} from "core-app/modules/bim/bcf/helper/bcf-path-helper.service";
@@ -35,13 +35,15 @@ import {QueryResource} from "core-app/modules/hal/resources/query-resource";
import {UrlParamsHelperService} from "core-components/wp-query/url-params-helper";
import {StateService} from "@uirouter/core";
import {UntilDestroyedMixin} from "core-app/helpers/angular/until-destroyed.mixin";
+import {WpTableExportModal} from "core-components/modals/export-modal/wp-table-export.modal";
+import {OpModalService} from "core-components/op-modals/op-modal.service";
@Component({
template: `
<a [title]="text.export"
class="button export-bcf-button"
- download
- [attr.href]="exportLink">
+ [attr.href]="exportLink"
+ (click)="showDelayedExport($event)">
<op-icon icon-classes="button--icon icon-export"></op-icon>
<span class="button--text"> {{text.export}} </span>
</a>
@@ -60,6 +62,8 @@ export class BcfExportButtonComponent extends UntilDestroyedMixin implements OnI
readonly bcfPathHelper:BcfPathHelperService,
readonly querySpace:IsolatedQuerySpace,
readonly queryUrlParamsHelper:UrlParamsHelperService,
+ readonly opModalService:OpModalService,
+ readonly injector:Injector,
readonly state:StateService) {
super();
}
@@ -81,4 +85,9 @@ export class BcfExportButtonComponent extends UntilDestroyedMixin implements OnI
);
});
}
+
+ public showDelayedExport(event:any) {
+ this.opModalService.show(WpTableExportModal, this.injector, { link: this.exportLink });
+ event.preventDefault();
+ }
}
diff --git a/frontend/src/app/modules/common/loading-indicator/loading-indicator.service.ts b/frontend/src/app/modules/common/loading-indicator/loading-indicator.service.ts
index eacee6e5fb7..ea2f2eb0ea6 100644
--- a/frontend/src/app/modules/common/loading-indicator/loading-indicator.service.ts
+++ b/frontend/src/app/modules/common/loading-indicator/loading-indicator.service.ts
@@ -47,6 +47,21 @@ export function withLoadingIndicator<T>(indicator:LoadingIndicator, delayStopTim
};
}
+export function withDelayedLoadingIndicator<T>(indicator:() => LoadingIndicator):(source:Observable<T>) => Observable<T> {
+ return (source$:Observable<T>) => {
+ setTimeout(() => indicator().start());
+
+ return source$.pipe(
+ tap(
+ () => undefined,
+ () => indicator().stop(),
+ () => indicator().stop()
+ )
+ );
+ };
+}
+
+
export class LoadingIndicator {
private indicatorTemplate:string =
@@ -61,7 +76,8 @@ export class LoadingIndicator {
</div>
`;
- constructor(public indicator:JQuery) {}
+ constructor(public indicator:JQuery) {
+ }
public set promise(promise:Promise<unknown>) {
this.start();
@@ -93,9 +109,23 @@ export class LoadingIndicator {
export class LoadingIndicatorService {
// Provide shortcut to the primarily used indicators
- public get table() { return this.indicator('table'); }
- public get wpDetails() { return this.indicator('wpDetails'); }
- public get modal() { return this.indicator('modal'); }
+ public get table() {
+ return this.indicator('table');
+ }
+
+ public get wpDetails() {
+ return this.indicator('wpDetails');
+ }
+
+ public get modal() {
+ return this.indicator('modal');
+ }
+
+ // Returns a getter function to an indicator
+ // in case the indicator is shown conditionally
+ public getter(name:string):() => LoadingIndicator {
+ return this.indicator.bind(this, name);
+ }
// Return an indicator by name or element
public indicator(indicator:string|JQuery):LoadingIndicator {
diff --git a/frontend/src/app/modules/work_packages/openproject-work-packages.module.ts b/frontend/src/app/modules/work_packages/openproject-work-packages.module.ts
index 05b36e7d4d8..7d2ad18ccbb 100644
--- a/frontend/src/app/modules/work_packages/openproject-work-packages.module.ts
+++ b/frontend/src/app/modules/work_packages/openproject-work-packages.module.ts
@@ -169,7 +169,6 @@ import {WorkPackageViewPageComponent} from "core-app/modules/work_packages/routi
import {WorkPackageSettingsButtonComponent} from "core-components/wp-buttons/wp-settings-button/wp-settings-button.component";
import {BackButtonComponent} from "core-app/modules/common/back-routing/back-button.component";
-
@NgModule({
imports: [
// Commons
diff --git a/lib/api/v3/attachments/attachment_representer.rb b/lib/api/v3/attachments/attachment_representer.rb
index b6722ab431b..f561683a859 100644
--- a/lib/api/v3/attachments/attachment_representer.rb
+++ b/lib/api/v3/attachments/attachment_representer.rb
@@ -50,7 +50,7 @@ module API
def self.associated_container_getter
->(*) do
- next unless embed_links
+ next unless embed_links && container_representer
container_representer
.new(represented.container, current_user: current_user)
@@ -59,6 +59,8 @@ module API
def self.associated_container_link
->(*) do
+ return nil unless v3_container_name == 'nil_class' || api_v3_paths.respond_to?(v3_container_name)
+
::API::Decorators::LinkObject
.new(represented,
path: v3_container_name,
@@ -123,6 +125,8 @@ module API
name = v3_container_name.camelcase
"::API::V3::#{name.pluralize}::#{name}Representer".constantize
+ rescue NameError
+ nil
end
def v3_container_name
diff --git a/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb b/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb
index 34a3e471726..f0ea9a58d2e 100644
--- a/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb
+++ b/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb
@@ -70,6 +70,10 @@ module Redmine
extract_tsv: attachable_extract_tsv_option(options)
}
+ # Because subclasses can have their own attachable_options,
+ # we ensure those are also listed.
+ Redmine::Acts::Attachable.attachables.push(self) unless Redmine::Acts::Attachable.attachables.include?(self)
+
options.except!(:view_permission,
:delete_permission,
:add_on_new_permission,
diff --git a/modules/bim/lib/open_project/bim/bcf_xml/exporter.rb b/modules/bim/lib/open_project/bim/bcf_xml/exporter.rb
index 13b886e7a0c..dac1cc47057 100644
--- a/modules/bim/lib/open_project/bim/bcf_xml/exporter.rb
+++ b/modules/bim/lib/open_project/bim/bcf_xml/exporter.rb
@@ -13,10 +13,6 @@ module OpenProject::Bim::BcfXml
User.current
end
- def work_packages
- super.includes(journals: [:bcf_comment], bcf_issue: [:comments, { viewpoints: :attachments }])
- end
-
def list
Dir.mktmpdir do |dir|
files = create_bcf! dir
@@ -41,7 +37,7 @@ module OpenProject::Bim::BcfXml
end
def success(zip)
- WorkPackage::Exporter::Success
+ WorkPackage::Exporter::Result::Success
.new format: :xls,
content: zip,
title: bcf_filename,
diff --git a/modules/bim/spec/bcf/bcf_xml/exporter_spec.rb b/modules/bim/spec/bcf/bcf_xml/exporter_spec.rb
index c07fa0a07f2..d40d52646be 100644
--- a/modules/bim/spec/bcf/bcf_xml/exporter_spec.rb
+++ b/modules/bim/spec/bcf/bcf_xml/exporter_spec.rb
@@ -29,14 +29,14 @@
require 'spec_helper'
describe ::OpenProject::Bim::BcfXml::Exporter do
- let(:query) { FactoryBot.build(:global_query)}
+ let(:query) { FactoryBot.build(:global_query) }
let(:work_package) { FactoryBot.create :work_package }
let(:admin) { FactoryBot.create(:admin) }
let(:current_user) { admin }
before do
work_package
- allow(User).to receive(:current).and_return current_user
+ login_as current_user
end
subject { described_class.new(query) }
diff --git a/modules/bim/spec/controllers/work_packages_controller_spec.rb b/modules/bim/spec/controllers/work_packages_controller_spec.rb
new file mode 100644
index 00000000000..a2eb798a576
--- /dev/null
+++ b/modules/bim/spec/controllers/work_packages_controller_spec.rb
@@ -0,0 +1,78 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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 WorkPackagesController, type: :controller do
+ before do
+ login_as current_user
+ end
+
+ let(:stub_project) { FactoryBot.build_stubbed(:project, identifier: 'test_project', public: false) }
+ let(:current_user) { FactoryBot.build_stubbed(:user) }
+ let(:work_packages) { [FactoryBot.build_stubbed(:stubbed_work_package)] }
+
+ describe 'index' do
+ let(:query) do
+ FactoryBot.build_stubbed(:query)
+ end
+
+ before do
+ allow(User.current).to receive(:allowed_to?).and_return(true)
+ allow(controller).to receive(:retrieve_query).and_return(query)
+ end
+
+ describe 'bcf' do
+ let(:mime_type) { 'bcf' }
+ let(:export_storage) { FactoryBot.build_stubbed(:work_packages_export) }
+
+ before do
+ service_instance = double('service_instance')
+
+ allow(WorkPackages::Exports::ScheduleService)
+ .to receive(:new)
+ .with(user: current_user)
+ .and_return(service_instance)
+
+ allow(service_instance)
+ .to receive(:call)
+ .with(query: query, mime_type: mime_type.to_sym, params: anything)
+ .and_return(ServiceResult.new(result: export_storage))
+ end
+
+ it 'redirects to the export' do
+ get 'index', params: { format: 'bcf' }
+
+ expect(response)
+ .to redirect_to work_packages_export_path(export_storage.id)
+ end
+ end
+ end
+end
diff --git a/modules/bim/spec/features/bcf/export_spec.rb b/modules/bim/spec/features/bcf/export_spec.rb
index b7e07c65246..9f27918aa7f 100644
--- a/modules/bim/spec/features/bcf/export_spec.rb
+++ b/modules/bim/spec/features/bcf/export_spec.rb
@@ -38,7 +38,21 @@ describe 'bcf export', type: :feature, js: true do
let!(:open_bcf_issue) { FactoryBot.create(:bcf_issue, work_package: open_work_package) }
let!(:closed_bcf_issue) { FactoryBot.create(:bcf_issue, work_package: closed_work_package) }
- let(:current_user) { FactoryBot.create :admin }
+ let(:permissions) do
+ %i[view_ifc_models
+ view_linked_issues
+ manage_bcf
+ add_work_packages
+ edit_work_packages
+ view_work_packages
+ export_work_packages]
+ end
+
+ let(:current_user) do
+ FactoryBot.create :user,
+ member_in_project: project,
+ member_with_permissions: permissions
+ end
let!(:model) do
FactoryBot.create(:ifc_model_minimal_converted,
@@ -62,6 +76,7 @@ describe 'bcf export', type: :feature, js: true do
::DownloadedFile::clear_downloads
page.find('.export-bcf-button').click
+ perform_enqueued_jobs
# Wait for the file to download
::DownloadedFile.wait_for_download
::DownloadedFile.wait_for_download_content
diff --git a/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb b/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb
new file mode 100644
index 00000000000..a25f3c4a688
--- /dev/null
+++ b/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb
@@ -0,0 +1,87 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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 WorkPackages::Exports::ExportJob do
+ let(:user) { FactoryBot.build_stubbed(:user) }
+ let(:export) do
+ FactoryBot.build_stubbed(:work_packages_export, user: user)
+ end
+ let(:query) { FactoryBot.build_stubbed(:query) }
+
+ let(:instance) { described_class.new }
+ let(:options) { {} }
+ subject do
+ instance.perform(export: export,
+ mime_type: mime_type,
+ options: options,
+ query: query)
+ end
+
+ describe '#perform' do
+ context 'with the bcf mime type' do
+ let(:mime_type) { :bcf }
+
+ it 'issues an OpenProject::Bim::BcfXml::Exporter export' do
+ file = double(File)
+ allow(file)
+ .to receive(:is_a?)
+ .with(File)
+ .and_return true
+
+ result = WorkPackage::Exporter::Result::Success.new(format: 'blubs',
+ title: 'some_title',
+ content: file,
+ mime_type: "application/octet-stream")
+
+ service = double('attachments create service')
+
+ expect(Attachments::CreateService)
+ .to receive(:new)
+ .with(export, author: user)
+ .and_return(service)
+
+ expect(WorkPackages::Exports::CleanupOutdatedJob)
+ .to receive(:perform_after_grace)
+
+ expect(service)
+ .to receive(:call)
+ .with(uploaded_file: file, description: '')
+
+ allow(OpenProject::Bim::BcfXml::Exporter)
+ .to receive(:list)
+ .and_yield(result)
+
+ subject
+ end
+ end
+ end
+end
diff --git a/modules/dashboards/spec/requests/api/v3/attachments/grid_spec.rb b/modules/dashboards/spec/requests/api/v3/attachments/grid_spec.rb
index 7da55c69e85..7df5074cd20 100644
--- a/modules/dashboards/spec/requests/api/v3/attachments/grid_spec.rb
+++ b/modules/dashboards/spec/requests/api/v3/attachments/grid_spec.rb
@@ -30,6 +30,10 @@ require 'spec_helper'
require File.join(Rails.root, 'spec', 'requests', 'api', 'v3', 'attachments', 'attachment_resource_shared_examples')
describe "grid attachments" do
+ before do
+ Grids::Dashboard
+ end
+
it_behaves_like "an APIv3 attachment resource" do
let(:attachment_type) { :grid }
diff --git a/modules/xls_export/app/models/xls_export/work_package/exporter/xls.rb b/modules/xls_export/app/models/xls_export/work_package/exporter/xls.rb
new file mode 100644
index 00000000000..e9238c20783
--- /dev/null
+++ b/modules/xls_export/app/models/xls_export/work_package/exporter/xls.rb
@@ -0,0 +1,242 @@
+module XlsExport::WorkPackage::Exporter
+ class XLS < WorkPackage::Exporter::Base
+ include Redmine::I18n
+
+ def current_user
+ User.current
+ end
+
+ def with_descriptions
+ options[:show_descriptions]
+ end
+
+ def with_relations
+ options[:show_relations]
+ end
+
+ def work_packages
+ super
+ .includes(:assigned_to, :type, :priority, :category, :version)
+ end
+
+ def enable!(singleton_module)
+ singleton_class.prepend singleton_module
+ end
+
+ def list
+ enable! WithTimeZone
+ enable! WithDescription if with_descriptions
+ enable! WithRelations if with_relations
+
+ yield success(spreadsheet.xls)
+ end
+
+ def success(content)
+ WorkPackage::Exporter::Result::Success
+ .new format: :xls,
+ content: content,
+ title: xls_export_filename,
+ mime_type: 'application/vnd.ms-excel'
+ end
+
+ def spreadsheet
+ sb = spreadsheet_builder
+
+ add_headers! sb
+ add_rows! sb
+ set_column_format_options! sb
+
+ sb
+ end
+
+ def add_headers!(spreadsheet)
+ spreadsheet.add_headers headers, 0
+ end
+
+ def add_rows!(spreadsheet)
+ rows.each do |row|
+ spreadsheet.add_row row
+ end
+ end
+
+ def rows
+ work_packages.map do |work_package|
+ row work_package
+ end
+ end
+
+ def row(work_package)
+ column_values(work_package)
+ end
+
+ def column_values(work_package)
+ columns.collect do |column|
+ column_value column, work_package
+ end
+ end
+
+ def column_value(column, work_package)
+ value = format_column_value column, work_package
+
+ value.respond_to?(:name) ? value.name : value
+ end
+
+ def format_column_value(column, work_package)
+ formatters[column].format work_package, column
+ end
+
+ def set_column_format_options!(spreadsheet)
+ columns.each_with_index do |column, i|
+ options = formatters[column].format_options column
+
+ spreadsheet.add_format_option_to_column i, options
+ end
+ end
+
+ def columns
+ @columns ||= valid_export_columns
+ end
+
+ def formatters
+ @formatters ||= OpenProject::XlsExport::Formatters.for_columns(columns)
+ end
+
+ def spreadsheet_builder
+ OpenProject::XlsExport::SpreadsheetBuilder.new I18n.t(:label_work_package_plural)
+ end
+
+ def headers
+ columns.map(&:caption)
+ end
+
+ def xls_export_filename
+ sane_filename(
+ "#{Setting.app_title} #{I18n.t(:label_work_package_plural)} \
+ #{format_time_as_date(Time.now, '%Y-%m-%d')}.xls"
+ )
+ end
+ end
+
+ module WithTimeZone
+ def format_column_value(column, work_package)
+ value = super
+
+ if value.is_a? ActiveSupport::TimeWithZone
+ value.in_time_zone current_user.time_zone
+ else
+ value
+ end
+ end
+ end
+
+ module WithDescription
+ def headers
+ super + [WorkPackage.human_attribute_name(:description)]
+ end
+
+ def row(work_package)
+ super + [work_package.description]
+ end
+ end
+
+ module WithRelations
+ def add_headers!(spreadsheet)
+ headers_0 = [I18n.t(:label_work_package_plural)] +
+ columns.size.times.map { |_| "" } +
+ [I18n.t("js.work_packages.tabs.relations")]
+
+ spreadsheet.add_headers headers_0, 0
+ spreadsheet.add_headers headers, 1
+ end
+
+ def headers
+ # The filtered work packages columns +
+ # the relations columns +
+ # the columns of the work packages connected by the relations.
+ [""] + super + [""] + with_relations_headers + super
+ end
+
+ def rows
+ super.flatten(1) # since we will now generate several rows for each original row
+ end
+
+ def row(work_package)
+ wp_columns = super
+
+ relatives = related_work_packages work_package
+
+ if relatives.size > 0
+ relatives.map do |other, rel|
+ relation_row work_package, wp_columns, other, rel
+ end
+ else
+ unrelated_row wp_columns
+ end
+ end
+
+ module_function
+
+ ##
+ # Work packages both related explicitly through relation records
+ # as well via their parent_id association (parent and children).
+ #
+ # @return Array A list of work package - relation tuples
+ # where the relation may be nil which indicates
+ # that the respective work package is either a
+ # parent or a child.
+ def related_work_packages(work_package)
+ family = ([work_package.parent].compact +
+ work_package.children.order(:subject))
+ .select { |wp| wp.visible? current_user }
+ .map { |wp| [wp, nil] }
+
+ family + relation_work_packages(work_package)
+ end
+
+ ##
+ # Work packages related through explicit relation records.
+ #
+ # @return Array<Array<WorkPackage, Relation>> A list of work package - relation tuples.
+ def relation_work_packages(work_package)
+ relations = work_package_relations work_package
+
+ relations.map { |rel| [rel.other_work_package(work_package), rel] }
+ end
+
+ def unrelated_row(wp_columns)
+ [([""] + wp_columns)]
+ end
+
+ def relation_row(work_package, wp_columns, other, relation)
+ type = relation_type work_package, other, relation
+ delay = relation ? relation.delay : ""
+ description = relation ? relation.description : ""
+ relation_columns = ["", type, delay, description] + column_values(other)
+
+ [""] + wp_columns + relation_columns
+ end
+
+ def relation_type(work_package, other, relation)
+ if relation
+ normalized = relation.relation_type_for(work_package)
+ I18n.t("js.relation_labels.#{normalized}", default: normalized)
+ elsif work_package.parent_id == other.id
+ I18n.t 'xls_export.child_of'
+ elsif work_package.children.where(id: other.id).exists?
+ I18n.t 'xls_export.parent_of'
+ end
+ end
+
+ def with_relations_headers
+ [
+ Relation.human_attribute_name(:relation_type),
+ Relation.human_attribute_name(:delay),
+ Relation.human_attribute_name(:description)
+ ]
+ end
+
+ def work_package_relations(work_package)
+ work_package.relations.direct.non_hierarchy.visible
+ end
+ end
+end
diff --git a/modules/xls_export/lib/open_project/xls_export/engine.rb b/modules/xls_export/lib/open_project/xls_export/engine.rb
index d4929ecdf95..f16520ef17b 100644
--- a/modules/xls_export/lib/open_project/xls_export/engine.rb
+++ b/modules/xls_export/lib/open_project/xls_export/engine.rb
@@ -25,14 +25,18 @@ module OpenProject::XlsExport
end
initializer 'xls_export.register_mimetypes' do
+ next if defined? Mime::XLS
+
Mime::Type.register('application/vnd.ms-excel',
:xls,
- %w(application/vnd.ms-excel)) unless defined? Mime::XLS
+ %w(application/vnd.ms-excel))
end
+ class_inflection_override('xls' => 'XLS')
+
config.to_prepare do
WorkPackage::Exporter
- .register_for_list(:xls, OpenProject::XlsExport::WorkPackageXlsExport)
+ .register_for_list(:xls, XlsExport::WorkPackage::Exporter::XLS)
end
end
end
diff --git a/modules/xls_export/lib/open_project/xls_export/formatters.rb b/modules/xls_export/lib/open_project/xls_export/formatters.rb
index 70beae80e94..ea084b53028 100644
--- a/modules/xls_export/lib/open_project/xls_export/formatters.rb
+++ b/modules/xls_export/lib/open_project/xls_export/formatters.rb
@@ -56,13 +56,13 @@ module OpenProject::XlsExport
class TimeFormatter < DefaultFormatter
def format_options(column)
- {:number_format => '0.0 "h"'}
+ { :number_format => '0.0 "h"' }
end
end
class CostFormatter < DefaultFormatter
def format_options(column)
- {:number_format => number_format_string}
+ { :number_format => number_format_string }
end
def number_format_string
diff --git a/modules/xls_export/lib/open_project/xls_export/work_package_xls_export.rb b/modules/xls_export/lib/open_project/xls_export/work_package_xls_export.rb
deleted file mode 100644
index 567e34cc7d6..00000000000
--- a/modules/xls_export/lib/open_project/xls_export/work_package_xls_export.rb
+++ /dev/null
@@ -1,244 +0,0 @@
-module OpenProject
- module XlsExport
- class WorkPackageXlsExport < WorkPackage::Exporter::Base
- include Redmine::I18n
-
- def current_user
- User.current
- end
-
- def with_descriptions
- options[:show_descriptions]
- end
-
- def with_relations
- options[:show_relations]
- end
-
- def work_packages
- super
- .includes(:assigned_to, :type, :priority, :category, :version)
- end
-
- def enable!(singleton_module)
- singleton_class.prepend singleton_module
- end
-
- def list
- enable! WithTimeZone
- enable! WithDescription if with_descriptions
- enable! WithRelations if with_relations
-
- yield success(spreadsheet.xls)
- end
-
- def success(content)
- WorkPackage::Exporter::Success
- .new format: :xls,
- content: content,
- title: xls_export_filename,
- mime_type: 'application/vnd.ms-excel'
- end
-
- def spreadsheet
- sb = spreadsheet_builder
-
- add_headers! sb
- add_rows! sb
- set_column_format_options! sb
-
- sb
- end
-
- def add_headers!(spreadsheet)
- spreadsheet.add_headers headers, 0
- end
-
- def add_rows!(spreadsheet)
- rows.each do |row|
- spreadsheet.add_row row
- end
- end
-
- def rows
- work_packages.map do |work_package|
- row work_package
- end
- end
-
- def row(work_package)
- column_values(work_package)
- end
-
- def column_values(work_package)
- columns.collect do |column|
- column_value column, work_package
- end
- end
-
- def column_value(column, work_package)
- value = format_column_value column, work_package
-
- value.respond_to?(:name) ? value.name : value
- end
-
- def format_column_value(column, work_package)
- formatters[column].format work_package, column
- end
-
- def set_column_format_options!(spreadsheet)
- columns.each_with_index do |column, i|
- options = formatters[column].format_options column
-
- spreadsheet.add_format_option_to_column i, options
- end
- end
-
- def columns
- @columns ||= valid_export_columns
- end
-
- def formatters
- @formatters ||= OpenProject::XlsExport::Formatters.for_columns(columns)
- end
-
- def spreadsheet_builder
- SpreadsheetBuilder.new I18n.t(:label_work_package_plural)
- end
-
- def headers
- columns.map(&:caption)
- end
-
- def xls_export_filename
- sane_filename(
- "#{Setting.app_title} #{I18n.t(:label_work_package_plural)} \
- #{format_time_as_date(Time.now, '%Y-%m-%d')}.xls"
- )
- end
- end
-
- module WithTimeZone
- def format_column_value(column, work_package)
- value = super
-
- if value.is_a? ActiveSupport::TimeWithZone
- value.in_time_zone current_user.time_zone
- else
- value
- end
- end
- end
-
- module WithDescription
- def headers
- super + [WorkPackage.human_attribute_name(:description)]
- end
-
- def row(work_package)
- super + [work_package.description]
- end
- end
-
- module WithRelations
- def add_headers!(spreadsheet)
- headers_0 = [I18n.t(:label_work_package_plural)] +
- columns.size.times.map { |_| "" } +
- [I18n.t("js.work_packages.tabs.relations")]
-
- spreadsheet.add_headers headers_0, 0
- spreadsheet.add_headers headers, 1
- end
-
- def headers
- # The filtered work packages columns +
- # the relations columns +
- # the columns of the work packages connected by the relations.
- [""] + super + [""] + with_relations_headers + super
- end
-
- def rows
- super.flatten(1) # since we will now generate several rows for each original row
- end
-
- def row(work_package)
- wp_columns = super
-
- relatives = related_work_packages work_package
-
- if relatives.size > 0
- relatives.map do |other, rel|
- relation_row work_package, wp_columns, other, rel
- end
- else
- unrelated_row wp_columns
- end
- end
-
- module_function
-
- ##
- # Work packages both related explicitly through relation records
- # as well via their parent_id association (parent and children).
- #
- # @return Array A list of work package - relation tuples
- # where the relation may be nil which indicates
- # that the respective work package is either a
- # parent or a child.
- def related_work_packages(work_package)
- family = ([work_package.parent].compact +
- work_package.children.order(:subject))
- .select { |wp| wp.visible? current_user }
- .map { |wp| [wp, nil] }
-
- family + relation_work_packages(work_package)
- end
-
- ##
- # Work packages related through explicit relation records.
- #
- # @return Array<Array<WorkPackage, Relation>> A list of work package - relation tuples.
- def relation_work_packages(work_package)
- relations = work_package_relations work_package
-
- relations.map { |rel| [rel.other_work_package(work_package), rel] }
- end
-
- def unrelated_row(wp_columns)
- [([""] + wp_columns)]
- end
-
- def relation_row(work_package, wp_columns, other, relation)
- type = relation_type work_package, other, relation
- delay = relation ? relation.delay : ""
- description = relation ? relation.description : ""
- relation_columns = ["", type, delay, description] + column_values(other)
-
- [""] + wp_columns + relation_columns
- end
-
- def relation_type(work_package, other, relation)
- if relation
- normalized = relation.relation_type_for(work_package)
- I18n.t("js.relation_labels.#{normalized}", default: normalized)
- elsif work_package.parent_id == other.id
- I18n.t 'xls_export.child_of'
- elsif work_package.children.where(id: other.id).exists?
- I18n.t 'xls_export.parent_of'
- end
- end
-
- def with_relations_headers
- [
- Relation.human_attribute_name(:relation_type),
- Relation.human_attribute_name(:delay),
- Relation.human_attribute_name(:description)
- ]
- end
-
- def work_package_relations(work_package)
- work_package.relations.direct.non_hierarchy.visible
- end
- end
- end
-end
diff --git a/modules/xls_export/spec/lib/custom_field_xls_export_spec.rb b/modules/xls_export/spec/lib/custom_field_xls_export_spec.rb
index c70faa05b89..4b5164a4481 100644
--- a/modules/xls_export/spec/lib/custom_field_xls_export_spec.rb
+++ b/modules/xls_export/spec/lib/custom_field_xls_export_spec.rb
@@ -62,7 +62,7 @@ describe "WorkPackageXlsExport Custom Fields" do
end
let(:export) do
- OpenProject::XlsExport::WorkPackageXlsExport.new query
+ XlsExport::WorkPackage::Exporter::XLS.new query
end
def load_sheet(export)
diff --git a/modules/xls_export/spec/lib/work_package_xls_export_spec.rb b/modules/xls_export/spec/lib/work_package_xls_export_spec.rb
deleted file mode 100644
index bac464f10b9..00000000000
--- a/modules/xls_export/spec/lib/work_package_xls_export_spec.rb
+++ /dev/null
@@ -1,171 +0,0 @@
-require 'spec_helper'
-require 'spreadsheet'
-
-describe "WorkPackageXlsExport" do
- let(:project) { FactoryBot.create :project }
-
- let(:parent) { FactoryBot.create :work_package, project: project, subject: 'Parent' }
- let(:child_1) do
- FactoryBot.create :work_package, parent: parent, project: project, subject: 'Child 1'
- end
- let(:child_2) do
- FactoryBot.create :work_package, parent: parent, project: project, subject: 'Child 2'
- end
-
- let(:single) { FactoryBot.create :work_package, project: project, subject: 'Single' }
- let(:followed) { FactoryBot.create :work_package, project: project, subject: 'Followed' }
-
- let(:child_2_child) do
- FactoryBot.create :work_package, parent: child_2, project: project, subject: "Child 2's child"
- end
-
- let(:relation) do
- child_2.new_relation.tap do |r|
- r.to = followed
- r.relation_type = 'follows'
- r.delay = 0
- r.description = 'description foobar'
- r.save
- end
- end
-
- let(:work_packages) do
- work_packages = [parent, child_1, child_2, single, followed]
- child_2_child
-
- work_packages
- end
-
- let(:current_user) { FactoryBot.create :admin } # may export relations
-
- let(:query) do
- query = FactoryBot.build(:query, user: current_user, project: project)
-
- query.filters.clear
- query.sort_criteria = [['id', 'asc']]
- query
- end
-
- let(:sheet) do
- login_as(current_user)
- work_packages
- relation
- work_packages.each(&:reload) # to init .leaves and relations
- load_sheet export
- end
-
- let(:export) do
- OpenProject::XlsExport::WorkPackageXlsExport.new(
- query,
- show_relations: true
- )
- end
-
- def load_sheet(export)
- f = Tempfile.new 'result.xls'
- begin
- f.binmode
- f.write export.list(&:content)
- ensure
- f.close
- end
-
- sheet = Spreadsheet.open(f.path).worksheets.first
- f.unlink
-
- sheet
- end
-
- # expected row and column indices
-
- PARENT = 2
- CHILD_1 = 4
- CHILD_2 = 5
- SINGLE = 8
- FOLLOWED = 9
- RELATION = 8
- RELATION_DESCRIPTION = 10
- RELATED_SUBJECT = 13
-
- it 'produces the correct result' do
- expect(query.columns.map(&:name)).to eq [:type, :id, :subject, :status, :assigned_to, :priority]
-
- # the first header row devides the sheet into work packages and relation columns
- expect(sheet.rows.first.take(8)).to eq ['Work packages', nil, nil, nil, nil, nil, nil, 'Relations']
-
- # the second header row includes the column names for work packages and relations and the related work package
- expect(sheet.rows[1])
- .to eq [
- nil, 'Type', 'ID', 'Subject', 'Status', 'Assignee', 'Priority',
- nil, 'Relation type', 'Delay', 'Description',
- 'Type', 'ID', 'Subject', 'Status', 'Assignee', 'Priority',
- nil
- ]
-
- # duplicates rows for each relation
- c2id = child_2.id
- expect(sheet.column(2).drop(2))
- .to eq [parent.id, parent.id, child_1.id, c2id, c2id, c2id, single.id, followed.id, child_2_child.id]
-
- # marks Parent as parent of Child 1 and 2
- expect(sheet.row(PARENT)[RELATION]).to eq 'parent of'
- expect(sheet.row(PARENT)[RELATED_SUBJECT]).to eq 'Child 1'
-
- expect(sheet.row(PARENT + 1)[RELATION]).to eq 'parent of'
- expect(sheet.row(PARENT + 1)[RELATED_SUBJECT]).to eq 'Child 2'
-
- # shows Child 1 as child of Parent
- expect(sheet.row(CHILD_1)[RELATION]).to eq 'child of'
- expect(sheet.row(CHILD_1)[RELATED_SUBJECT]).to eq 'Parent'
-
- # shows Child 2 as child of Parent
- expect(sheet.row(CHILD_2)[RELATION]).to eq 'child of'
- expect(sheet.row(CHILD_2)[RELATED_SUBJECT]).to eq 'Parent'
-
- # shows Child 2 as parent of Child 2's child
- expect(sheet.row(CHILD_2 + 1)[RELATION]).to eq 'parent of'
- expect(sheet.row(CHILD_2 + 1)[RELATED_SUBJECT]).to eq "Child 2's child"
-
- # shows Child 2 as following Followed
- expect(sheet.row(CHILD_2 + 2)[RELATION]).to eq 'Follows'
- expect(sheet.row(CHILD_2 + 2)[RELATED_SUBJECT]).to eq 'Followed'
-
- # shows no relation information for Single
- expect(sheet.row(SINGLE).drop(7).compact).to eq []
-
- # shows Followed as preceding Child 2'
- expect(sheet.row(FOLLOWED)[RELATION]).to eq 'Precedes'
- expect(sheet.row(FOLLOWED)[RELATION_DESCRIPTION]).to eq 'description foobar'
- expect(sheet.row(FOLLOWED)[RELATED_SUBJECT]).to eq 'Child 2'
-
- # exports the correct data (examples)
- expect(sheet.row(PARENT))
- .to eq [
- nil, parent.type.name, parent.id, parent.subject, parent.status.name, parent.assigned_to, parent.priority.name,
- nil, 'parent of', nil, nil,
- child_1.type.name, child_1.id, child_1.subject, child_1.status.name, child_1.assigned_to, child_1.priority.name
- ] # delay nil as this is a parent-child relation not represented by an actual Relation record
-
- expect(sheet.row(SINGLE))
- .to eq [
- nil, single.type.name, single.id, single.subject, single.status.name, single.assigned_to, single.priority.name
- ]
-
- expect(sheet.row(FOLLOWED))
- .to eq [
- nil,
- followed.type.name, followed.id, followed.subject, followed.status.name, followed.assigned_to, followed.priority.name,
- nil, 'Precedes', 0, relation.description,
- child_2.type.name, child_2.id, child_2.subject, child_2.status.name, child_2.assigned_to, child_2.priority.name
- ]
- end
-
- context 'with someone who may not see related work packages' do
- let(:current_user) { FactoryBot.create :user }
-
- it 'exports no information without visibility' do
- expect(sheet.rows.length).to eq(2)
- expect(sheet.column(1).drop(2)).to be_empty
- end
- end
-end
diff --git a/modules/xls_export/spec/models/xls_export/work_package/exporter/xls_integration_spec.rb b/modules/xls_export/spec/models/xls_export/work_package/exporter/xls_integration_spec.rb
new file mode 100644
index 00000000000..cebbf4214fb
--- /dev/null
+++ b/modules/xls_export/spec/models/xls_export/work_package/exporter/xls_integration_spec.rb
@@ -0,0 +1,321 @@
+require 'spec_helper'
+require 'spreadsheet'
+
+describe XlsExport::WorkPackage::Exporter::XLS do
+ let(:project) { FactoryBot.create :project }
+
+ let(:current_user) { FactoryBot.create :admin }
+
+ let(:column_names) { %w[type id subject status assigned_to priority] }
+ let(:query) do
+ query = FactoryBot.build(:query, user: current_user, project: project)
+
+ query.filters.clear
+ query.column_names = column_names
+ query.sort_criteria = [['id', 'asc']]
+ query
+ end
+
+ let(:relations) { [] }
+
+ let(:sheet) do
+ login_as(current_user)
+ work_packages
+ relations
+ work_packages.each(&:reload) # to init .leaves and relations
+ load_sheet export
+ end
+
+ let(:options) { {} }
+
+ let(:export) do
+ described_class.new(
+ query,
+ options
+ )
+ end
+
+ def load_sheet(export)
+ f = Tempfile.new 'result.xls'
+ begin
+ f.binmode
+ f.write export.list(&:content)
+ ensure
+ f.close
+ end
+
+ sheet = Spreadsheet.open(f.path).worksheets.first
+ f.unlink
+
+ sheet
+ end
+
+ context 'with relations' do
+ let(:options) { { show_relations: true } }
+
+ let(:parent) { FactoryBot.create :work_package, project: project, subject: 'Parent' }
+ let(:child_1) do
+ FactoryBot.create :work_package, parent: parent, project: project, subject: 'Child 1'
+ end
+ let(:child_2) do
+ FactoryBot.create :work_package, parent: parent, project: project, subject: 'Child 2'
+ end
+
+ let(:single) { FactoryBot.create :work_package, project: project, subject: 'Single' }
+ let(:followed) { FactoryBot.create :work_package, project: project, subject: 'Followed' }
+
+ let(:child_2_child) do
+ FactoryBot.create :work_package, parent: child_2, project: project, subject: "Child 2's child"
+ end
+
+ let(:relation) do
+ child_2.new_relation.tap do |r|
+ r.to = followed
+ r.relation_type = 'follows'
+ r.delay = 0
+ r.description = 'description foobar'
+ r.save
+ end
+ end
+
+ let(:relations) { [relation] }
+
+ let(:work_packages) do
+ work_packages = [parent, child_1, child_2, single, followed]
+ child_2_child
+
+ work_packages
+ end
+ # expected row and column indices
+
+ PARENT = 2
+ CHILD_1 = 4
+ CHILD_2 = 5
+ SINGLE = 8
+ FOLLOWED = 9
+ RELATION = 8
+ RELATION_DESCRIPTION = 10
+ RELATED_SUBJECT = 13
+
+ it 'produces the correct result' do
+ expect(query.columns.map(&:name)).to eq %i[type id subject status assigned_to priority]
+
+ # the first header row devides the sheet into work packages and relation columns
+ expect(sheet.rows.first.take(8)).to eq ['Work packages', nil, nil, nil, nil, nil, nil, 'Relations']
+
+ # the second header row includes the column names for work packages and relations and the related work package
+ expect(sheet.rows[1])
+ .to eq [
+ nil, 'Type', 'ID', 'Subject', 'Status', 'Assignee', 'Priority',
+ nil, 'Relation type', 'Delay', 'Description',
+ 'Type', 'ID', 'Subject', 'Status', 'Assignee', 'Priority',
+ nil
+ ]
+
+ # duplicates rows for each relation
+ c2id = child_2.id
+ expect(sheet.column(2).drop(2))
+ .to eq [parent.id, parent.id, child_1.id, c2id, c2id, c2id, single.id, followed.id, child_2_child.id]
+
+ # marks Parent as parent of Child 1 and 2
+ expect(sheet.row(PARENT)[RELATION]).to eq 'parent of'
+ expect(sheet.row(PARENT)[RELATED_SUBJECT]).to eq 'Child 1'
+
+ expect(sheet.row(PARENT + 1)[RELATION]).to eq 'parent of'
+ expect(sheet.row(PARENT + 1)[RELATED_SUBJECT]).to eq 'Child 2'
+
+ # shows Child 1 as child of Parent
+ expect(sheet.row(CHILD_1)[RELATION]).to eq 'child of'
+ expect(sheet.row(CHILD_1)[RELATED_SUBJECT]).to eq 'Parent'
+
+ # shows Child 2 as child of Parent
+ expect(sheet.row(CHILD_2)[RELATION]).to eq 'child of'
+ expect(sheet.row(CHILD_2)[RELATED_SUBJECT]).to eq 'Parent'
+
+ # shows Child 2 as parent of Child 2's child
+ expect(sheet.row(CHILD_2 + 1)[RELATION]).to eq 'parent of'
+ expect(sheet.row(CHILD_2 + 1)[RELATED_SUBJECT]).to eq "Child 2's child"
+
+ # shows Child 2 as following Followed
+ expect(sheet.row(CHILD_2 + 2)[RELATION]).to eq 'Follows'
+ expect(sheet.row(CHILD_2 + 2)[RELATED_SUBJECT]).to eq 'Followed'
+
+ # shows no relation information for Single
+ expect(sheet.row(SINGLE).drop(7).compact).to eq []
+
+ # shows Followed as preceding Child 2'
+ expect(sheet.row(FOLLOWED)[RELATION]).to eq 'Precedes'
+ expect(sheet.row(FOLLOWED)[RELATION_DESCRIPTION]).to eq 'description foobar'
+ expect(sheet.row(FOLLOWED)[RELATED_SUBJECT]).to eq 'Child 2'
+
+ # exports the correct data (examples)
+ expect(sheet.row(PARENT))
+ .to eq [
+ nil, parent.type.name, parent.id, parent.subject, parent.status.name, parent.assigned_to, parent.priority.name,
+ nil, 'parent of', nil, nil,
+ child_1.type.name, child_1.id, child_1.subject, child_1.status.name, child_1.assigned_to, child_1.priority.name
+ ] # delay nil as this is a parent-child relation not represented by an actual Relation record
+
+ expect(sheet.row(SINGLE))
+ .to eq [
+ nil, single.type.name, single.id, single.subject, single.status.name, single.assigned_to, single.priority.name
+ ]
+
+ expect(sheet.row(FOLLOWED))
+ .to eq [
+ nil,
+ followed.type.name, followed.id, followed.subject, followed.status.name, followed.assigned_to, followed.priority.name,
+ nil, 'Precedes', 0, relation.description,
+ child_2.type.name, child_2.id, child_2.subject, child_2.status.name, child_2.assigned_to, child_2.priority.name
+ ]
+ end
+
+ context 'with someone who may not see related work packages' do
+ let(:current_user) { FactoryBot.create :user }
+
+ it 'exports no information without visibility' do
+ expect(sheet.rows.length).to eq(2)
+ expect(sheet.column(1).drop(2)).to be_empty
+ end
+ end
+ end
+
+ describe 'with cost and time entries' do
+ # Since this test has to work without the actual costs plugin we'll just add
+ # a custom field called 'costs' to emulate it.
+
+ let(:custom_field) do
+ FactoryBot.create(:float_wp_custom_field,
+ name: 'unit costs')
+ end
+ let(:custom_value) do
+ FactoryBot.create(:custom_value,
+ custom_field: custom_field)
+ end
+ let(:type) do
+ type = project.types.first
+ type.custom_fields << custom_field
+ type
+ end
+ let(:project) do
+ FactoryBot.create(:project,
+ work_package_custom_fields: [custom_field])
+ end
+ let(:work_packages) do
+ wps = FactoryBot.create_list(:work_package, 4,
+ project: project,
+ type: type)
+ wps[0].estimated_hours = 27.5
+ wps[0].save!
+ wps[1].send(:"custom_field_#{custom_field.id}=", 1)
+ wps[1].save!
+ wps[2].send(:"custom_field_#{custom_field.id}=", 99.99)
+ wps[2].save!
+ wps[3].send(:"custom_field_#{custom_field.id}=", 1000)
+ wps[3].save!
+ wps
+ end
+ let(:column_names) { ['subject', 'status', 'estimated_hours', "cf_#{custom_field.id}"] }
+
+ before do
+ allow(OpenProject::XlsExport::Formatters::TimeFormatter).to receive(:apply?) do |column|
+ column.caption =~ /time/i
+ end
+
+ allow(OpenProject::XlsExport::Formatters::CostFormatter).to receive(:apply?) do |column|
+ column.caption =~ /cost/i
+ end
+
+ allow(Setting)
+ .to receive(:plugin_openproject_costs)
+ .and_return('costs_currency' => 'EUR', 'costs_currency_format' => '%n %u')
+ end
+
+ it 'should successfully export the work packages with a cost column' do
+ expect(sheet.rows.size).to eq(4 + 1)
+
+ cost_column = sheet.columns.last.to_a
+ %w[1 99.99 1000].each do |value|
+ expect(cost_column).to include(value)
+ end
+ end
+
+ context 'with german locale' do
+ let(:current_user) { FactoryBot.create(:admin, language: :de) }
+
+ it 'should successfully export the work packages with a cost column localized' do
+ I18n.with_locale :de do
+ sheet
+ end
+
+ expect(sheet.rows.size).to eq(4 + 1)
+ cost_column = sheet.columns.last.to_a
+ %w[1 99,99 1000].each do |value|
+ expect(cost_column).to include(value)
+ end
+ end
+ end
+
+ it 'should include estimated hours' do
+ expect(sheet.rows.size).to eq(4 + 1)
+
+ # Check row after header row
+ hours = sheet.rows[1].values_at(2)
+ expect(hours).to include(27.5)
+ end
+ end
+
+ context 'with descriptions' do
+ let(:options) { { show_descriptions: true } }
+
+ let(:work_package) do
+ FactoryBot.create(:work_package,
+ description: 'some arbitrary description',
+ project: project,
+ type: project.types.first)
+ end
+ let(:work_packages) { [work_package] }
+ let(:column_names) { %w[id] }
+
+ it 'includes the description' do
+ expect(sheet.rows.size).to eq(1 + 1)
+
+ expect(sheet.rows[1][1])
+ .to eql(work_package.description)
+ end
+ end
+
+ describe 'empty result' do
+ let(:work_packages) { [] }
+
+ it 'should yield an empty XLS file' do
+ expect(sheet.rows.size).to eq(1) # just the headers
+ end
+ end
+
+ describe 'with user time zone' do
+ let(:zone) { +2 }
+ let(:work_package) do
+ FactoryBot.create(:work_package,
+ project: project,
+ type: project.types.first)
+ end
+ let(:work_packages) { [work_package] }
+
+ let(:column_names) { %w[subject status updated_at] }
+
+ before do
+ allow(current_user).to receive(:time_zone).and_return(zone)
+
+ allow(OpenProject::XlsExport::Formatters::TimeFormatter).to receive(:apply?) do |column|
+ column.caption =~ /time/i
+ end
+ end
+
+ it 'should adapt the datetime fields to the user time zone' do
+ work_package.reload
+ updated_at_cell = sheet.rows.last.to_a.last
+ expect(updated_at_cell.to_s(:number)).to eq(work_package.updated_at.in_time_zone(zone).to_s(:number))
+ end
+ end
+end
diff --git a/modules/xls_export/spec/patches/work_packages_controller_patch_spec.rb b/modules/xls_export/spec/patches/work_packages_controller_patch_spec.rb
index dc8d548f7db..41aea29b6d4 100644
--- a/modules/xls_export/spec/patches/work_packages_controller_patch_spec.rb
+++ b/modules/xls_export/spec/patches/work_packages_controller_patch_spec.rb
@@ -1,244 +1,151 @@
-require 'spec_helper'
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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.
+#++
-describe WorkPackagesController, 'rendering to xls', type: :controller do
- let(:current_user) { FactoryBot.create(:admin) }
- let!(:work_package) do
- FactoryBot.create(:work_package,
- subject: '!SUBJECT!',
- description: '!DESCRIPTION!')
- end
+require 'spec_helper'
+describe WorkPackagesController, type: :controller do
before do
- allow(User).to receive(:current).and_return current_user
+ login_as current_user
end
- describe "should respond with the xls if requested in the index" do
- before do
- get('index', params: { format: 'xls', project_id: work_package.project_id })
- end
-
- it 'should respond with 200 OK' do
- expect(response.response_code).to eq(200)
- end
-
- it 'should have a length > 100 bytes' do
- expect(response.body.length).to be > 100
- end
-
- it 'should not contain a description' do
- expect(response.body).not_to include('!DESCRIPTION!')
- end
-
- it 'should contain a subject' do
- expect(response.body).to include('!SUBJECT!')
- end
-
- context 'the mime type' do
- it { expect(response.header['Content-Type']).to eq('application/vnd.ms-excel') }
- end
+ let(:project) { FactoryBot.create(:project, identifier: 'test_project', public: false) }
+ let(:stub_project) { FactoryBot.build_stubbed(:project, identifier: 'test_project', public: false) }
+ let(:type) { FactoryBot.build_stubbed(:type) }
+ let(:stub_work_package) do
+ FactoryBot.build_stubbed(:stubbed_work_package,
+ id: 1337,
+ type: type,
+ project: stub_project)
end
- describe 'with cost and time entries' do
- # Since this test has to work without the actual costs plugin we'll just add
- # a custom field called 'costs' to emulate it.
+ let(:current_user) { FactoryBot.create(:user) }
- let(:custom_field) do
- FactoryBot.create(:float_wp_custom_field,
- name: 'unit costs')
- end
- let(:custom_value) do
- FactoryBot.create(:custom_value,
- custom_field: custom_field)
- end
- let(:type) do
- type = project.types.first
- type.custom_fields << custom_field
- type
- end
- let(:project) do
- FactoryBot.create(:project,
- work_package_custom_fields: [custom_field])
- end
- let(:work_packages) do
- wps = FactoryBot.create_list(:work_package, 4,
- project: project,
- type: type)
- wps[0].estimated_hours = 27.5
- wps[0].save!
- wps[1].send(:"custom_field_#{custom_field.id}=", 1)
- wps[1].save!
- wps[2].send(:"custom_field_#{custom_field.id}=", 99.99)
- wps[2].save!
- wps[3].send(:"custom_field_#{custom_field.id}=", 1000)
- wps[3].save!
- wps
- end
-
- before do
- allow(OpenProject::XlsExport::Formatters::TimeFormatter).to receive(:apply?) do |column|
- column.caption =~ /time/i
- end
+ def self.requires_export_permission(&block)
+ describe 'w/ the export permission
+ w/o a project' do
+ let(:project) { nil }
- allow(OpenProject::XlsExport::Formatters::CostFormatter).to receive(:apply?) do |column|
- column.caption =~ /cost/i
+ before do
+ expect(User.current).to receive(:allowed_to?)
+ .with(:export_work_packages,
+ project,
+ global: true)
+ .and_return(true)
end
- allow(Setting).to receive(:plugin_openproject_costs).and_return('costs_currency' => 'EUR', 'costs_currency_format' => '%n %u')
-
- get 'index',
- params: {
- format: 'xls',
- project_id: work_packages.first.project_id,
- set_filter: '1',
- c: ['subject',
- 'status',
- 'estimated_hours',
- "cf_#{custom_field.id}"],
- sortBy: JSON::dump(['id:asc'])
- }
-
- expect(response.response_code).to eq(200)
-
- f = Tempfile.new 'result.xls'
- begin
- f.binmode
- f.write response.body
- ensure
- f.close
- end
-
- require 'spreadsheet'
-
- @sheet = Spreadsheet.open(f.path).worksheets.first
- f.unlink
- end
-
- it 'should successfully export the work packages with a cost column' do
- expect(@sheet.rows.size).to eq(4 + 1)
-
- cost_column = @sheet.columns.last.to_a
- %w[1 99.99 1000].each do |value|
- expect(cost_column).to include(value)
- end
+ instance_eval(&block)
end
- context 'with german locale' do
- let(:current_user) { FactoryBot.create(:admin, language: :de) }
+ describe 'w/ the export permission
+ w/ a project' do
+ before do
+ params[:project_id] = project.id
- it 'should successfully export the work packages with a cost column localized' do
- expect(@sheet.rows.size).to eq(4 + 1)
-
- cost_column = @sheet.columns.last.to_a
- %w[1 99,99 1000].each do |value|
- expect(cost_column).to include(value)
- end
+ expect(User.current).to receive(:allowed_to?)
+ .with(:export_work_packages,
+ project,
+ global: false)
+ .and_return(true)
end
- end
-
- it 'should include estimated hours' do
- expect(@sheet.rows.size).to eq(4 + 1)
-
- # Check row after header row
- hours = @sheet.rows[1].values_at(2)
- expect(hours).to include(27.5)
- end
- end
-
- context 'with descriptions' do
- before do
- get 'index',
- params: {
- format: 'xls',
- project_id: work_package.project_id,
- show_descriptions: 'true'
- }
- end
-
- it 'should respond with 200 OK' do
- expect(response.response_code).to eq(200)
- end
-
- it 'should have a length > 100 bytes' do
- expect(response.body.length).to be > 100
- end
-
- it 'should contain a description' do
- expect(response.body).to include('!DESCRIPTION!')
- end
-
- it 'should contain a subject' do
- expect(response.body).to include('!SUBJECT!')
- end
- it 'returns the xls mime mime type' do
- expect(response.header['Content-Type'])
- .to eq('application/vnd.ms-excel')
+ instance_eval(&block)
end
- end
- describe 'empty result' do
- before do
- work_package.delete
-
- get 'index', params: { format: 'xls', project_id: work_package.project_id }
- end
+ describe 'w/o the export permission' do
+ let(:project) { nil }
- it 'should yield an empty XLS file' do
- expect(response.response_code).to be(200)
+ before do
+ expect(User.current).to receive(:allowed_to?)
+ .with(:export_work_packages,
+ project,
+ global: true)
+ .and_return(false)
- f = Tempfile.new 'result.xls'
- begin
- f.binmode
- f.write response.body
- ensure
- f.close
+ call_action
end
- require 'spreadsheet'
-
- sheet = Spreadsheet.open(f.path).worksheets.first
- expect(sheet.rows.size).to eq(1) # just the headers
+ it 'should render a 403' do
+ expect(response.response_code).to eq(403)
+ end
end
end
- describe 'with user time zone' do
- let(:zone) { +2 }
+ describe 'index' do
+ let(:query) { FactoryBot.build_stubbed(:query).tap(&:add_default_filter) }
+ let(:work_packages) { double('work packages').as_null_object }
+ let(:results) { double('results').as_null_object }
before do
- allow(current_user).to receive(:time_zone).and_return(zone)
-
- allow(OpenProject::XlsExport::Formatters::TimeFormatter).to receive(:apply?) do |column|
- column.caption =~ /time/i
+ allow(User.current).to receive(:allowed_to?).and_return(false)
+ expect(User.current).to receive(:allowed_to?)
+ .with({ controller: 'work_packages',
+ action: 'index' },
+ project,
+ global: project.nil?)
+ .and_return(true)
+ end
+
+ describe 'with valid query' do
+ before do
+ allow(controller).to receive(:retrieve_query).and_return(query)
end
- get 'index',
- params: {
- format: 'xls',
- project_id: work_package.project_id,
- set_filter: '1',
- c: ['subject', 'status', 'updated_at']
- }
-
- expect(response.response_code).to eq(200)
-
- f = Tempfile.new 'result.xls'
- begin
- f.binmode
- f.write response.body
- ensure
- f.close
+ describe 'xls' do
+ let(:params) { {} }
+ let(:call_action) { get('index', params: params.merge(format: mime_type)) }
+ let(:mime_type) { 'xls' }
+ let(:export_storage) { FactoryBot.build_stubbed(:work_packages_export) }
+
+ requires_export_permission do
+ before do
+ service_instance = double('service_instance')
+
+ allow(WorkPackages::Exports::ScheduleService)
+ .to receive(:new)
+ .with(user: current_user)
+ .and_return(service_instance)
+
+ allow(service_instance)
+ .to receive(:call)
+ .with(query: query, mime_type: mime_type.to_sym, params: anything)
+ .and_return(ServiceResult.new(result: export_storage))
+ end
+
+ it 'should fulfill the defined should_receives' do
+ call_action
+
+ expect(response)
+ .to redirect_to(work_packages_export_path(export_storage.id))
+ end
+ end
end
-
- require 'spreadsheet'
-
- @sheet = Spreadsheet.open(f.path).worksheets.first
- f.unlink
- end
-
- it 'should adapt the datetime fields to the user time zone' do
- work_package.reload
- updated_at_cell = @sheet.rows.last.to_a.last
- expect(updated_at_cell.to_s(:number)).to eq(work_package.updated_at.in_time_zone(zone).to_s(:number))
end
end
end
diff --git a/spec/controllers/work_packages/exports_controller_spec.rb b/spec/controllers/work_packages/exports_controller_spec.rb
new file mode 100644
index 00000000000..e93c439de4b
--- /dev/null
+++ b/spec/controllers/work_packages/exports_controller_spec.rb
@@ -0,0 +1,111 @@
+
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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 WorkPackages::ExportsController, type: :controller do
+ include ::API::V3::Utilities::PathHelper
+
+ before do
+ login_as current_user
+ end
+
+ let(:user) { FactoryBot.build_stubbed(:user) }
+ let(:current_user) { user }
+ let!(:export) do
+ FactoryBot.build_stubbed(:work_packages_export, user: user).tap do |export|
+ allow(WorkPackages::Export)
+ .to receive(:find)
+ .and_raise(ActiveRecord::RecordNotFound)
+
+ allow(WorkPackages::Export)
+ .to receive(:find)
+ .with(export.id.to_s)
+ .and_return(export)
+ end
+ end
+ let!(:attachment) do
+ FactoryBot.build_stubbed(:attachment, container: export).tap do |a|
+ export_attachments = attachment_done ? [a] : []
+
+ allow(export)
+ .to receive(:attachments)
+ .and_return(export_attachments)
+ end
+ end
+ let(:attachment_done) { true }
+
+ describe 'show' do
+ let(:query) { FactoryBot.build_stubbed(:query) }
+
+ context 'with an existing id' do
+ before do
+ get 'show', params: { id: export.id }
+ end
+
+ context 'with the attachment being ready' do
+ it 'redirects to the download location' do
+ expect(response)
+ .to redirect_to api_v3_paths.attachment_content(attachment.id)
+ end
+ end
+
+ context 'with the attachment not being ready' do
+ let(:attachment_done) { false }
+
+ it 'returns 202 ACCEPTED' do
+ expect(response.status)
+ .to eql 202
+ end
+ end
+
+ context 'with the export belonging to a different user' do
+ let(:current_user) { FactoryBot.build_stubbed(:user) }
+
+ it 'returns 404 NOT FOUND' do
+ expect(response.status)
+ .to eql 404
+ end
+ end
+ end
+
+ context 'with an inexisting id' do
+ before do
+ get 'show', params: { id: export.id + 5 }
+ end
+
+ it 'returns 404 NOT FOUND' do
+ expect(response.status)
+ .to eql 404
+ end
+ end
+ end
+end
diff --git a/spec/controllers/work_packages_controller_spec.rb b/spec/controllers/work_packages_controller_spec.rb
index f6fbe029244..c34072be740 100644
--- a/spec/controllers/work_packages_controller_spec.rb
+++ b/spec/controllers/work_packages_controller_spec.rb
@@ -32,14 +32,18 @@ require 'spec_helper'
describe WorkPackagesController, type: :controller do
before do
- allow(User).to receive(:current).and_return current_user
- # disables sending mails
- allow(UserMailer).to receive(:new).and_return(double('mailer').as_null_object)
+ login_as current_user
end
let(:project) { FactoryBot.create(:project, identifier: 'test_project', public: false) }
let(:stub_project) { FactoryBot.build_stubbed(:project, identifier: 'test_project', public: false) }
- let(:stub_work_package) { double('work_package', id: 1337, project: stub_project).as_null_object }
+ let(:type) { FactoryBot.build_stubbed(:type) }
+ let(:stub_work_package) do
+ FactoryBot.build_stubbed(:stubbed_work_package,
+ id: 1337,
+ type: type,
+ project: stub_project)
+ end
let(:current_user) { FactoryBot.create(:user) }
@@ -121,24 +125,17 @@ describe WorkPackagesController, type: :controller do
let(:work_packages) { double('work packages').as_null_object }
let(:results) { double('results').as_null_object }
- before do
- allow(User.current).to receive(:allowed_to?).and_return(false)
- expect(User.current).to receive(:allowed_to?)
- .with({ controller: 'work_packages',
- action: 'index' },
- project,
- global: project.nil?)
- .and_return(true)
- end
-
describe 'with valid query' do
before do
- allow(controller).to receive(:retrieve_query).and_return(query)
+ allow(User.current).to receive(:allowed_to?).and_return(false)
+ expect(User.current).to receive(:allowed_to?)
+ .with({ controller: 'work_packages',
+ action: 'index' },
+ project,
+ global: project.nil?)
+ .and_return(true)
- # Note: Stubs for methods used to build up the json query results.
- # TODO RS: Clearly this isn't testing anything, but it all needs to be moved to an API controller anyway.
- allow(query).to receive(:results).and_return(results)
- allow(results).to receive_message_chain(:sorted_work_packages, :page, :per_page).and_return(work_packages)
+ allow(controller).to receive(:retrieve_query).and_return(query)
end
describe 'html' do
@@ -163,118 +160,46 @@ describe WorkPackagesController, type: :controller do
end
end
- describe 'csv' do
- let(:params) { {} }
- let(:call_action) { get('index', params: params.merge(format: 'csv')) }
+ shared_examples_for 'export of mime_type' do
+ let(:export_storage) { FactoryBot.build_stubbed(:work_packages_export) }
+ let(:call_action) { get('index', params: params.merge(format: mime_type)) }
requires_export_permission do
before do
- mock_result = double('mock csv result',
- error?: false,
- content: 'blubs',
- mime_type: 'text/csv',
- title: 'blubs.csv')
-
- expect(WorkPackage::Exporter::CSV)
- .to receive(:list)
- .with(query, anything)
- .and_yield(mock_result)
-
- expect(controller)
- .to receive(:send_data)
- .with(mock_result.content,
- type: mock_result.mime_type,
- filename: mock_result.title) do |_|
- # We need to render something because otherwise
- # the controller will and he will not find a suitable template
- controller.render plain: 'success'
- end
+ service_instance = double('service_instance')
+
+ allow(WorkPackages::Exports::ScheduleService)
+ .to receive(:new)
+ .with(user: current_user)
+ .and_return(service_instance)
+
+ allow(service_instance)
+ .to receive(:call)
+ .with(query: query, mime_type: mime_type.to_sym, params: anything)
+ .and_return(ServiceResult.new(result: export_storage))
end
it 'should fulfill the defined should_receives' do
call_action
+
+ expect(response)
+ .to redirect_to(work_packages_export_path(export_storage.id))
end
end
end
- describe 'pdf' do
+ describe 'csv' do
let(:params) { {} }
- let(:call_action) { get('index', params: params.merge(format: 'pdf')) }
-
- requires_export_permission do
- context 'w/ a valid query' do
- before do
- mock_result = double('mock pdf result',
- error?: false,
- content: 'blubs',
- mime_type: 'application/pdf',
- title: 'blubs.pdf')
-
- expect(controller)
- .to receive(:send_data)
- .with(mock_result.content,
- type: mock_result.mime_type,
- filename: mock_result.title) do |_|
- # We need to render something because otherwise
- # the controller will and he will not find a suitable template
- controller.render plain: 'success'
- end
-
- expect(WorkPackage::Exporter::PDF)
- .to receive(:list)
- .with(query, anything)
- .and_yield(mock_result)
- end
-
- it 'should fulfill the defined should_receives' do
- call_action
- end
- end
-
- context 'with invalid query' do
- let(:params) { { query_id: 'hokusbogus' } }
+ let(:mime_type) { 'csv' }
- context 'when a non-existant query has been previously selected' do
- before do
- allow(controller)
- .to receive(:retrieve_query)
- .and_raise(ActiveRecord::RecordNotFound)
-
- call_action
- end
-
- it 'renders a 404' do
- expect(response.response_code).to be === 404
- end
- end
- end
-
- context 'with an export error' do
- before do
- mock_result = double('mock pdf result',
- error?: true,
- message: 'because')
-
- expect(WorkPackage::Exporter::PDF)
- .to receive(:list)
- .with(query, anything)
- .and_yield(mock_result)
-
- call_action
- end
+ it_behaves_like 'export of mime_type'
+ end
- it "shows the error message" do
- expect(flash[:error].downcase).to include("because")
- end
+ describe 'pdf' do
+ let(:params) { {} }
+ let(:mime_type) { 'pdf' }
- it "redirects to the html index" do
- if project
- expect(response).to redirect_to project_work_packages_path(project)
- else
- expect(response).to redirect_to work_packages_path
- end
- end
- end
+ it_behaves_like 'export of mime_type' do
end
end
@@ -284,9 +209,14 @@ describe WorkPackagesController, type: :controller do
requires_export_permission do
before do
+ # Note: Stubs for methods used to build up the json query results.
+ # TODO RS: Clearly this isn't testing anything, but it all needs to be moved to an API controller anyway.
+ allow(query).to receive(:results).and_return(results)
+ allow(results).to receive_message_chain(:sorted_work_packages, :page, :per_page).and_return(work_packages)
+
expect(controller).to receive(:render_feed).with(work_packages, anything) do |*_args|
# We need to render something because otherwise
- # the controller will and he will not find a suitable template
+ # the controller will and it will not find a suitable template
controller.render plain: 'success'
end
end
@@ -297,42 +227,28 @@ describe WorkPackagesController, type: :controller do
end
end
end
- end
- describe 'index with actual data' do
- require 'csv'
- render_views
-
- ##
- # When Ruby tries to join the following work package's subject encoded in ISO-8859-1
- # and its description encoded in UTF-8 it will result in a CompatibilityError.
- # This would not happen if the description contained only letters covered by
- # ISO-8859-1. Since this can happen, though, it is more sensible to encode everything
- # in UTF-8 which gets rid of this problem altogether.
- let(:work_package) do
- FactoryBot.create(
- :work_package,
- subject: "Ruby encodes ß as '\\xDF' in ISO-8859-1.",
- description: "\u2022 requires unicode.",
- assigned_to: current_user
- )
- end
- let(:current_user) { FactoryBot.create(:admin) }
+ context 'with invalid query' do
+ describe 'pdf' do
+ let(:call_action) { get('index', params: params.merge(format: 'pdf')) }
+ let(:params) { { query_id: 'hokusbogus' } }
- it 'performs a successful export' do
- wp = work_package.reload
+ context 'when a non-existant query has been previously selected' do
+ before do
+ allow(User.current).to receive(:allowed_to?).and_return(true)
- expect do
- get :index, params: { format: 'csv', c: %i(subject assignee updatedAt) }
- end.not_to raise_error
+ allow(controller)
+ .to receive(:retrieve_query)
+ .and_raise(ActiveRecord::RecordNotFound)
- data = CSV.parse(response.body)
+ call_action
+ end
- expect(data.size).to eq(2)
- expect(data.last).to include(wp.subject)
- expect(data.last).to include(wp.description)
- expect(data.last).to include(current_user.name)
- expect(data.last).to include(wp.updated_at.localtime.strftime("%m/%d/%Y %I:%M %p"))
+ it 'renders a 404' do
+ expect(response.response_code).to eql 404
+ end
+ end
+ end
end
end
@@ -375,7 +291,7 @@ describe WorkPackagesController, type: :controller do
type: expected_type,
filename: expected_name) do |*_args|
# We need to render something because otherwise
- # the controller will and he will not find a suitable template
+ # the controller will and it will not find a suitable template
controller.render plain: 'success'
end
call_action
diff --git a/spec/factories/work_packags_export_factory.rb b/spec/factories/work_packags_export_factory.rb
new file mode 100644
index 00000000000..65bb6fc2d3a
--- /dev/null
+++ b/spec/factories/work_packags_export_factory.rb
@@ -0,0 +1,33 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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.
+#++
+
+FactoryBot.define do
+ factory :work_packages_export, class: WorkPackages::Export do
+
+ end
+end
diff --git a/spec/features/work_packages/export_spec.rb b/spec/features/work_packages/export_spec.rb
index e30916a23de..422df1a285c 100644
--- a/spec/features/work_packages/export_spec.rb
+++ b/spec/features/work_packages/export_spec.rb
@@ -55,7 +55,7 @@ describe 'work package export', type: :feature do
wp_3
wp_4
- allow(User).to receive(:current).and_return current_user
+ login_as(current_user)
end
subject { DownloadedFile.download_content }
@@ -67,22 +67,26 @@ describe 'work package export', type: :feature do
settings_menu.open_and_choose 'Export ...'
click_on 'CSV'
- end
- before do
- # render the CSV as plain text so we can run expectations against the output
- expect_any_instance_of(WorkPackagesController)
- .to receive(:send_data) do |receiver, serialized_work_packages, _opts|
- receiver.render plain: serialized_work_packages
- end
+ perform_enqueued_jobs
+ # Wait for the file to download
+ ::DownloadedFile.wait_for_download
+ ::DownloadedFile.wait_for_download_content
end
+ #before do
+ # # render the CSV as plain text so we can run expectations against the output
+ # expect_any_instance_of(WorkPackagesController)
+ # .to receive(:send_data) do |receiver, serialized_work_packages, _opts|
+ # receiver.render plain: serialized_work_packages
+ # end
+ #end
+
after do
DownloadedFile::clear_downloads
end
context 'with default filter' do
-
before do
work_packages_page.visit_index
filters.expect_filter_count 1
diff --git a/spec/models/work_package/exporter/csv_integration_spec.rb b/spec/models/work_package/exporter/csv_integration_spec.rb
new file mode 100644
index 00000000000..ce2707c1b1c
--- /dev/null
+++ b/spec/models/work_package/exporter/csv_integration_spec.rb
@@ -0,0 +1,88 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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 WorkPackage::Exporter::CSV, 'integration', type: :model do
+ before do
+ login_as current_user
+ end
+
+ let(:project) { FactoryBot.create(:project) }
+
+ let(:current_user) do
+ FactoryBot.create(:user,
+ member_in_project: project,
+ member_with_permissions: %i(view_work_packages))
+ end
+ let(:query) do
+ Query.new(name: '_').tap do |query|
+ query.column_names = %i(subject assigned_to updated_at)
+ end
+ end
+ let(:instance) do
+ described_class.new(query)
+ end
+
+ describe 'list' do
+ ##
+ # When Ruby tries to join the following work package's subject encoded in ISO-8859-1
+ # and its description encoded in UTF-8 it will result in a CompatibilityError.
+ # This would not happen if the description contained only letters covered by
+ # ISO-8859-1. Since this can happen, though, it is more sensible to encode everything
+ # in UTF-8 which gets rid of this problem altogether.
+ let!(:work_package) do
+ FactoryBot.create(
+ :work_package,
+ subject: "Ruby encodes ß as '\\xDF' in ISO-8859-1.",
+ description: "\u2022 requires unicode.",
+ assigned_to: current_user,
+ project: project
+ )
+ end
+
+ it 'performs a successful export' do
+ work_package.reload
+
+ data = ''
+
+ instance.list do |result|
+ data = result.content
+ end
+ data = CSV.parse(data)
+
+ expect(data.size).to eq(2)
+ expect(data.last).to include(work_package.subject)
+ expect(data.last).to include(work_package.description)
+ expect(data.last).to include(current_user.name)
+ expect(data.last).to include(work_package.updated_at.localtime.strftime("%m/%d/%Y %I:%M %p"))
+ end
+ end
+end
diff --git a/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb b/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb
index 35f5bb81ecf..75e485db8af 100644
--- a/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb
+++ b/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb
@@ -105,7 +105,7 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
end
describe '#post' do
- let(:permissions) { %i[edit_wiki_pages] }
+ let(:permissions) { Array(update_permission) }
let(:request_path) { api_v3_paths.attachments }
let(:request_parts) { { metadata: metadata, file: file } }
@@ -173,7 +173,20 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
end
context 'missing permissions' do
- let(:permissions) { [] }
+ let(:permissions) do
+ # Some attachables use public permissions
+ # which more or less allows everybody to upload attachments.
+ # This messes with the tests.
+ # However, it might make sense to reevaluate the necessity of this test.
+ allow(Redmine::Acts::Attachable)
+ .to receive(:attachables)
+ .and_return(Redmine::Acts::Attachable.attachables.select do |a|
+ permission = OpenProject::AccessControl.permission(a.attachable_options[:add_on_new_permission])
+ !permission || !permission.public?
+ end)
+
+ []
+ end
it_behaves_like 'unauthorized access'
end
@@ -200,7 +213,13 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
shared_examples_for 'does not delete the attachment' do |status = 403|
it "responds with #{status}" do
- expect(subject.status).to eq status
+ if permissions.any? || read_permission.nil?
+ expect(subject.status).to eq status
+ else
+ # In case no permissions are left, the user is not allowed to see the attachment
+ # and will thus receive a 404.
+ expect(subject.status).to eq 404
+ end
end
it 'does not delete the attachment' do
@@ -257,7 +276,7 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
let(:content_disposition) { raise "define content_disposition" }
let(:attachment) do
- att = FactoryBot.create(:attachment, container: container, file: mock_file)
+ att = FactoryBot.create(:attachment, container: container, file: mock_file, author: current_user)
att.file.store!
att.send :write_attribute, :file, mock_file.original_filename
@@ -308,9 +327,11 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
context 'for a local json file' do
it_behaves_like 'for a local file' do
- let(:mock_file) { FileHelpers.mock_uploaded_file ({ name: 'foobar.json',
- content_type: "application/json",
- content: '{"id": "12342"}' }) }
+ let(:mock_file) do
+ FileHelpers.mock_uploaded_file(name: 'foobar.json',
+ content_type: "application/json",
+ content: '{"id": "12342"}')
+ end
let(:content_disposition) { "attachment; filename=foobar.json" }
end
end
@@ -319,7 +340,7 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
let(:external_url) { 'http://some_service.org/blubs.gif' }
let(:mock_file) { FileHelpers.mock_uploaded_file name: 'foobar.txt' }
let(:attachment) do
- FactoryBot.create(:attachment, container: container, file: mock_file) do |a|
+ FactoryBot.create(:attachment, container: container, file: mock_file, author: current_user).tap do
# need to mock here to avoid dependency on external service
allow_any_instance_of(Attachment)
.to receive(:external_url)
diff --git a/spec/requests/api/v3/attachments/work_packages_export_spec.rb b/spec/requests/api/v3/attachments/work_packages_export_spec.rb
new file mode 100644
index 00000000000..2eb17dd61a3
--- /dev/null
+++ b/spec/requests/api/v3/attachments/work_packages_export_spec.rb
@@ -0,0 +1,104 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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'
+require_relative './attachment_resource_shared_examples'
+
+describe "WorkPackages::Export attachments" do
+ it_behaves_like "an APIv3 attachment resource", include_by_container = false do
+ let(:attachment_type) { :export }
+
+ let(:create_permission) { :export_work_packages }
+ let(:read_permission) { :export_work_packages }
+ let(:update_permission) { :export_work_packages }
+
+ let(:export) { FactoryBot.create(:work_packages_export, user: author) }
+
+ let(:missing_permissions_user) { FactoryBot.create(:user) }
+ let(:other_user) { FactoryBot.create(:user) }
+
+ let(:other_user_attachment) { FactoryBot.create(:attachment, container: export, author: other_user) }
+
+ describe '#get' do
+ subject(:response) { last_response }
+ let(:get_path) { api_v3_paths.attachment attachment.id }
+
+ before do
+ get get_path
+ end
+
+ context 'for a user different from the author' do
+ let(:attachment) { other_user_attachment }
+
+ it 'responds with 404' do
+ expect(subject.status).to eq(404)
+ end
+ end
+ end
+
+ describe '#delete' do
+ let(:path) { api_v3_paths.attachment attachment.id }
+
+ before do
+ delete path
+ end
+
+ context 'for a user different from the author' do
+ let(:attachment) { other_user_attachment }
+
+ subject(:response) { last_response }
+
+ it "responds with 404" do
+ expect(subject.status).to eq 404
+ end
+
+ it 'does not delete the attachment' do
+ expect(Attachment.exists?(attachment.id)).to be_truthy
+ end
+ end
+ end
+
+ describe '#content' do
+ let(:path) { api_v3_paths.attachment_content attachment.id }
+
+ before do
+ get path
+ end
+
+ subject(:response) { last_response }
+
+ context 'for a user different from the author' do
+ let(:attachment) { other_user_attachment }
+
+ it "responds with 404" do
+ expect(subject.status).to eq 404
+ end
+ end
+ end
+ end
+end
diff --git a/spec/routing/work_packages/exports_spec.rb b/spec/routing/work_packages/exports_spec.rb
new file mode 100644
index 00000000000..4ca82ab7a80
--- /dev/null
+++ b/spec/routing/work_packages/exports_spec.rb
@@ -0,0 +1,35 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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 'work_package exports routes', type: :routing do
+ it '/work_packages/exports/:id GET routes to work_packages/exports#show' do
+ expect(get('/work_packages/exports/5')).to route_to('work_packages/exports#show', id: "5")
+ end
+end
diff --git a/spec/workers/work_packages/exports/export_job_spec.rb b/spec/workers/work_packages/exports/export_job_spec.rb
new file mode 100644
index 00000000000..0ed8560da07
--- /dev/null
+++ b/spec/workers/work_packages/exports/export_job_spec.rb
@@ -0,0 +1,100 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# 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 WorkPackages::Exports::ExportJob do
+ let(:user) { FactoryBot.build_stubbed(:user) }
+ let(:export) do
+ FactoryBot.build_stubbed(:work_packages_export, user: user)
+ end
+ let(:query) { FactoryBot.build_stubbed(:query) }
+
+ let(:instance) { described_class.new }
+ let(:options) { {} }
+ subject do
+ instance.perform(export: export,
+ mime_type: mime_type,
+ options: options,
+ query: query)
+ end
+
+ shared_examples_for 'exporter returning string' do
+ it 'exports' do
+ content = 'some string'
+
+ result = WorkPackage::Exporter::Result::Success.new(format: 'blubs',
+ title: "some_title.#{mime_type}",
+ content: content,
+ mime_type: "application/octet-stream")
+
+ service = double('attachments create service')
+
+ expect(Attachments::CreateService)
+ .to receive(:new)
+ .with(export, author: user)
+ .and_return(service)
+
+ expect(WorkPackages::Exports::CleanupOutdatedJob)
+ .to receive(:perform_after_grace)
+
+ expect(service)
+ .to receive(:call) do |uploaded_file:, description:|
+ expect(File.basename(uploaded_file))
+ .to start_with 'some_title'
+
+ expect(File.basename(uploaded_file))
+ .to end_with ".#{mime_type}"
+ end
+
+ allow("WorkPackage::Exporter::#{mime_type.upcase}".constantize)
+ .to receive(:list)
+ .and_yield(result)
+
+ subject
+ end
+ end
+
+ describe '#perform' do
+ context 'with the pdf mime type' do
+ let(:mime_type) { :pdf }
+
+ it_behaves_like 'exporter returning string'
+ end
+ end
+
+ describe '#perform' do
+ context 'with the csv mime type' do
+ let(:mime_type) { :csv }
+
+ it_behaves_like 'exporter returning string'
+ end
+ end
+end