Exemplo n.º 1
0
 private Document Create(int serviceSupplierId, Models.Requests.Document document) => new Document
 {
     Name              = document.UploadedFile.FileName,
     ContentType       = document.UploadedFile.ContentType,
     Key               = string.Empty,
     Created           = _dateTimeProvider.UtcNow(),
     ServiceSupplierId = serviceSupplierId,
     ContractId        = document.ContractId
 };
Exemplo n.º 2
0
        public Task <Result <Models.Responses.Document> > Add(Models.Requests.Document document)
        {
            return(_managerContext.GetServiceSupplier()
                   .Check(serviceSupplier => _serviceSupplierContext.EnsureContractBelongsToServiceSupplier(serviceSupplier, document.ContractId))
                   .Bind(serviceSupplier =>
            {
                var validationResult = ValidationHelper.Validate(document, new DocumentValidator());

                return validationResult.IsFailure ? Result.Failure <ServiceSupplier>(validationResult.Error) : Result.Success(serviceSupplier);
            })
                   .Map(serviceSupplier => Create(serviceSupplier.Id, document))
                   .Map(dbDocument => AddDocument(dbDocument, document.UploadedFile))
                   .Ensure(dbDocument => dbDocument != null, "Error saving document")
                   .Map(dbDocument => Build(dbDocument)));


            async Task <Document> AddDocument(Document dbDocument, FormFile uploadedFile)
            {
                var extension = Path.GetExtension(uploadedFile.FileName);

                var entry = _dbContext.Documents.Add(dbDocument);

                await _dbContext.SaveChangesAsync();

                entry.Entity.Key = $"{S3FolderName}/{dbDocument.ContractId}/{entry.Entity.Id}{extension}";

                var result = await _amazonS3ClientService.Add(_bucketName, dbDocument.Key, uploadedFile.OpenReadStream(), S3CannedACL.Private);

                if (result.IsFailure)
                {
                    _dbContext.Documents.Remove(entry.Entity);

                    await _dbContext.SaveChangesAsync();

                    return(null);
                }

                await _dbContext.SaveChangesAsync();

                _dbContext.DetachEntry(entry.Entity);

                return(entry.Entity);
            }
        }