Exemple #1
0
        public async Task <IEnumerable <ReferentialCounterPartySearchResultDto> > SearchReferentialCounterPartyListAsync(string company, EntitySearchRequest searchRequest, bool showDuplicateCounterpartyData = false)
        {
            var grideCode = "referentialCounterPartiesGrid";

            var grid = await _gridQueries.GetGrid(grideCode, company);

            if (grid == null)
            {
                throw new AtlasTechnicalException($"No grid configuration found for {grideCode}.");
            }

            if (grid.MaxNumberOfRecords.HasValue && grid.MaxNumberOfRecords < searchRequest.Limit)
            {
                searchRequest.Limit = grid.MaxNumberOfRecords;
            }

            var dynamicQueryDefinition = AutoMapper.Mapper.Map <DynamicQueryDefinition>(searchRequest);

            var columnConfiguration = AutoMapper.Mapper.Map <List <ColumnConfiguration> >(grid.Columns);

            var companyDate = await _systemDateTimeService.GetCompanyDate(company);

            var buildQueryResult = DynamicQueryBuilder.BuildQuery(company, _identityService.GetUserName(), dynamicQueryDefinition, "[Configuration].[Vw_ReferentialCounterPartyListAndSearch]", columnConfiguration, companyDate);

            var referentialCounterPartySearchResult = await ExecuteDynamicQueryAsync <ReferentialCounterPartySearchResultDto>(buildQueryResult.Sql, buildQueryResult.Parameters);

            if (showDuplicateCounterpartyData == false)
            {
                var result = referentialCounterPartySearchResult.ToList();
                return(result.GroupBy(counterpartyData => counterpartyData.CounterpartyCode).Select(duplicateRow => duplicateRow.First()));
            }

            return(referentialCounterPartySearchResult.ToList());
        }
Exemple #2
0
        public async Task <Unit> Handle(ProcessInterfaceDataChangeLogsRequest request, CancellationToken cancellationToken)
        {
            var paymentRequestStatus = await _paymentRequestRepository.GetPaymentRequestStatus((int)BusinessApplicationType.TRAX, request.CompanyId, null, request.TransactionDocumentId);

            if (paymentRequestStatus == null || ((InterfaceStatus)paymentRequestStatus.DocumentStatus == InterfaceStatus.None || (InterfaceStatus)paymentRequestStatus.DocumentStatus == InterfaceStatus.TransmitError))
            {
                long eventId;
                _unitOfWork.BeginTransaction();
                var eventdata = new Event((int)EventSubType.PaymentRequest, request.CashId, request.CashDocumentRef, (int)InterfaceStatus.ReadyToTransmit, request.CompanyId, null);
                try
                {
                    eventId = await _interfaceEventLogService.CreateEventAsync(eventdata);

                    // Insert record into InterfaceStatus
                    await ProcessStatusUpdate(request, InterfaceStatus.ReadyToTransmit, "Ready To Transmit");

                    _unitOfWork.Commit();
                }
                catch
                {
                    _unitOfWork.Rollback();
                    throw;
                }

                var companyDate = await _systemDateTimeService.GetCompanyDate(request.CompanyId);

                _logger.LogInformation("Cash with DocumentId {Atlas_PaymentRequestCashDocumentId} having status {Atlas_PaymentRequestStatus} is sent to Treasury System at {Atlas_DateTime}", request.CashDocumentRef, InterfaceStatus.ReadyToTransmit, companyDate);

                var paymentRequestMessage = await _paymentRequestRepository.GetTRAXMessageAsync(request.CashId, request.CompanyId);

                var eventHistory = new EventHistory(eventId, "Message Generated", paymentRequestMessage, null, null);
                _unitOfWork.BeginTransaction();
                try
                {
                    await _interfaceEventLogService.CreateEventHistoryAsync(eventHistory, request.CompanyId);

                    _unitOfWork.Commit();
                }
                catch
                {
                    _unitOfWork.Rollback();
                    throw;
                }

                var legalEntityCode = await _paymentRequestRepository.GetLegalEntityCodeAsync(request.CompanyId, request.BusinessApplicationType);

                await SendBusinessObjectToInterface(request, paymentRequestMessage, legalEntityCode, eventId);
            }
            else
            {
                _logger.LogWarning("Invalid Document ({Atlas_DocumentReference}) status {Atlas_InterfaceStatus}.", request.DocumentReference, ((InterfaceStatus)paymentRequestStatus.DocumentStatus).ToString());
            }

            return(Unit.Value);
        }
Exemple #3
0
        protected virtual async Task <IEnumerable <T> > SearchAsync <T>(string company, EntitySearchRequest searchRequest, string gridCode, string viewName, bool skipPaginationLimit = false)
        {
            var grid = await _gridQueries.GetGrid(gridCode, company);

            if (grid == null)
            {
                throw new AtlasTechnicalException($"No grid configuration found for {gridCode}.");
            }

            if (!skipPaginationLimit && grid.MaxNumberOfRecords.HasValue && grid.MaxNumberOfRecords < searchRequest.Limit)
            {
                searchRequest.Limit = grid.MaxNumberOfRecords;
            }

            var dynamicQueryDefinition = _mapper.Map <DynamicQueryDefinition>(searchRequest);

            var columnConfiguration = _mapper.Map <List <ColumnConfiguration> >(grid.Columns);

            var companyDate = await _systemDateTimeService.GetCompanyDate(company);

            var userDepartments = (await _userService.GetUserByIdAsync(_identityService.GetUserAtlasId(), false)).Permissions
                                  .FirstOrDefault(permission => permission.CompanyId == company)
                                  ?.Departments.Select(department => department.DepartmentId).ToList();

            var dataVersionId = searchRequest.DataVersionId ?? await _systemDateTimeService.GetCompanyCurrentDataVersionId(company);

            var buildQueryResult = DynamicQueryBuilder.BuildQuery(company, _identityService.GetUserName(), dynamicQueryDefinition, viewName, columnConfiguration, companyDate, dataVersionId, userDepartments);

            var results = await ExecuteDynamicQueryAsync <T>(buildQueryResult.Sql, buildQueryResult.Parameters);

            return(results.ToList());
        }
        public async Task <long> Handle(GenerateContractAdviceCommand request, CancellationToken cancellationToken)
        {
            var authorizationResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), Policies.GenerateContractAdvicePolicy);

            if (!authorizationResult.Succeeded)
            {
                throw new AtlasSecurityException("One or more privileges are required to perform this action.");
            }

            var template = await _physicalDocumentGenerationService.GetTemplateByPath(request.DocumentTemplatePath, PhysicalDocumentType.ContractAdvice, request.CompanyId);

            if (template == null)
            {
                throw new AtlasBusinessException($"Cannot find requested template: {request.DocumentTemplatePath}");
            }

            var contractAdviceInfo = await _documentRepository.GetContractAdviceInfoAsync(request.SectionId, request.CompanyId);

            var reportParameters = new Dictionary <string, string>
            {
                { "CompanyId", request.CompanyId },
                { "PhysicalContractId", contractAdviceInfo.PhysicalContractId.ToString(CultureInfo.InvariantCulture) }
            };

            var documentResponse = await _physicalDocumentGenerationService.GenerateDocument(request.DocumentTemplatePath, reportParameters, PhysicalDocumentFormat.WORDOPENXML);

            var companyDate = await _systemDateTimeService.GetCompanyDate(request.CompanyId);

            string counterPartyCode = contractAdviceInfo.Type == ContractType.Purchase ? contractAdviceInfo.SellerCode : contractAdviceInfo.BuyerCode;

            var documentName = $"{companyDate.ToString("yyyyMMdd_HHMMss", CultureInfo.InvariantCulture)}_{request.CompanyId}_CONADV_{request.SectionId}_PREVIEW_{counterPartyCode}_{_identityService.GetUserName()}.{documentResponse.Extension}";

            // Save document in database
            var documentId = await _physicalDocumentStorageService.UploadDocument(
                new UploadDocumentParameters
            {
                CompanyId              = request.CompanyId,
                DocumentName           = documentName,
                File                   = documentResponse.Result,
                DocumentTemplatePath   = template.Path,
                PhysicalDocumentTypeId = PhysicalDocumentType.ContractAdvice,
                PhysicalDocumentStatus = PhysicalDocumentStatus.New,
                RecordId               = request.SectionId,
                TableId                = request.TableId,
                IsDraft                = true
            });

            _logger.LogInformation("Document with id {Atlas_DocumentId} has been created by user {Atlas_UserId}.", documentId, _identityService.GetUserName());

            return(documentId);
        }
Exemple #5
0
        public async Task <int> Handle(CreateReportCriteriasCommand request, CancellationToken cancellationToken)
        {
            _unitOfWork.BeginTransaction();

            try
            {
                var grid = await _gridQueries.GetGrid(request.ReportCriterias.GridName, request.Company);

                if (grid == null)
                {
                    throw new Exception($"No grid configuration found for {request.ReportCriterias.GridName}.");
                }

                var dynamicQueryDefinition = Mapper.Map <DynamicQueryDefinition>(request.ReportCriterias);

                var columnConfiguration = Mapper.Map <List <ColumnConfiguration> >(grid.Columns);

                var companyDate = await _systemDateTimeService.GetCompanyDate(request.Company);

                var criterias = DynamicQueryBuilder.BuildReportFilters(dynamicQueryDefinition, columnConfiguration, companyDate);

                ReportPredicate predicate = new ReportPredicate
                {
                    CompanyId = request.Company,
                    Criterias = criterias.Select(c => new ReportCriteria {
                        Value = c.Item1, TableAlias = c.Item2
                    })
                };

                var predicateId = await _reportRepository.CreateReportCriteriasAsync(predicate);

                _unitOfWork.Commit();

                _logger.LogInformation("New report criterias created with id {Atlas_PredicateId}.", predicateId);

                return(predicateId);
            }
            catch
            {
                _unitOfWork.Rollback();
                throw;
            }
        }
Exemple #6
0
        public async Task <Unit> Handle(ProcessHeldAndMappingErrorDocumentCommand request, CancellationToken cancellationToken)
        {
            _unitOfWork.BeginTransaction();

            try
            {
                var companyDate = await _systemDateTimeService.GetCompanyDate(request.Company);

                IEnumerable <AccountingDocument> accountingDocuments = await _accountingQueries.GetAccountingDocumentInHeldAndMappingErrorState(request.Company);

                foreach (AccountingDocument accountingDocument in accountingDocuments)
                {
                    await CommonRules.CalculateFunctionalAndStatutoryCurrencyAccountingLine(_foreignExchangeRateService, accountingDocument);

                    AccountingSetupDto accountingSetup = await _accountingQueries.GetAccountingSetup((int)accountingDocument.TransactionDocumentTypeId, request.Company);

                    accountingDocument.StatusId = await ReturnAccountingDocumentStatus(accountingDocument, companyDate, request.Company, accountingSetup);

                    await _accountingDocumentRepository.UpdateAccountingDocument(accountingDocument, request.Company);

                    if (accountingDocument.StatusId == PostingStatus.Authorised)
                    {
                        bool postOpClosedPolicy = await CommonRules.CheckPrivileges(_authorizationService, _identityService);

                        await EnqueuePostingProcessorMessage(accountingDocument.AccountingId, request.Company, postOpClosedPolicy);
                    }
                }

                _unitOfWork.Commit();
            }
            catch
            {
                _unitOfWork.Rollback();

                throw;
            }

            return(Unit.Value);
        }
Exemple #7
0
        private async Task AuthorizeForPosting(List <long> listOfDocId, string company, bool postOpClosedPolicy)
        {
            List <AccountingDocument> accountDocumentsDto = (await _accountingDocumentRepository.GetAccountingDocumentsByAccountingIdsAsync(listOfDocId, company)).ToList();

            var companyDate = await _systemDateTimeService.GetCompanyDate(company);

            foreach (AccountingDocument accountingDocumentDto in accountDocumentsDto)
            {
                await CommonRules.CalculateFunctionalAndStatutoryCurrencyAccountingLine(_foreignExchangeRateService, accountingDocumentDto);

                AccountingSetupDto accountingSetup = await _accountingQueries.GetAccountingSetup((int)accountingDocumentDto.TransactionDocumentTypeId, company);

                accountingDocumentDto.StatusId = await CommonRules.ReturnAccountingDocumentStatus(_accountingQueries, accountingDocumentDto, companyDate, company, accountingSetup);

                await _accountingDocumentRepository.UpdateAccountingDocumentStatutoryAndFunctionalCurrencyAmounts(company, accountingDocumentDto);
            }

            var listOfAuthorizedDocument = accountDocumentsDto.Where(x => x.StatusId == PostingStatus.Authorised).ToList();

            foreach (AccountingDocument accountingDocument in listOfAuthorizedDocument)
            {
                await EnqueuePostingProcessorMessage(accountingDocument.AccountingId, company, postOpClosedPolicy);
            }
        }
        public async Task <Unit> Handle(UpdateSectionTrafficCommand request, CancellationToken cancellationToken)
        {
            _unitOfWork.BeginTransaction();

            try
            {
                var sectionTraffic = ConvertToSectionTraffic(request);

                var authorizationResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), sectionTraffic, Policies.CharterPolicy);

                var vesselNamePolicyResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), sectionTraffic, Policies.VesselNamePolicy);

                var blDatePolicyResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), sectionTraffic, Policies.BlDatePolicy);

                var blReferencePolicyResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), sectionTraffic, Policies.BlReferencePolicy);

                var quantityForTrafficPolicyResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), sectionTraffic, Policies.QuantityForTrafficPolicy);

                if (authorizationResult.Succeeded || vesselNamePolicyResult.Succeeded || blDatePolicyResult.Succeeded || blReferencePolicyResult.Succeeded || quantityForTrafficPolicyResult.Succeeded)
                {
                    if (request.DataVersionId != null)
                    {
                        var freezeDate = await _freezeRepository.GetFreezeNotClosedAsync(request.CompanyId, request.DataVersionId.Value);

                        if (freezeDate == null)
                        {
                            throw new AtlasBusinessException($"Contracts cannot be updated in a freeze if the month is closed.");
                        }
                    }

                    var companyDate = await _systemDateTimeService.GetCompanyDate(request.CompanyId);

                    if (request.BLDate != null && request.BLDate.Value.Date > companyDate.Date)
                    {
                        throw new AtlasBusinessException($"BL Date cannot be in the future. Bl Date: {request.BLDate.Value.Date}. Company date: {companyDate}.");
                    }

                    await _charterRepository.UpdateSectionTrafficDetailsAsync(sectionTraffic, request.CompanyId, request.DataVersionId);

                    if (request.DataVersionId != null)
                    {
                        await InsertFreezeRecalcProcessQueue(request.SectionId, request.DataVersionId, request.CompanyId);
                    }

                    _unitOfWork.Commit();

                    _logger.LogInformation("Section Traffic with id {Atlas_SectionId} updated.", request.SectionId);
                }
                else
                {
                    throw new AtlasSecurityException("One or more privileges are required to perform this action.");
                }

                return(Unit.Value);
            }
            catch
            {
                _unitOfWork.Rollback();
                throw;
            }
        }
Exemple #9
0
        public async Task <ActionResult <string> > GetCompanyDate(string companyId)
        {
            var companyDate = await _systemDateTimeService.GetCompanyDate(companyId);

            return(Ok(companyDate.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
        }
        public async Task <IEnumerable <SectionReference> > Handle(CreatePhysicalFixedPricedContractCommand request, CancellationToken cancellationToken)
        {
            List <SectionReference> sectionReferences = new List <SectionReference>();

            _unitOfWork.BeginTransaction();

            try
            {
                if (request.ContractReference?.Length > 0)
                {
                    request.ContractReference = request.ContractReference.PadLeft(7, '0');
                }

                var companyDate = await _systemDateTimeService.GetCompanyDate(request.CompanyId);

                if (request.ContractDate.Date > companyDate.Date)
                {
                    throw new AtlasBusinessException($"Contract date cannot be in the future. Contract date: {request.ContractDate.Date}. Company date: {companyDate}.");
                }

                if (request.DataVersionId != null)
                {
                    var freezeDate = await _freezeRepository.GetFreezeNotClosedAsync(request.CompanyId, request.DataVersionId.Value);

                    if (freezeDate == null)
                    {
                        throw new AtlasBusinessException($"Contracts cannot be created in a freeze if the month is closed.");
                    }

                    if (request.ContractReference == null)
                    {
                        throw new AtlasBusinessException($"Contract reference is mandatory in a frozen database.");
                    }
                }

                await PhysicalContractCommonRules.ValidatePhysicalContract(request, _identityService, _masterDataService, _userService, _systemDateTimeService);

                var user = _identityService.GetUserName();
                request.CreatedBy = user;
                var physicalFixedPricedContract = _mapper.Map <Section>(request);
                var company = await _masterDataService.GetCompanyByIdAsync(request.CompanyId);

                if (company.IsProvinceEnable)
                {
                    physicalFixedPricedContract.ProvinceId = company.DefaultProvinceId;
                    physicalFixedPricedContract.BranchId   = company.DefaultBranchId;
                }
                else
                {
                    physicalFixedPricedContract.ProvinceId = null;
                    physicalFixedPricedContract.BranchId   = null;
                }

                // At least one contract has to be always created
                physicalFixedPricedContract.NumberOfContract = (request.NumberOfContracts > 0) ? request.NumberOfContracts : 1;
                physicalFixedPricedContract.IsInterco        = request.IsInterco;

                if (!string.IsNullOrWhiteSpace(physicalFixedPricedContract.OtherReference))
                {
                    physicalFixedPricedContract.EstimatedMaturityDate = null;
                }

                physicalFixedPricedContract.EstimatedMaturityDate = await CalculateEstimatedMaturityDate(physicalFixedPricedContract, request.CompanyId);

                var references = (await _tradeRepository.CreatePhysicalContractAsImageAsync(physicalFixedPricedContract)).ToList();
                sectionReferences.AddRange(references);
                foreach (var item in references)
                {
                    if (item.SectionId > 0 && item.Quantity > 0 && physicalFixedPricedContract.Costs.Any())
                    {
                        foreach (var costItem in physicalFixedPricedContract.Costs)
                        {
                            costItem.CompanyId     = request.CompanyId;
                            costItem.SectionId     = item.SectionId;
                            costItem.DataVersionId = item.DataVersionId;
                        }

                        // check the business rule for PriceUnitId.
                        await _costRepository.AddCostsAsync(physicalFixedPricedContract.Costs, request.CompanyId, request.DataVersionId);
                    }

                    // request.ChildSections would not be null if only it is Imaging the trade and we have selected Image Splits/tranche option as well
                    if (request.ChildSections != null)
                    {
                        if (item.SectionId > 0 && request.ChildSections.Any())
                        {
                            CreateSplitCommand splitRequest = new CreateSplitCommand();
                            splitRequest.ChildSections = request.ChildSections;
                            splitRequest.ChildSections.ToList().ForEach(section => section.OriginalQuantity = 0);
                            splitRequest.CompanyId        = request.CompanyId;
                            splitRequest.OriginalQuantity = request.Quantity;
                            splitRequest.Quantity         = request.Quantity;
                            var sectionTrancheContract = _mapper.Map <SectionDeprecated>(splitRequest);
                            sectionTrancheContract.SectionId     = item.SectionId;
                            sectionTrancheContract.ContractLabel = item.ContractLabel;
                            foreach (var splitTrancheItem in sectionTrancheContract.ChildSections)
                            {
                                splitTrancheItem.SectionId             = 0;
                                splitTrancheItem.ContractId            = item.PhysicalContractId;
                                splitTrancheItem.SectionOriginId       = (int)item.SectionId;
                                splitTrancheItem.EstimatedMaturityDate = physicalFixedPricedContract.EstimatedMaturityDate;
                            }

                            bool isTradeImage          = true;
                            var  splitTranchReferences = await _tradeRepository.CreateTrancheSplitAsync(sectionTrancheContract, request.CompanyId, isTradeImage);

                            // Inserting cost while creating an Image of a trade,if available
                            foreach (var childItem in splitTranchReferences)
                            {
                                if (request.ChildSections.First().Costs != null)
                                {
                                    var childCosts = request.ChildSections.First().Costs;
                                    foreach (var costItem in childCosts)
                                    {
                                        costItem.CompanyId     = request.CompanyId;
                                        costItem.SectionId     = childItem.SectionId;
                                        costItem.DataVersionId = childItem.DataVersionId;
                                    }

                                    await _costRepository.AddCostsAsync(childCosts, request.CompanyId, request.DataVersionId);
                                }
                            }
                        }
                    }

                    if (request.IsInterco)
                    {
                        sectionReferences = await CreateIntercoContractOnCreateContract(request, physicalFixedPricedContract, references, sectionReferences);
                    }

                    if (request.DataVersionId != null)
                    {
                        // this might be incorrect. This is due to the code that is written above where you can create multiple contracts in your Current db with Image
                        await InsertFreezeRecalcProcessQueue(references[0].SectionId, request.DataVersionId, request.CompanyId);
                    }
                }

                _unitOfWork.Commit();
                _logger.LogInformation("New physical contract with id {Atlas_ContractLabel} created.", references[0].ContractLabel);

                return(sectionReferences);
            }
            catch
            {
                _unitOfWork.Rollback();
                throw;
            }
        }
        public async Task <Unit> Handle(ProcessInterfaceDataChangeLogsRequest request, CancellationToken cancellationToken)
        {
            int tAorJLTypeId = 0;
            // There should be no record in DB the first time.
            var docStatus = await _accountingInterfaceRepository.GetDocumentStatus((int)BusinessApplicationType.AX, request.CompanyId, null, request.TransactionDocumentId, request.DocumentId);

            var docReference = await _accountingInterfaceRepository.GetDocumentReferenceByAccountingId(request.DocumentId, (int)request.DocumentTypeId, request.CompanyId);

            if (docStatus == InterfaceStatus.None || docStatus == InterfaceStatus.TransmitError)
            {
                long eventId;
                if (request.DocumentTypeId == DocumentType.ManualTemporaryAdjustment)
                {
                    tAorJLTypeId = await _accountingInterfaceRepository.GetTATypeIdAsync(request.TransactionDocumentId, request.DocumentTypeId, request.CompanyId);
                }

                if (request.DocumentTypeId == DocumentType.RegularJournal)
                {
                    tAorJLTypeId = await _accountingInterfaceRepository.GetJLTypeIdAsync(request.TransactionDocumentId, request.DocumentTypeId, request.CompanyId);
                }

                EventSubType eventSubType = await GetEventSubType(request.DocumentTypeId, tAorJLTypeId);

                _unitOfWork.BeginTransaction();
                var eventdata = new Event((int)eventSubType, request.DocumentId, docReference, (int)InterfaceStatus.ReadyToTransmit, request.CompanyId, null);

                try
                {
                    eventId = await _interfaceEventLogService.CreateEventAsync(eventdata);

                    // Insert Record into InterfaceStatus
                    await ProcessStatusUpdate(request, InterfaceStatus.InterfaceReady, "Ready To be Interfaced");

                    _unitOfWork.Commit();
                }
                catch
                {
                    _unitOfWork.Rollback();
                    throw;
                }

                var companyDate = await _systemDateTimeService.GetCompanyDate(request.CompanyId);

                _logger.LogInformation("Accounting Document with DocumentId {Atlas_DocumentId} having status {Atlas_InterfaceStatus} is sent to Accounting System at {Atlas_DateTime}", request.DocumentId, docStatus.ToString(), companyDate);

                var accountingInterfaceXMLMessage = await _accountingInterfaceRepository.GetESBMessageAsync(request.DocumentId, request.CompanyId);

                var eventHistory = new EventHistory(eventId, "Message Generated", accountingInterfaceXMLMessage, null, null);
                _unitOfWork.BeginTransaction();
                try
                {
                    await _interfaceEventLogService.CreateEventHistoryAsync(eventHistory, request.CompanyId);

                    _unitOfWork.Commit();
                }
                catch
                {
                    _unitOfWork.Rollback();
                    throw;
                }

                await SendBusinessObjectToInterface(request, accountingInterfaceXMLMessage, tAorJLTypeId, eventId, false);
            }
            else
            {
                _logger.LogWarning("Invalid Document ({Atlas_DocumentReference}) status {Atlas_InterfaceStatus}.", request.DocumentReference, docStatus.ToString());
            }

            return(Unit.Value);
        }
        /// <summary>
        /// Handling the creation of an accounting document
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <IEnumerable <long> > Handle(CreateAccountingDocumentCommand request, CancellationToken cancellationToken)
        {
            _unitOfWork.BeginTransaction();
            IEnumerable <AccountingDocumentCreationStatus> accountingDocumentCreationStatusList = null;
            long accountingId = -1;
            IEnumerable <long> createdAccountingDocumentIds = null;

            Company company = null;

            try
            {
                TransactionDocumentDto transactionDocument = await _accountingQueries.GetTransactionDocumentTypeByDocId(request.DocId, request.Company);

                if (transactionDocument == null)
                {
                    throw new NotFoundException("TransactionDocument", request.DocId);
                }

                if (transactionDocument.TransactionDocumentTypeId == (int)DocumentType.CP ||
                    transactionDocument.TransactionDocumentTypeId == (int)DocumentType.CI)
                {
                    // Note: the "CreateAccounting" background process is called also for cash status updates, after a
                    // 'response' received from the TRAX system. In this context, the caller just sends a "creaete accounting doc" message
                    // Below, we are checking the existance of the acc doc for the cash (through the SP update).

                    // Updates the document date and the value date of the given cash
                    accountingId = await _accountingDocumentRepository.UpdateAccountingDocumentForTraxResponse(request.DocId, request.Company);

                    // If the doc accounting doc of the cash exists, then accountingId is >0...
                }

                if (accountingId > 0)
                {
                    // ... and in this case, we just queue the cash for posting. As a reminder, the TRAX-ed cash cannot have the “Authorized for posting” flag
                    // set by the user (the UI prevents it)
                    List <long> listOfDocId = new List <long>();
                    listOfDocId.Add(accountingId);
                    await AuthorizeForPosting(listOfDocId, request.Company, request.PostOpClosedPolicy);

                    _unitOfWork.Commit();
                }
                else
                {
                    List <AccountingDocument> accountingDocuments = new List <AccountingDocument>();
                    int docTypeId = transactionDocument.TransactionDocumentTypeId;
                    AccountingSetupDto accountingSetup = await _accountingQueries.GetAccountingSetup(docTypeId, request.Company);

                    var transactionIdOfReversedDoc = await _accountingQueries.GetTransactionDocumentIdByReversalId(request.DocId, request.Company);

                    if (transactionIdOfReversedDoc != null)
                    {
                        // We are in the situation of a reversal
                        var accountingCreationStatusList = await _accountingDocumentRepository.CreateAccountingDocumentForReversal(
                            request.DocId,                      // TransDocId of the Reversal
                            transactionIdOfReversedDoc.Value,   // TransDocId of the Reversed (original)
                            request.Company,
                            request.PostOpClosedPolicy);
                        await EnqueueBulkPostingProcessorMessage(
                            accountingCreationStatusList,
                            request.Company,
                            request.PostOpClosedPolicy);
                    }
                    else
                    {
                        // The document is a standard non-reversed document for which to generate the accounting document
                        company = await _masterDataService.GetCompanyByIdAsync(request.Company);

                        long transactionDocumentId = request.DocId;
                        var  companyDate           = await _systemDateTimeService.GetCompanyDate(request.Company);

                        switch (docTypeId)
                        {
                        case (int)DocumentType.PI:
                        case (int)DocumentType.SI:
                        case (int)DocumentType.CN:
                        case (int)DocumentType.DN:
                            accountingDocuments.Add(await GetInformationForInvoice(request.PostOpClosedPolicy, transactionDocumentId, docTypeId, accountingSetup, company, request.Company, companyDate));
                            break;

                        case (int)DocumentType.CP:
                        case (int)DocumentType.CI:
                            accountingDocuments.AddRange(await GetInformationForCash(request.PostOpClosedPolicy, transactionDocumentId, docTypeId, accountingSetup, company, companyDate));

                            /*CashForCounterpartyDto cashForCounterpartyDto = null;
                             * cashForCounterpartyDto = await _accountingQueries.GetCashTypeIdForCounterParty(transactionDocumentId);
                             * if (cashForCounterpartyDto != null && cashForCounterpartyDto.CashTypeId == (int)CashSelectionType.PaymentDifferentClient && cashForCounterpartyDto.JLTypeId == (int)JLType.CounterPartyTransfer)
                             * {
                             *  accountingDocuments.Add(await GetInformationForCounterParty(request.PostOpClosedPolicy, cashForCounterpartyDto.TransactionDocumentId, docTypeId, accountingSetup, company, companyDate, cashForCounterpartyDto));
                             * }*/

                            break;

                        case (int)DocumentType.MJL:
                        case (int)DocumentType.MTA:
                            TransactionDocumentDto transactionDocumentDto = null;
                            transactionDocumentDto = await _accountingQueries.GetJLDocumentTypeByTransactionDocumentId(transactionDocumentId, company.CompanyId);

                            if (transactionDocumentDto != null && transactionDocumentDto.JLTypeId == 2)     // JLType = 2 = Reval
                            {
                                var revalInformation = await _accountingQueries.GetRevalInformationForAccountingDocument(
                                    transactionDocumentId, company.CompanyId);

                                var revalAccountingDocument = await GetInformationForRevaluation(
                                    request.PostOpClosedPolicy,
                                    transactionDocumentId,
                                    docTypeId,
                                    accountingSetup,
                                    company,
                                    companyDate,
                                    revalInformation);

                                if (revalAccountingDocument != null &&
                                    revalAccountingDocument.AccountingDocumentLines != null &&
                                    revalAccountingDocument.AccountingDocumentLines.Count() > 0)
                                {
                                    // We create the accounting document for reval only if it contains non-0 records
                                    accountingDocuments.Add(revalAccountingDocument);
                                    // Stores a new document matching in the database, to link the revaluation record to it, so that
                                    // it appears as linked in the "delete match" screen
                                    await _invoicingRepository.CreateDocumentMatchingAsync(new DocumentMatching
                                    {
                                        CompanyId             = company.CompanyId,
                                        MatchFlagId           = revalInformation.MatchFlagId,
                                        TransactionDocumentId = transactionDocumentId,
                                        ValueDate             = revalInformation.PaymentDocumentDate,
                                        DepartmentId          = revalInformation.DepartmentId
                                    });
                                }
                                else
                                {
                                    // We delete the Revaluation Transaction document if no accounting
                                    // document has to be associated to it
                                    await _invoicingRepository.DeleteManualJLOrRevaluationAsync(
                                        transactionDocumentId, request.Company);
                                }
                            }
                            else
                            {
                                (AccountingDocument adTAJL, MonthEndTADocumentDto MonthEnd) = await CreateAccountingForTAandJL(request.PostOpClosedPolicy, transactionDocument, transactionDocumentId, docTypeId, accountingSetup, company, companyDate);

                                if (docTypeId == (int)DocumentType.MTA)
                                {
                                    var accountingDocumentPerAccuralNumberTA = await CreateAccountingDocumentPerAccuralNumberTA(adTAJL, MonthEnd, request.Company, transactionDocumentId);

                                    accountingDocuments.AddRange(accountingDocumentPerAccuralNumberTA);
                                }
                                else
                                {
                                    accountingDocuments.Add(adTAJL);
                                }
                            }

                            break;

                        case (int)DocumentType.FJ:
                            accountingDocuments.Add(await CreateAccountingDocumentForFxDeal(request.PostOpClosedPolicy, transactionDocumentId, docTypeId, accountingSetup, company, request.Company, companyDate));
                            break;
                        }

                        var createdAccountingDocuments = await CreateAccountingDocumentsAndEnqueueForPosting(request.Company, accountingDocuments, request.PostOpClosedPolicy);

                        createdAccountingDocumentIds = createdAccountingDocuments.Select(a => a.AccountingId);
                    }

                    _unitOfWork.Commit();
                }

                if (transactionDocument.TransactionDocumentTypeId == (int)DocumentType.FJ && accountingDocumentCreationStatusList != null)
                {
                    long createdAccountingId = accountingDocumentCreationStatusList.ToList().FirstOrDefault().AccountingId;

                    await UpdateFxDealInformation(company.Id, request.DocId, createdAccountingId, request.Company);
                }

                _logger.LogInformation("Doc with id {Atlas_DocId}.", request.DocId);
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception on Creating Accouting Document for {Atlas_DocId}.", request.DocId, ex);
                _unitOfWork.Rollback();

                throw;
            }

            return(createdAccountingDocumentIds);
        }
Exemple #13
0
        internal static async Task ValidateFxDeal(FxDeal fxDeal, IIdentityService identityService, IMasterDataService masterDataService, IUserService userService, ISystemDateTimeService systemDateTimeService)
        {
            var departments = await masterDataService.GetDepartmentsAsync(fxDeal.CompanyId);

            if (!departments.Any(d => d.DepartmentId == fxDeal.DepartmentId))
            {
                throw new AtlasBusinessException($"The department {fxDeal.DepartmentId} does not belong to the {fxDeal.CompanyId} company.");
            }

            var trader = await userService.GetUserByIdAsync(fxDeal.TraderId);

            if (trader == null)
            {
                throw new NotFoundException("User", fxDeal.TraderId);
            }

            if (!trader.Permissions.Any(p => p.CompanyId == fxDeal.CompanyId && p.IsTrader))
            {
                throw new AtlasBusinessException($"The user {fxDeal.TraderId} is not configured as a trader for company {fxDeal.CompanyId}.");
            }

            var companyDate = await systemDateTimeService.GetCompanyDate(fxDeal.CompanyId);

            // The date entered in the Contract date field by the user is not in the future.
            if (fxDeal.ContractDate.Date > companyDate.Date)
            {
                throw new AtlasBusinessException($"The contract date cannot be in the future. Company date: {companyDate.Date}");
            }

            // The department code must belong to the list of departments attached to the user’s account.
            var user = await userService.GetUserByIdAsync(identityService.GetUserAtlasId());

            var companyPermissions = user.Permissions
                                     .FirstOrDefault(p => p.CompanyId == fxDeal.CompanyId);

            var userDepartments = companyPermissions.Departments
                                  .Select(department => department.DepartmentId).ToList();

            if (!companyPermissions.AllDepartments && !userDepartments.Contains(fxDeal.DepartmentId))
            {
                throw new AtlasBusinessException($"The department {fxDeal.DepartmentId} does not belong to the list of departments attached to the user’s account.");
            }

            // The FX Deal type must belong to the Deal type master data
            var fxTradeTypes = await masterDataService.GetFxTradeTypes(fxDeal.CompanyId);

            if (!fxTradeTypes.Any(n => n.FxTradeTypeId == fxDeal.FxTradeTypeId))
            {
                throw new AtlasBusinessException($"The FX Deal type {fxDeal.FxTradeTypeId} does not belong to the company {fxDeal.CompanyId}.");
            }

            // Settled amount calculation
            // The value is calculated by multiplying or dividing (depending on M/D field) the “Dealt amount” field’s value by the “Spot ROE” field’s value.
            var settledAmount = fxDeal.Amount * (fxDeal.SpotRateType == "D" ? 1 / fxDeal.SpotRate : fxDeal.SpotRate);

            // TODO: tolerance band on Spot ROE

            // Traded ROE field is the sum of the “Spot ROE” and “FW Points”
            var tradedRoe = fxDeal.SpotRate + fxDeal.FwPoints;

            // The Nominal account (Deal) must belong to the Nominal account master data assigned to the company.
            var nominalAccounts = await masterDataService.GetNominalAccountsAsync(fxDeal.CompanyId);

            if (!nominalAccounts.Any(n => n.NominalAccountId == fxDeal.NominalAccountId))
            {
                throw new AtlasBusinessException($"The Nominal account (Deal) {fxDeal.NominalAccountId} does not belong to the company {fxDeal.CompanyId}.");
            }

            // The Nominal account (Settlement) must belong to the Nominal account master data assigned to the company.
            if (!nominalAccounts.Any(n => n.NominalAccountId == fxDeal.SettlementNominalAccountId))
            {
                throw new AtlasBusinessException($"The Nominal account (Settlement) {fxDeal.NominalAccountId} does not belong to the company {fxDeal.CompanyId}.");
            }

            // The Bank/broker” must belong to the the list of counterparties assigned to the company and having the value “Bank” in “Account type” field
            var counterparties = await masterDataService.GetCounterpartiesAsync(fxDeal.CompanyId);

            if (!counterparties.Any(c => c.CounterpartyID == fxDeal.CounterpartyId))
            {
                throw new AtlasBusinessException($"The counterparty {fxDeal.CounterpartyId} does not belong to the company {fxDeal.CounterpartyId}.");
            }
        }
Exemple #14
0
        /// <summary>
        /// Handling of the unmatching of a match (whichever a manual or the result of a cash by picking)
        /// </summary>
        /// <param name="request">request</param>
        /// <param name="cancellationToken">cancellationToken</param>
        public async Task <ManualDocumentMatchingRecord> Handle(UnmatchManualDocumentMatchingCommand request, CancellationToken cancellationToken)
        {
            _unitOfWork.BeginTransaction();
            try
            {
                long?revalutionTransactionDocId = await _manualDocumentMatchingRepository.DeleteMatchFlag(
                    request.MatchFlagId, request.Company);

                string documentReference = string.Empty;

                if (revalutionTransactionDocId != null)
                {
                    var companyDate = await _systemDateTimeService.GetCompanyDate(request.Company);

                    // A revaluation exists => we have to create a reversal for it
                    int refNumberToCreateForReversal = await _transactionDocumentQueries.GetNextTransactionDocumentReferenceValues(
                        request.Company,
                        (int)MasterDocumentType.JL, // The type of document for reversal is JL
                        companyDate.Year);

                    // Calculate the document reference
                    documentReference = string.Concat(
                        MasterDocumentType.JL,
                        companyDate.Year - 2000,
                        string.Format(CultureInfo.InvariantCulture, "{0:D5}", refNumberToCreateForReversal));

                    var reversalTransactionDocumentId = await _transactionDocumentRepository.ReverseDocument(
                        revalutionTransactionDocId.Value,
                        request.Company,
                        companyDate.Year,
                        refNumberToCreateForReversal,
                        documentReference,
                        companyDate);

                    var authorizationResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), Policies.PostOpClosedPolicy);

                    var content = new JObject();
                    content.Add(new JProperty("docId", reversalTransactionDocumentId));
                    content.Add(new JProperty("postOpClosedPolicy", authorizationResult.Succeeded));

                    // Requesting the creation of the corresponding accounting document
                    await _processMessageService.SendMessage(new ProcessMessage​
                    {
                        ProcessTypeId = (int)ProcessType.AtlasAccountingDocumentProcessor,
                        CompanyId     = request.Company,
                        Content       = content.ToString(),
                    });
                }

                _unitOfWork.Commit();
                _logger.LogInformation("Match Flag Deleted");

                return(revalutionTransactionDocId == null ? null : new ManualDocumentMatchingRecord()
                {
                    ReversalRevalJournalCode = documentReference
                });
            }
            catch
            {
                _unitOfWork.Rollback();
                throw;
            }
        }