Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VCST-420: Use new file uploader in the back office #105

Merged
merged 6 commits into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions module.ignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ PipelineNet.dll
SixLabors.ImageSharp.dll
sni.dll
TimeZoneConverter.dll
VirtoCommerce.FileExperienceApi.Core.dll
VirtoCommerce.FileExperienceApi.Data.dll
VirtoCommerce.ImageTools.ImageAbstractions.dll
VirtoCommerce.Tools.dll
VirtoCommerce.XDigitalCatalog.dll
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VirtoCommerce.CartModule.Core.Model;
using VirtoCommerce.FileExperienceApi.Core.Models;
using VirtoCommerce.FileExperienceApi.Core.Services;
using VirtoCommerce.OrdersModule.Core.Model;
using VirtoCommerce.OrdersModule.Core.Services;
using VirtoCommerce.Platform.Core.Common;
using VirtoCommerce.QuoteModule.Core;
using VirtoCommerce.QuoteModule.Core.Models;
using VirtoCommerce.QuoteModule.Core.Services;
using VirtoCommerce.ShippingModule.Core.Model.Search;
Expand All @@ -28,21 +31,24 @@ public class QuoteModuleController : Controller
private readonly IShippingMethodsSearchService _shippingMethodsSearchService;
private readonly IQuoteConverter _quoteConverter;
private readonly ICustomerOrderBuilder _customerOrderBuilder;
private readonly IFileUploadService _fileUploadService;

public QuoteModuleController(
IQuoteRequestService quoteRequestService,
IQuoteTotalsCalculator totalsCalculator,
IStoreService storeService,
IShippingMethodsSearchService shippingMethodsSearchService,
IQuoteConverter quoteConverter,
ICustomerOrderBuilder customerOrderBuilder)
ICustomerOrderBuilder customerOrderBuilder,
IFileUploadService fileUploadService)
{
_quoteRequestService = quoteRequestService;
_totalsCalculator = totalsCalculator;
_storeService = storeService;
_shippingMethodsSearchService = shippingMethodsSearchService;
_quoteConverter = quoteConverter;
_customerOrderBuilder = customerOrderBuilder;
_fileUploadService = fileUploadService;
}

/// <summary>
Expand Down Expand Up @@ -228,5 +234,11 @@ public async Task<ActionResult> UpdateStatus([FromRoute] string id, [FromQuery]

return NoContent();
}

[HttpGet("attachments/options")]
public Task<FileUploadScopeOptions> GetAttachmentOptions()
{
return _fileUploadService.GetOptionsAsync(ModuleConstants.QuoteAttachmentsScope);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,16 @@
}
}
},
"file-upload-error": {
"status": "Error",
"status-text": "File upload failed",
"invalid-configuration": "File upload scope is not configured",
"template": "{{fileName}}: {{errorMessage}}",
"duplicate-name": "File with the same name already exists",
"INVALID_SIZE": "File size exceeds {{parameter}} bytes",
"INVALID_EXTENSION": "File type is not one of the allowed types ({{parameter}})",
"UNKNOWN_ERROR": "Unknown error: {{message}}"
},
"module": {
"VirtoCommerce.Quote": {
"description": "Export or import quote requests (RFQs)"
Expand Down
193 changes: 150 additions & 43 deletions src/VirtoCommerce.QuoteModule.Web/Scripts/blades/quote-assets.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,156 @@
angular.module('virtoCommerce.quoteModule')
.controller('virtoCommerce.quoteModule.quoteAssetController', ['$scope', 'virtoCommerce.catalogModule.items', 'platformWebApp.bladeNavigationService', '$filter', 'FileUploader', 'platformWebApp.dialogService', '$injector', function ($scope, items, bladeNavigationService, $filter, FileUploader, dialogService, $injector) {
var blade = $scope.blade;
blade.updatePermission = 'quote:update';
$scope.currentEntities = blade.currentEntities = blade.currentEntity.attachments;

function initialize() {
if (!$scope.uploader && blade.hasUpdatePermission()) {
// create the uploader
var uploader = $scope.uploader = new FileUploader({
scope: $scope,
headers: { Accept: 'application/json' },
url: 'api/assets?folderUrl=quote/' + blade.currentEntity.id,
method: 'POST',
autoUpload: true,
removeAfterUpload: true
});

uploader.onSuccessItem = function (fileItem, assets, status, headers) {
angular.forEach(assets, function (asset) {
//ADD uploaded asset
blade.currentEntities.push(asset);
});
.controller('virtoCommerce.quoteModule.quoteAssetController', [
'$scope', '$translate', 'platformWebApp.bladeNavigationService', 'virtoCommerce.quoteModule.quotes', 'FileUploader',
function ($scope, $translate, bladeNavigationService, quotes, FileUploader) {
var blade = $scope.blade;
blade.updatePermission = 'quote:update';
$scope.currentEntities = blade.currentEntities = blade.currentEntity.attachments;

var _canUpload = true;
var _options = null;
const _fileErrors = [];
const _uploadError = {
status: translate('status'),
statusText: translate('status-text'),
data: {
errors: _fileErrors,
},
};

uploader.onAfterAddingAll = function (addedItems) {
bladeNavigationService.setError(null, blade);
$scope.canUpload = function () {
return _canUpload && blade.hasUpdatePermission();
}

function initialize() {
if ($scope.uploader || !blade.hasUpdatePermission()) {
blade.isLoading = false;
return;
}

// create the uploader
var uploader = $scope.uploader = new FileUploader({
scope: $scope,
headers: { Accept: 'application/json' },
method: 'POST',
autoUpload: true,
removeAfterUpload: true
});

uploader.onAfterAddingAll = function (items) {
clearErrors();

angular.forEach(items, function (item) {
const result = validateFile(item.file);
if (!result.succeeded) {
addFileError(item.file.name, result.errorCode, result.errorParameter);
}
});

if (_fileErrors.length > 0) {
uploader.clearQueue();
}
};

uploader.onSuccessItem = function (item, response, status, headers) {
angular.forEach(response, function (result) {
if (result.succeeded === false) {
addFileError(item.file.name, result.errorCode, result.errorParameter, result.errorMessage);
}
else {
result.mimeType = result.contentType;
blade.currentEntities.push(result);
}
});
};

uploader.onErrorItem = function (item, response, status, headers) {
addFileError(item.file.name, 'UNKNOWN_ERROR', status, response.message);
};

quotes.getAttachmentOptions(function (options) {
if (!options.scope) {
_canUpload = false;
bladeNavigationService.setError(translate('invalid-configuration'), blade);
}
else {
options.allowedExtensions = options.allowedExtensions.map(x => x.toLowerCase());
uploader.url = `/api/files/${options.scope}`;
_options = options;
}

blade.isLoading = false;
});
}

$scope.removeAction = function (asset) {
const idx = blade.currentEntities.indexOf(asset);
if (idx >= 0) {
blade.currentEntities.splice(idx, 1);
}
};

uploader.onErrorItem = function (item, response, status, headers) {
bladeNavigationService.setError(item._file.name + ' failed: ' + (response.message ? response.message : status), blade);
$scope.copyUrl = function (data) {
var link = document.createElement("a");
link.href = data.url;
window.prompt('Copy to clipboard: Ctrl+C, Enter', link.href);
};
}
}

$scope.removeAction = function (asset) {
var idx = blade.currentEntities.indexOf(asset);
if (idx >= 0) {
blade.currentEntities.splice(idx, 1);
}
};

$scope.copyUrl = function (data) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", data.url);
};

initialize();
blade.isLoading = false;
}]);

function validateFile(file) {
const result = {
succeeded: true,
};

const existingFileNames = blade.currentEntities.map(x => x.name.toLowerCase());

if (existingFileNames.includes(file.name.toLowerCase())) {
result.succeeded = false;
result.errorCode = 'duplicate-name';
}
else if (_options) {
if (file.size > _options.maxFileSize) {
result.succeeded = false;
result.errorCode = 'INVALID_SIZE';
result.errorParameter = _options.maxFileSize;
}
else {
if (_options.allowedExtensions.length) {
const fileExtension = /(\.[^.]+)?$/.exec(file.name)?.[1]?.toLowerCase();
if (!_options.allowedExtensions.includes(fileExtension)) {
result.succeeded = false;
result.errorCode = 'INVALID_EXTENSION';
result.errorParameter = _options.allowedExtensions;
}
}
}
}

return result;
}

function clearErrors() {
_fileErrors.length = 0;
bladeNavigationService.clearError(blade);
}

function addFileError(fileName, code, parameter, message) {
if (code === 'INVALID_EXTENSION' && Array.isArray(parameter)) {
parameter = parameter.join(', ');
}

var errorMessage = translateError(code, { parameter: parameter, message: message }) || message || parameter;
const error = translate('template', { fileName: fileName, errorMessage: errorMessage });
_fileErrors.push(error);
bladeNavigationService.setError(_uploadError, blade);
}

function translateError(key, parameters) {
const result = translate(key, parameters);
return result !== key ? result : null;
}

function translate(key, parameters) {
return $translate.instant(`file-upload-error.${key}`, parameters);
}

initialize();
}]);
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
<div class="blade-inner">
<div class="inner-block">
<div class="inner">
<div class="sub-t" va-permission="{{blade.updatePermission}}">{{ 'quotes.blades.quotes-assets.labels.select-files' | translate }}</div>
<form class="form" ng-if="blade.hasUpdatePermission()">
<div class="sub-t" ng-if="canUpload()">{{ 'quotes.blades.quotes-assets.labels.select-files' | translate }}</div>
<form class="form" ng-if="canUpload()">
<div ng-show="uploader.isHTML5">
<!-- 3. ng-file-over | ng-file-over="className" -->
<div class="well my-drop-zone panel drag-area" uploader="uploader" nv-file-drop nv-file-over>
Expand Down
19 changes: 10 additions & 9 deletions src/VirtoCommerce.QuoteModule.Web/Scripts/resources/quotes.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
angular.module('virtoCommerce.quoteModule')
.factory('virtoCommerce.quoteModule.quotes', ['$resource', function ($resource) {
return $resource('api/quote/requests/:id', {}, {
search: { method: 'POST', url: 'api/quote/requests/search' },
getShippingMethods: { url: 'api/quote/requests/:id/shipmentmethods', isArray: true },
recalculate: { method: 'PUT', url: 'api/quote/requests/recalculate' },
update: { method: 'PUT' }
});
}]);
angular.module('virtoCommerce.quoteModule')
.factory('virtoCommerce.quoteModule.quotes', ['$resource', function ($resource) {
return $resource('api/quote/requests/:id', {}, {
search: { method: 'POST', url: 'api/quote/requests/search' },
getShippingMethods: { url: 'api/quote/requests/:id/shipmentmethods', isArray: true },
getAttachmentOptions: { url: 'api/quote/requests/attachments/options' },
recalculate: { method: 'PUT', url: 'api/quote/requests/recalculate' },
update: { method: 'PUT' }
});
}]);
16 changes: 0 additions & 16 deletions tests/VirtoCommerce.QuoteModule.Tests/QuoteMockTest.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<None Remove="Properties\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PackageReference Include="coverlet.collector" Version="6.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
Loading