Exemplo n.º 1
0
        internal static async Task ValidateSplitContract(CreateSplitCommand command, IPhysicalContractQueries physicalContractQueries, IUserService userService)
        {
            // splited quantities should be less than or equal to parent contract quantity
            decimal totalSplitedQuantity = 0;

            foreach (var child in command.ChildSections)
            {
                totalSplitedQuantity = totalSplitedQuantity + child.Quantity;
            }

            if (command.Quantity < totalSplitedQuantity)
            {
                throw new AtlasBusinessException($"The total splited quantity {totalSplitedQuantity} should be less than or equal to parent contrat quantity {command.Quantity}.");
            }

            // trader
            foreach (var child in command.ChildSections)
            {
                if (child.ContractId > 0)
                {
                    var physicalContract = await physicalContractQueries.GetPhysicalContractByIdAsync(command.CompanyId, child.ContractId, null);

                    var trader = await userService.GetUserByIdAsync(physicalContract.TraderId.Value);

                    if (trader == null)
                    {
                        throw new NotFoundException("User", physicalContract.TraderId);
                    }
                }
            }
        }
        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;
            }
        }
        private async Task <List <SectionReference> > CreateIntercoContractOnUpdateContract(UpdatePhysicalContractCommand request,
                                                                                            Section section, List <SectionReference> sectionReferences)
        {
            string counterpartyCode = (request.Type == ContractType.Purchase) ? request.SellerCode : request.BuyerCode;
            var    counterparty     = await _masterDataService.GetAllByCounterpartyIdAsync(request.CompanyId, counterpartyCode);

            if (counterparty != null && counterparty.FirstOrDefault() != null &&
                counterparty.FirstOrDefault().CompanyId != request.CompanyId &&
                counterparty.FirstOrDefault().IsCounterpartyGroupAccount)
            {
                if (section != null && !section.IsInterco &&
                    (section.Type == ContractType.Purchase || section.Type == ContractType.Sale) &&
                    (section.SectionOriginId == 0) && (section.InvoicingStatusId == (long)InvoicingStatus.Uninvoiced))
                {
                    var dataVersionId = await _systemDateTimeService.GetCompanyCurrentDataVersionId(request.IntercoCompanyId);

                    var intercoPhysicalFixedPricedContract = _mapper.Map <Section>(section);
                    intercoPhysicalFixedPricedContract.CompanyId             = request.IntercoCompanyId;
                    intercoPhysicalFixedPricedContract.TraderId              = request.IntercoTraderId;
                    intercoPhysicalFixedPricedContract.DepartmentId          = request.IntercoDepartmentId;
                    intercoPhysicalFixedPricedContract.Type                  = (request.Type == ContractType.Purchase) ? ContractType.Sale : ContractType.Purchase;
                    intercoPhysicalFixedPricedContract.DataVersionId         = dataVersionId;
                    intercoPhysicalFixedPricedContract.ContractDate          = DateTime.UtcNow;
                    intercoPhysicalFixedPricedContract.PaymentTerms          = section.PaymentTermCode;
                    intercoPhysicalFixedPricedContract.ContractTerms         = section.ContractTermCode;
                    intercoPhysicalFixedPricedContract.ContractTermsLocation = section.ContractTermLocationCode;

                    string supplierCode = (section.Type == ContractType.Purchase) ? section.SellerCode : section.BuyerCode;
                    intercoPhysicalFixedPricedContract.Costs = (await _costRepository.LoadSectionCostsAsync(intercoPhysicalFixedPricedContract.SectionId,
                                                                                                            request.CompanyId, request.DataVersionId)).Where(c => c.SupplierCode == supplierCode).ToList();

                    // only one contract has to be always created
                    intercoPhysicalFixedPricedContract.NumberOfContract = 1;
                    intercoPhysicalFixedPricedContract.SectionId        = 0;

                    var intercoReferences = (await _tradeRepository.CreatePhysicalContractAsImageAsync(intercoPhysicalFixedPricedContract)).ToList();

                    foreach (var intercoItem in intercoReferences)
                    {
                        if (intercoItem.SectionId > 0 && intercoPhysicalFixedPricedContract.Costs.Any())
                        {
                            foreach (var intercoCostItem in intercoPhysicalFixedPricedContract.Costs)
                            {
                                intercoCostItem.CostId          = 0;
                                intercoCostItem.CompanyId       = intercoPhysicalFixedPricedContract.CompanyId;
                                intercoCostItem.SectionId       = intercoItem.SectionId;
                                intercoCostItem.DataVersionId   = dataVersionId;
                                intercoCostItem.CostDirectionId = (intercoCostItem.CostDirectionId == 1) ? 2 : 1;
                            }

                            // check the business rule for PriceUnitId.
                            await _costRepository.AddCostsAsync(intercoPhysicalFixedPricedContract.Costs, intercoPhysicalFixedPricedContract.CompanyId, dataVersionId);
                        }
                    }

                    var childSectionsDto = await _sectionQueries.GetTradeChildSectionDataAsync(request.CompanyId, request.SectionId, null, null);

                    // request.ChildSections would not be null if only it is Imaging the trade and we have selected Image Splits/tranche option as well
                    if (childSectionsDto != null && childSectionsDto.Any())
                    {
                        IEnumerable <SectionDeprecated> childSections = MapChildSections(childSectionsDto);

                        CreateSplitCommand splitRequest = new CreateSplitCommand();
                        splitRequest.ChildSections    = childSections;
                        splitRequest.CompanyId        = request.IntercoCompanyId;
                        splitRequest.OriginalQuantity = request.Quantity;
                        splitRequest.Quantity         = request.Quantity;
                        var sectionTrancheContract = _mapper.Map <SectionDeprecated>(splitRequest);
                        sectionTrancheContract.SectionId     = intercoReferences.FirstOrDefault().SectionId;
                        sectionTrancheContract.ContractLabel = intercoReferences.FirstOrDefault().ContractLabel;
                        foreach (var splitTrancheItem in sectionTrancheContract.ChildSections)
                        {
                            splitTrancheItem.SectionId             = 0;
                            splitTrancheItem.ContractId            = intercoReferences.FirstOrDefault().PhysicalContractId;
                            splitTrancheItem.SectionOriginId       = (int)intercoReferences.FirstOrDefault().SectionId;
                            splitTrancheItem.BuyerCode             = intercoPhysicalFixedPricedContract.BuyerCode;
                            splitTrancheItem.SellerCode            = intercoPhysicalFixedPricedContract.SellerCode;
                            splitTrancheItem.Memorandum            = string.Empty;
                            splitTrancheItem.CounterpartyReference = string.Empty;
                            splitTrancheItem.DeliveryPeriodEndDate = intercoPhysicalFixedPricedContract.DeliveryPeriodEndDate.Value;
                            splitTrancheItem.DepartmentId          = intercoPhysicalFixedPricedContract.DepartmentId;
                            splitTrancheItem.Status        = ContractStatus.Unapproved;
                            splitTrancheItem.PricingMethod = intercoPhysicalFixedPricedContract.PricingMethod;
                        }

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

                        // Inserting cost while creating an Image of a trade,if available
                        foreach (var childItem in splitTranchReferences)
                        {
                            int index = 0;
                            childItem.Costs = (await _costRepository.LoadSectionCostsAsync(childSectionsDto.ToList()[index].SectionId,
                                                                                           request.CompanyId, request.DataVersionId)).Where(c => c.SupplierCode == supplierCode).ToList();

                            if (childItem.Costs != null)
                            {
                                foreach (var costItem in childItem.Costs)
                                {
                                    costItem.CostId          = 0;
                                    costItem.CompanyId       = intercoPhysicalFixedPricedContract.CompanyId;
                                    costItem.SectionId       = childItem.SectionId;
                                    costItem.DataVersionId   = dataVersionId;
                                    costItem.CostDirectionId = (costItem.CostDirectionId == 1) ? 2 : 1;
                                }

                                await _costRepository.AddCostsAsync(childItem.Costs, request.IntercoCompanyId, dataVersionId);
                            }
                            index++;
                        }
                    }

                    // Update Reference & Memo Details
                    var sourceDataVersionId = await _systemDateTimeService.GetCompanyCurrentDataVersionId(request.CompanyId);

                    await UpdateReferenceAndInternalMemo(sourceDataVersionId,
                                                         request.PhysicalContractId,
                                                         request.IntercoCompanyId.ToUpper() + "/" + intercoReferences.FirstOrDefault().ContractLabel,
                                                         dataVersionId,
                                                         intercoReferences.FirstOrDefault().PhysicalContractId,
                                                         request.CompanyId.ToUpper() + "/" + section.ContractLabel,
                                                         request.Type);

                    sectionReferences.AddRange(intercoReferences);
                }
            }
            if (section != null && section.IsInterco && request.IsRemoveInterco)
            {
                await _tradeRepository.DeleteReferenceAndInternalMemoAsync(section.PhysicalContractId);
            }

            return(sectionReferences);
        }