Ejemplo n.º 1
0
        public async Task <IActionResult> Import(Guid commissionStatementId, [FromQuery] Guid commissionStatementTemplateId, [FromQuery] Guid?userId)
        {
            var scope = AuthenticationService.GetScope(User);

            var file = Request.Form.Files.FirstOrDefault();

            if (file == null)
            {
                return(BadRequest());
            }

            var statement = await CommissionStatementService.GetCommissionStatement(scope, commissionStatementId);

            var template = await CommissionStatementTemplateService.GetTemplate(commissionStatementTemplateId);

            string brokerFullName = null;

            if (template.BrokerSpecific)
            {
                if (!userId.HasValue)
                {
                    return(this.BadRequestMessage("UserId required for broker specific templates."));
                }

                var user = await UserService.GetUser(scope, userId.Value);

                if (user == null)
                {
                    return(this.BadRequestMessage("Invalid UserId."));
                }

                brokerFullName = $"{user.FirstName} {user.LastName}";
            }

            var config = template.Config;

            var result = new ImportResult();

            using (var stream = file.OpenReadStream())
            {
                var vatRate = await DirectoryLookupService.GetVATRate(statement.Date ?? DateTime.Now);

                var reader = new CommissionImportReader(config, vatRate, brokerFullName);
                var items  = reader.Read(stream);

                result = await CommissionImportService.ImportCommissions(scope, commissionStatementId, items);
            }

            if (result.UnknownCommissionTypeValues.Any())
            {
                using (var stream = file.OpenReadStream())
                {
                    var attachment = GetEmailAttachment(file, stream);
                    await SendUnkownCommissionTypesEmail(result, scope, commissionStatementId, template, attachment);
                }
            }

            if (!result.Results.Any(r => r.Success))
            {
                using (var stream = file.OpenReadStream())
                {
                    var attachment = GetEmailAttachment(file, stream);
                    await SendZeroEntriesEmail(scope, commissionStatementId, template, attachment);
                }
            }

            if (result.Results.Any())
            {
                using (var stream = file.OpenReadStream())
                {
                    var path = new CommissionStatementFilePath(scope.OrganisationId, commissionStatementId, file.FileName);
                    await FileStorageService.AddFileAsync(path, stream);
                }
            }

            return(Ok(result));
        }