private PgStageDetailsForm GetStageDetails(bool isAipe, string budgetRegion, string targetBudget, CostType costType, string agencyCurrency)
        {
            var stageDetails = new PgStageDetailsForm
            {
                BudgetRegion = new AbstractTypeValue {
                    Key = budgetRegion
                },
                InitialBudget  = decimal.Parse(targetBudget),
                IsAIPE         = isAipe,
                CostType       = costType.ToString(),
                AgencyCurrency = agencyCurrency
            };

            if (costType == CostType.Production)
            {
                stageDetails.ContentType = new DictionaryValue {
                    Key = _contentType
                };
                stageDetails.ProductionType = new DictionaryValue {
                    Key = _productionType
                };
            }
            else
            {
                stageDetails.UsageBuyoutType = new DictionaryValue {
                    Key = _contentType
                };
            }

            return(stageDetails);
        }
Exemplo n.º 2
0
        private async Task <CostStageModel> BuildCostFirstStageModel(PgStageDetailsForm stageDetailsForm, Guid userId, CostType costType, IStageDetails stageDetails)
        {
            var stages = await GetStages(stageDetailsForm, costType);

            var firstStage = GetFirstStage(stageDetails, stageDetailsForm, stages);

            var stagesToBuildDocs = GetStagesToBuildDocs(stages, firstStage.Key, firstStage.Key);

            return(new CostStageModel
            {
                Key = firstStage.Key,
                Name = firstStage.Name,
                Order = 1,
                Revisions = new[]
                {
                    new CostStageRevisionModel
                    {
                        Name = firstStage.Key,
                        Status = CostStageRevisionStatus.Draft,
                        StageDetails = JsonConvert.SerializeObject(stageDetails.Data),
                        SupportingDocuments = await BuildSupportingDocuments(stageDetails, costType, stagesToBuildDocs, Guid.Empty)
                    }
                }
            });
        }
        public async Task GetMediaTypes_Types_WhenCostTypeIsTrafficking_ShouldReturnValidListOfMediaTypes()
        {
            // Arrange
            var revisionId         = Guid.NewGuid();
            var pgStageDetailsForm = new PgStageDetailsForm();

            var revision = new CostStageRevision
            {
                Id           = revisionId,
                StageDetails = new CustomFormData
                {
                    Data = JsonConvert.SerializeObject(pgStageDetailsForm)
                },
                CostStage = new CostStage
                {
                    Cost = new Cost
                    {
                        CostType = CostType.Trafficking
                    }
                }
            };

            _efContext.CostStageRevision.Add(revision);
            _efContext.SaveChanges();
            _costStageRevisionServiceMock.Setup(s =>
                                                s.GetStageDetails <PgStageDetailsForm>(revision))
            .Returns(pgStageDetailsForm);

            // Act
            var result = await _service.GetMediaTypes(revisionId);

            // Assert
            result.Select(i => i.Key).Should().BeEquivalentTo(Constants.MediaType.NA);
        }
        private string GetDpvCurrencyCode(ExcelCellValueLookup entries, PgStageDetailsForm stageDetails)
        {
            if (stageDetails.ProductionType?.Key == Constants.ProductionType.FullProduction)
            {
                return(GetSectionCurrencyCode(entries, Production));
            }

            return(GetSectionCurrencyCode(entries, PostProduction));
        }
        protected void SetupDataSharedAcrossTests(Agency agency, Country country,
                                                  Cost cost, CostStageRevision latestRevision, Project project, CostUser costOwner, Guid costOwnerId, CostStage costStage,
                                                  Brand brand, Guid costId, Guid costStageRevisionId, Guid projectId, string budgetRegion = Constants.BudgetRegion.AsiaPacific)
        {
            agency.Country  = country;
            cost.CostNumber = CostNumber;
            cost.LatestCostStageRevision = latestRevision;
            cost.Project             = project;
            costOwner.Agency         = agency;
            costOwner.Id             = costOwnerId;
            latestRevision.CostStage = costStage;
            project.Brand            = brand;

            agency.Name           = AgencyName;
            brand.Name            = BrandName;
            cost.Id               = costId;
            costStage.Name        = CostStageName.ToString();
            costOwner.FullName    = CostOwnerFullName;
            costOwner.GdamUserId  = CostOwnerGdamUserId;
            latestRevision.Id     = costStageRevisionId;
            project.Id            = projectId;
            project.Name          = ProjectName;
            project.GdamProjectId = ProjectGdamId;
            project.AdCostNumber  = ProjectNumber;
            country.Name          = AgencyLocation;

            var stageDetails = new PgStageDetailsForm
            {
                ContentType = new core.Builders.DictionaryValue
                {
                    Id  = Guid.NewGuid(),
                    Key = ContentType
                },
                CostType       = cost.CostType.ToString(),
                ProductionType = new core.Builders.DictionaryValue
                {
                    Id  = Guid.NewGuid(),
                    Key = CostProductionType
                },
                Title = CostTitle,
                AgencyTrackingNumber = AgencyTrackingNumber,
                BudgetRegion         = new AbstractTypeValue
                {
                    Key  = budgetRegion,
                    Name = budgetRegion
                }
            };
            var existingUser = EFContext.CostUser.FirstOrDefault(a => a.GdamUserId == CostOwnerGdamUserId);

            if (existingUser == null)
            {
                EFContext.Add(costOwner);
                EFContext.SaveChanges();
            }

            CostStageRevisionServiceMock.Setup(csr => csr.GetStageDetails <PgStageDetailsForm>(costStageRevisionId)).ReturnsAsync(stageDetails);
        }
Exemplo n.º 6
0
        public static string GetContentType(this PgStageDetailsForm stageForm)
        {
            if (stageForm.CostType == CostType.Production.ToString())
            {
                return(stageForm.ContentType.Key);
            }

            return(string.Empty);
        }
Exemplo n.º 7
0
        public Task <Currency> GetCurrencyIfChanged(PgStageDetailsForm oldStageDetails, PgProductionDetailsForm oldProductionDetails, PgStageDetailsForm newStageDetails, PgProductionDetailsForm newProductionDetails)
        {
            if ((newProductionDetails?.DirectPaymentVendor?.CurrencyId != oldProductionDetails?.DirectPaymentVendor?.CurrencyId) ||
                (newStageDetails.AgencyCurrency != oldStageDetails.AgencyCurrency))
            {
                return(GetCurrency(newStageDetails.AgencyCurrency, newProductionDetails));
            }

            return(Task.FromResult <Currency>(null));
        }
Exemplo n.º 8
0
        public void EmptyForm_GetProductionType()
        {
            //Arrange
            var target = new PgStageDetailsForm();

            //Act
            var result = target.GetProductionType();

            //Assert
            result.Should().BeEmpty();
        }
Exemplo n.º 9
0
        public void CostType_Trafficking_GetContentType()
        {
            //Arrange
            var target = new PgStageDetailsForm {
                CostType = CostType.Trafficking.ToString()
            };

            //Act
            var result = target.GetContentType();

            //Assert
            result.Should().BeEmpty();
        }
Exemplo n.º 10
0
        // this is all calculated in Default Currency (USD)
        // to be later converted into Agency Currency
        public CostSectionTotals Build(PgStageDetailsForm stage, IEnumerable <CostLineItemView> costLineItems, string currentStageKey)
        {
            var totals = new CostSectionTotals();

            if (stage == null)
            {
                Logger.Warning($"PY001: {nameof(stage)} is null.");
            }

            if (costLineItems == null)
            {
                Logger.Error($"PY002: {nameof(costLineItems)} is null.");
                return(totals);
            }

            if (string.IsNullOrEmpty(currentStageKey))
            {
                Logger.Error($"PY003: {nameof(currentStageKey)} is null or empty string.");
                return(totals);
            }

            // NB: individual items are found by their name
            var costLineItemsArray = costLineItems as CostLineItemView[] ?? costLineItems.ToArray();

            var productionInsurance     = costLineItemsArray.Where(x => x.Name == Constants.CostSection.ProductionInsurance).Sum(x => x.ValueInDefaultCurrency);
            var postProductionInsurance = costLineItemsArray.Where(x => x.Name == Constants.CostSection.PostProductionInsurance).Sum(x => x.ValueInDefaultCurrency);

            totals.InsuranceCostTotal = productionInsurance + postProductionInsurance;

            totals.TechnicalFeeCostTotal = costLineItemsArray.Where(x => x.Name == Constants.CostSection.TechnicalFee).Sum(x => x.ValueInDefaultCurrency);
            totals.TalentFeeCostTotal    = costLineItemsArray.Where(x => x.Name == Constants.CostSection.TalentFees).Sum(x => x.ValueInDefaultCurrency);

            // NB: composite items are found by template section name
            totals.PostProductionCostTotal = costLineItemsArray.Where(x => x.TemplateSectionName == Constants.CostSection.PostProduction).Sum(x => x.ValueInDefaultCurrency) - postProductionInsurance;
            totals.ProductionCostTotal     = costLineItemsArray.Where(x => x.TemplateSectionName == Constants.CostSection.Production).Sum(x => x.ValueInDefaultCurrency) - productionInsurance;

            // target budget total is relevant only for AIPE stage
            if (currentStageKey == CostStages.Aipe.ToString())
            {
                totals.TargetBudgetTotal    = stage.InitialBudget.GetValueOrDefault();
                totals.TotalCostAmountTotal = totals.TargetBudgetTotal;
                totals.OtherCostTotal       = 0;
            }
            else
            {
                totals.TotalCostAmountTotal = costLineItemsArray.Sum(i => i.ValueInDefaultCurrency);
                totals.OtherCostTotal       = totals.TotalCostAmountTotal - totals.InsuranceCostTotal - totals.TechnicalFeeCostTotal - totals.PostProductionCostTotal - totals.ProductionCostTotal;
            }

            return(totals);
        }
Exemplo n.º 11
0
        private async Task <Dictionary <string, StageModel> > GetStages(PgStageDetailsForm stageDetailsForm, CostType costType)
        {
            var testStageRule = new PgStageRule
            {
                BudgetRegion       = stageDetailsForm.BudgetRegion?.Key,
                ContentType        = stageDetailsForm.ContentType?.Key,
                ProductionType     = stageDetailsForm.ProductionType?.Key,
                CostType           = costType.ToString(),
                TargetBudgetAmount = stageDetailsForm.InitialBudget.GetValueOrDefault()
            };
            var stages = await _pgStageBuilder.GetStages(testStageRule);

            return(stages);
        }
        public async Task DoesUserHaveRoleForCost_When_UserHasBusinessRoleAgainstOnSmoAndSmoDoesNotMatch_Should_ReturnFalse()
        {
            // Arrange
            var          userId          = Guid.NewGuid();
            var          costId          = Guid.NewGuid();
            const string smoStageDetails = "stage details SMO";
            const string smoAccessRule   = "access rule SMO";
            const string businessRole    = Constants.BusinessRole.FinanceManager;
            var          stageDetails    = new PgStageDetailsForm
            {
                SmoName = smoStageDetails
            };

            var cost = new Cost
            {
                Id = costId,
                LatestCostStageRevision = new CostStageRevision
                {
                    Id           = Guid.NewGuid(),
                    StageDetails = new CustomFormData
                    {
                        Data = JsonConvert.SerializeObject(stageDetails)
                    }
                }
            };

            _costStageRevisionServiceMock.Setup(csr => csr.GetStageDetails <PgStageDetailsForm>(It.Is <CostStageRevision>(r => r == cost.LatestCostStageRevision)))
            .Returns(stageDetails);

            _efContext.Cost.Add(cost);
            _efContext.UserBusinessRole.Add(new UserBusinessRole
            {
                CostUser = new CostUser
                {
                    Id = userId
                },
                BusinessRole = new BusinessRole
                {
                    Key = businessRole
                },
                Labels = new[] { smoAccessRule }
            });
            _efContext.SaveChanges();

            // Act
            var result = await _pgCostUserRoleService.DoesUserHaveRoleForCost(userId, costId, businessRole);

            // Assert
            result.Should().BeFalse();
        }
        protected void InitData(
            string budgetRegion   = Constants.BudgetRegion.AsiaPacific,
            string contentType    = Constants.ContentType.Photography,
            string productionType = Constants.ProductionType.FullProduction,
            CostType costType     = CostType.Production
            )
        {
            CreateTemplateIfNotCreated(User).Wait();

            var costTemplateId = costType == CostType.Production
                ? CostTemplate.Id
                : costType == CostType.Buyout
                    ? UsageCostTemplate.Id
                    : TrafficCostTemplate.Id;

            var costModel = new CreateCostModelBuilder()
                            .WithBudgetRegion(budgetRegion)
                            .WithContentType(contentType)
                            .WithProductionType(productionType)
                            .WithTemplateId(costTemplateId)
                            .Build();

            var createCostResponse = CreateCost(User, costModel).Result;

            _cost     = Deserialize <Cost>(createCostResponse.Body);
            _revision = EFContext.CostStageRevision.First(csr => csr.Id == _cost.LatestCostStageRevisionId.Value);
            var costStageRevisionId = _revision.Id;

            _contentType    = contentType;
            _productionType = productionType;
            _stageDetails   = new PgStageDetailsForm
            {
                ContentType = new DictionaryValue {
                    Key = _contentType
                },
                ProductionType = new DictionaryValue {
                    Key = _productionType
                },
                BudgetRegion = new AbstractTypeValue {
                    Key = budgetRegion
                }
            };
            _productionDetails = new PgProductionDetailsForm();

            _costStageRevisionServiceMock.Setup(csr => csr.GetRevisionById(costStageRevisionId)).ReturnsAsync(_revision);
            _costStageRevisionServiceMock.Setup(csr => csr.GetStageDetails <PgStageDetailsForm>(costStageRevisionId)).ReturnsAsync(_stageDetails);
            _costStageRevisionServiceMock.Setup(csr => csr.GetProductionDetails <PgProductionDetailsForm>(costStageRevisionId)).ReturnsAsync(_productionDetails);
        }
Exemplo n.º 14
0
        public void CostType_Buyout_GetContentType()
        {
            //Arrange
            string expectedContentType = string.Empty;
            var    target = new PgStageDetailsForm
            {
                CostType = CostType.Buyout.ToString()
            };

            //Act
            var result = target.GetContentType();

            //Assert
            result.Should().NotBeNull();
            result.Should().Be(expectedContentType);
        }
Exemplo n.º 15
0
        private static StageModel GetFirstStage(IStageDetails stageDetails, PgStageDetailsForm stageDetailsForm, Dictionary <string, StageModel> stages)
        {
            // if AIPE is applicable & selected, the initial stage is AIPE (1), otherwise - Original Estimate (2)
            var firstStageKey = stageDetailsForm.IsAIPE
                ? CostStages.Aipe.ToString()
                : !string.IsNullOrEmpty(stageDetailsForm.ApprovalStage)
                    ? stageDetailsForm.ApprovalStage
                    : CostStages.OriginalEstimate.ToString();

            if (!ValidateStage(stages, CostStages.New.ToString(), firstStageKey))
            {
                throw new ValidationException($"{firstStageKey} can't be first stage for {JsonConvert.SerializeObject(stageDetails.Data)}");
            }

            return(stages[firstStageKey]);
        }
        private static string GetCommodity(CostType costType, PgStageDetailsForm stageDetails)
        {
            switch (costType)
            {
            case CostType.Production:
                if (stageDetails.ContentType == null)
                {
                    break;
                }

                switch (stageDetails.ContentType.Key)
                {
                case Constants.ContentType.Video:
                case Constants.ContentType.Digital:
                    return(CommodityConstants.VideoProduction);

                case Constants.ContentType.Audio:
                    return(CommodityConstants.RadioProduction);

                case Constants.ContentType.Photography:
                    return(CommodityConstants.PrintAndImageProduction);
                }
                break;

            case CostType.Trafficking:
                return(CommodityConstants.MultimediaDistributionAndTraffic);

            case CostType.Buyout:
                if (stageDetails.UsageType == null)
                {
                    break;
                }

                switch (stageDetails.UsageType.Key)
                {
                case Constants.UsageType.Photography:
                case Constants.UsageType.Music:
                case Constants.UsageType.VoiceOver:
                    return(CommodityConstants.Music);

                default:
                    return(CommodityConstants.TalentAndCelebrity);
                }
            }

            return(string.Empty);
        }
        public async Task DoesUserHaveRoleForCost_When_UserHasBusinessRoleOnClientModule_Should_ReturnTrue()
        {
            // Arrange
            var          userId       = Guid.NewGuid();
            var          costId       = Guid.NewGuid();
            const string businessRole = Constants.BusinessRole.FinanceManager;
            var          stageDetails = new PgStageDetailsForm();

            var cost = new Cost
            {
                Id = costId,
                LatestCostStageRevision = new CostStageRevision
                {
                    Id           = Guid.NewGuid(),
                    StageDetails = new CustomFormData
                    {
                        Data = JsonConvert.SerializeObject(stageDetails)
                    }
                }
            };

            _costStageRevisionServiceMock.Setup(csr => csr.GetStageDetails <PgStageDetailsForm>(It.Is <CostStageRevision>(r => r == cost.LatestCostStageRevision)))
            .Returns(stageDetails);

            _efContext.Cost.Add(cost);
            _efContext.UserBusinessRole.Add(new UserBusinessRole
            {
                CostUser = new CostUser
                {
                    Id = userId
                },
                BusinessRole = new BusinessRole
                {
                    Key = businessRole
                },
                ObjectId = Guid.NewGuid()
            });
            _efContext.SaveChanges();

            // Act
            var result = await _pgCostUserRoleService.DoesUserHaveRoleForCost(userId, costId, businessRole);

            // Assert
            result.Should().BeTrue();
        }
Exemplo n.º 18
0
        public static string GetProductionType(this PgStageDetailsForm stageForm)
        {
            if (stageForm.ContentType?.Key == Constants.ContentType.Digital)
            {
                return(Constants.Miscellaneous.NotApplicable);
            }

            if (stageForm.CostType == CostType.Production.ToString())
            {
                return(stageForm.ProductionType.Key);
            }

            if (stageForm.CostType == CostType.Buyout.ToString())
            {
                return(stageForm.UsageBuyoutType.Key);
            }

            return(string.Empty);
        }
Exemplo n.º 19
0
        public void CostType_Buyout_GetProductionType()
        {
            //Arrange
            const string expectedProductionType = "Abc";
            var          target = new PgStageDetailsForm
            {
                CostType        = CostType.Buyout.ToString(),
                UsageBuyoutType = new core.Builders.DictionaryValue
                {
                    Key = expectedProductionType
                }
            };

            //Act
            var result = target.GetProductionType();

            //Assert
            result.Should().NotBeNull();
            result.Should().Be(expectedProductionType);
        }
Exemplo n.º 20
0
        public void ContentType_Digital_GetProductionType()
        {
            //Arrange
            const string expected = "N/A";
            var          target   = new PgStageDetailsForm
            {
                CostType    = CostType.Trafficking.ToString(),
                ContentType = new core.Builders.DictionaryValue
                {
                    Key = Constants.ContentType.Digital
                }
            };

            //Act
            var result = target.GetProductionType();

            //Assert
            result.Should().NotBeNull();
            result.Should().Be(expected);
        }
        public void Null_CostLineItemsStageForm_Returns_Empty()
        {
            //Arrange
            var stageDetailsForm = new PgStageDetailsForm();
            List <CostLineItemView> costLineItems = null;
            var stageKey = CostStages.OriginalEstimate.ToString();
            var expected = 0;

            //Act
            var result = _target.Build(stageDetailsForm, costLineItems, stageKey);

            //Assert
            result.Should().NotBeNull();
            result.InsuranceCostTotal.Should().Be(expected);
            result.OtherCostTotal.Should().Be(expected);
            result.PostProductionCostTotal.Should().Be(expected);
            result.ProductionCostTotal.Should().Be(expected);
            result.TargetBudgetTotal.Should().Be(expected);
            result.TechnicalFeeCostTotal.Should().Be(expected);
            result.TotalCostAmountTotal.Should().Be(expected);
        }
        public void Empty_StageKey_Returns_Empty()
        {
            //Arrange
            var stageDetailsForm = new PgStageDetailsForm();
            var costLineItems    = new List <CostLineItemView>();
            var stageKey         = string.Empty;
            var expected         = 0;

            //Act
            var result = _target.Build(stageDetailsForm, costLineItems, stageKey);

            //Assert
            result.Should().NotBeNull();
            result.InsuranceCostTotal.Should().Be(expected);
            result.OtherCostTotal.Should().Be(expected);
            result.PostProductionCostTotal.Should().Be(expected);
            result.ProductionCostTotal.Should().Be(expected);
            result.TargetBudgetTotal.Should().Be(expected);
            result.TechnicalFeeCostTotal.Should().Be(expected);
            result.TotalCostAmountTotal.Should().Be(expected);
        }
Exemplo n.º 23
0
        public void CostType_Production_GetContentType()
        {
            //Arrange
            const string expectedContentType = "Abc";
            var          target = new PgStageDetailsForm
            {
                CostType    = CostType.Production.ToString(),
                ContentType = new core.Builders.DictionaryValue
                {
                    Key   = expectedContentType,
                    Value = "A Value"
                }
            };

            //Act
            var result = target.GetContentType();

            //Assert
            result.Should().NotBeNull();
            result.Should().Be(expectedContentType);
        }
        protected void PopulateOtherFields(EmailNotificationMessage <CostNotificationObject> message, string parent, DateTime timestamp, Guid costId, Guid costStageRevisionId, CostUser approvalCostUser = null)
        {
            message.Timestamp = timestamp;

            CostNotificationObject obj = message.Object;

            core.Models.Notifications.Cost cost = obj.Cost;

            PgStageDetailsForm stageForm = CostStageRevisionService.GetStageDetails <PgStageDetailsForm>(costStageRevisionId).Result;

            cost.Title = stageForm.Title;
            switch (cost.CostType)
            {
            case core.Models.CostTemplate.CostType.Production:
                cost.ProductionType = stageForm.ProductionType?.Key;
                cost.ContentType    = stageForm.ContentType.Key;
                break;

            case core.Models.CostTemplate.CostType.Buyout:
                cost.ProductionType = stageForm.UsageBuyoutType.Key;
                cost.ContentType    = stageForm.UsageType?.Key;
                break;
            }

            cost.Url = _uriHelper.GetLink(ApplicationUriName.CostRevisionReview, costStageRevisionId.ToString(), costId.ToString());

            AssignApproverType(message, approvalCostUser);

            if (!string.IsNullOrEmpty(parent))
            {
                obj.Parents.Add(parent);
            }
            if (!string.IsNullOrEmpty(AppSettings.EnvironmentEmailSubjectPrefix))
            {
                obj.EnvironmentEmailSubjectPrefix = AppSettings.EnvironmentEmailSubjectPrefix;
            }
        }
        public async Task CreateCost_whenCyclonAgencyAnd_shouldSetIsExternalPurchaseEnabledToFalse(bool isCycloneAgency, string budgetRegion, bool isExternalPurchasesEnabled)
        {
            // Arrange
            var userId               = Guid.NewGuid();
            var agencyId             = Guid.NewGuid();
            var agencyAbstractTypeId = Guid.NewGuid();
            var projectId            = "Gdam Porject Id";
            var agency               = new Agency
            {
                Id     = agencyId,
                Name   = "Name",
                Labels = isCycloneAgency ? new[]
                {
                    Constants.Agency.CycloneLabel, Constants.Agency.PAndGLabel, $"{core.Constants.BusinessUnit.CostModulePrimaryLabelPrefix}P&G"
                } :
                new[]
                {
                    Constants.Agency.PAndGLabel, $"{core.Constants.BusinessUnit.CostModulePrimaryLabelPrefix}P&G"
                },
                AbstractTypes = new List <AbstractType>
                {
                    new AbstractType
                    {
                        Id       = Guid.NewGuid(),
                        ObjectId = agencyId,
                    }
                }
            };

            agency.AbstractTypes.First().Agency = agency;
            var costUser = new CostUser
            {
                Id     = userId,
                Agency = agency
            };
            var abstractTypeAgency = new AbstractType
            {
                Id       = agencyAbstractTypeId,
                Agency   = agency,
                ObjectId = agencyId,
                Parent   = new AbstractType
                {
                    Agency = agency
                }
            };

            EFContext.AbstractType.Add(abstractTypeAgency);
            EFContext.CostUser.Add(costUser);
            EFContext.SaveChanges();

            var costTemplateVersion = new CostTemplateVersion
            {
                Id           = Guid.NewGuid(),
                CostTemplate = new CostTemplate
                {
                    Id       = Guid.NewGuid(),
                    CostType = CostType.Production
                }
            };

            CostTemplateVersionServiceMock.Setup(ctv => ctv.GetLatestTemplateVersion(It.Is <Guid>(id => id == costTemplateVersion.CostTemplate.Id)))
            .ReturnsAsync(costTemplateVersion);

            var stageDetailsForm = new PgStageDetailsForm
            {
                ProjectId    = projectId,
                BudgetRegion = new AbstractTypeValue
                {
                    Key = budgetRegion
                },
                Agency = new PgStageDetailsForm.AbstractTypeAgency
                {
                    Id             = abstractTypeAgency.ObjectId,
                    AbstractTypeId = abstractTypeAgency.Id,
                }
            };

            ProjectServiceMock.Setup(p => p.GetByGadmid(projectId)).ReturnsAsync(new Project
            {
                GdamProjectId = projectId,
                AgencyId      = agencyId
            });
            var stageDetails = new StageDetails
            {
                Data = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(JsonConvert.SerializeObject(stageDetailsForm))
            };

            var createCostModel = new CreateCostModel
            {
                TemplateId   = costTemplateVersion.CostTemplate.Id,
                StageDetails = stageDetails
            };

            PgStageBuilderMock.Setup(sb => sb.GetStages(It.IsAny <PgStageRule>(), null))
            .ReturnsAsync(new Dictionary <string, StageModel>
            {
                {
                    CostStages.New.ToString(),
                    new StageModel
                    {
                        Key         = CostStages.New.ToString(),
                        Transitions = new Dictionary <string, StageModel> {
                            { CostStages.OriginalEstimate.ToString(), new StageModel() }
                        }
                    }
                },
                {
                    CostStages.OriginalEstimate.ToString(),
                    new StageModel {
                        Key = CostStages.OriginalEstimate.ToString()
                    }
                }
            });
            RuleServiceMock.Setup(r => r.GetCompiledByRuleType <SupportingDocumentRule>(RuleType.SupportingDocument)).ReturnsAsync(new List <CompiledRule <SupportingDocumentRule> >());

            // Act
            var result = await CostBuilder.CreateCost(costUser, createCostModel);

            // Assert
            result.Cost.IsExternalPurchasesEnabled.Should().Be(isExternalPurchasesEnabled);
        }
        private static string GetDescription(PgPurchaseOrderDTO purchaseOrderDto, PgStageDetailsForm stageDetailsForm)
        {
            var description = string.Format(DesciptionTemplate, stageDetailsForm.ContentType?.Value, stageDetailsForm.BudgetRegion?.Name, purchaseOrderDto.CostNumber);

            return(Truncate(description, 50));
        }
Exemplo n.º 27
0
        public void Setup()
        {
            User = new UserIdentity
            {
                Id = _xUserId
            };
            var clientModule = new Module
            {
                Id         = Guid.NewGuid(),
                ClientType = ClientType.Pg,
                Name       = "Procter & Gamble",
                ClientTag  = "costPG",
                Key        = "P&G"
            };
            var agencies = new List <Agency>
            {
                new Agency
                {
                    Id     = Guid.NewGuid(),
                    Name   = "SmoName1",
                    Labels = new [] { "CM_Prime_P&G" }
                },
                new Agency
                {
                    Id     = Guid.NewGuid(),
                    Name   = "SmoName2",
                    Labels = new [] { "CM_Prime_P&G" }
                }
            };

            _abstractTypes = new List <AbstractType>
            {
                new AbstractType
                {
                    Id       = Guid.NewGuid(),
                    ObjectId = clientModule.Id,
                    Module   = clientModule,
                    Type     = core.Constants.AccessObjectType.Module
                },
                new AbstractType
                {
                    Id       = Guid.NewGuid(),
                    ObjectId = agencies.First(a => a.Name == "SmoName1").Id,
                    Agency   = agencies.First(a => a.Name == "SmoName1"),
                    Type     = core.Constants.AccessObjectType.Agency
                },
                new AbstractType
                {
                    Id       = Guid.NewGuid(),
                    ObjectId = agencies.First(a => a.Name == "SmoName2").Id,
                    Agency   = agencies.First(a => a.Name == "SmoName2"),
                    Type     = core.Constants.AccessObjectType.Agency
                }
            };
            _costStageReviDetailsFormFirstCost = new PgStageDetailsForm
            {
                BudgetRegion = new AbstractTypeValue
                {
                    Id   = Guid.NewGuid(),
                    Key  = "",
                    Name = "RegionOne"
                },
                SmoName = "SmoName1",
                SmoId   = Guid.NewGuid().ToString()
            };
            _costStageReviDetailsFormSecondCost = new PgStageDetailsForm
            {
                BudgetRegion = new AbstractTypeValue
                {
                    Id   = Guid.NewGuid(),
                    Key  = "",
                    Name = "RegionTwo"
                },
                SmoName = "SmoName2",
                SmoId   = Guid.NewGuid().ToString()
            };
            _costStageReviDetailsFormThirdCost = new PgStageDetailsForm
            {
                BudgetRegion = new AbstractTypeValue
                {
                    Id   = Guid.NewGuid(),
                    Key  = "",
                    Name = "RegionThree"
                },
                SmoName = "SmoName3",
                SmoId   = Guid.NewGuid().ToString()
            };
            _costs = new List <Cost>
            {
                new Cost
                {
                    Id         = Guid.NewGuid(),
                    CostNumber = "number1",
                    ProjectId  = Guid.NewGuid(),
                    LatestCostStageRevision = new CostStageRevision
                    {
                        StageDetails = new CustomFormData
                        {
                            Data = JsonConvert.SerializeObject(_costStageReviDetailsFormFirstCost)
                        }
                    }
                },
                new Cost
                {
                    Id         = Guid.NewGuid(),
                    CostNumber = "number2",
                    ProjectId  = Guid.NewGuid(),
                    LatestCostStageRevision = new CostStageRevision
                    {
                        StageDetails = new CustomFormData
                        {
                            Data = JsonConvert.SerializeObject(_costStageReviDetailsFormSecondCost)
                        }
                    }
                },
                new Cost
                {
                    Id         = Guid.NewGuid(),
                    CostNumber = "number3",
                    ProjectId  = Guid.NewGuid(),
                    LatestCostStageRevision = new CostStageRevision
                    {
                        StageDetails = new CustomFormData
                        {
                            Data = JsonConvert.SerializeObject(_costStageReviDetailsFormThirdCost)
                        }
                    }
                }
            };

            var adminRole = new Role
            {
                Name           = Roles.ClientAdmin,
                Subtype        = "role",
                AbstractTypeId = Guid.NewGuid(),
                Id             = Guid.NewGuid()
            };

            var costCreaterRole = new Role
            {
                Name           = Roles.CostOwner,
                Subtype        = "role",
                AbstractTypeId = Guid.NewGuid(),
                Id             = Guid.NewGuid()
            };

            var costOwnerRole = new Role
            {
                Name           = Roles.CostOwner,
                Subtype        = "role",
                AbstractTypeId = Guid.NewGuid(),
                Id             = Guid.NewGuid()
            };

            var costApproverRole = new Role
            {
                Name           = Roles.CostApprover,
                Subtype        = "role",
                AbstractTypeId = Guid.NewGuid(),
                Id             = Guid.NewGuid()
            };

            var agencyAdminRole = new Role
            {
                Name           = Roles.AgencyAdmin,
                Subtype        = "role",
                AbstractTypeId = Guid.NewGuid(),
                Id             = Guid.NewGuid()
            };

            var userBeingUpdated = new CostUser
            {
                Id                = _userNoRoles,
                Email             = "*****@*****.**",
                UserUserGroups    = new List <UserUserGroup>(),
                UserBusinessRoles = new List <UserBusinessRole>(),
                Agency            = new Agency
                {
                    Id     = Guid.NewGuid(),
                    Labels = new[] { "costPG" },
                    Name   = "AgencyName_11111"
                },
                ApprovalLimit = 0m,
                UserGroups    = new string[0]
            };

            _businessRoles = new List <BusinessRole>
            {
                new BusinessRole
                {
                    Id     = Guid.NewGuid(),
                    Key    = Constants.BusinessRole.GovernanceManager,
                    Value  = Constants.BusinessRole.GovernanceManager,
                    RoleId = adminRole.Id,
                    Role   = adminRole
                },
                new BusinessRole
                {
                    Id     = Guid.NewGuid(),
                    Key    = Constants.BusinessRole.AgencyOwner,
                    Value  = Constants.BusinessRole.AgencyOwner,
                    RoleId = costCreaterRole.Id,
                    Role   = costCreaterRole
                },
                new BusinessRole
                {
                    Id     = Guid.NewGuid(),
                    Key    = Constants.BusinessRole.AgencyFinanceManager,
                    Value  = Constants.BusinessRole.AgencyFinanceManager,
                    RoleId = costCreaterRole.Id,
                    Role   = costCreaterRole
                },
                new BusinessRole
                {
                    Id     = Guid.NewGuid(),
                    Key    = Constants.BusinessRole.FinanceManager,
                    Value  = Constants.BusinessRole.FinanceManager,
                    RoleId = adminRole.Id,
                    Role   = adminRole
                },
                new BusinessRole
                {
                    Id     = Guid.NewGuid(),
                    Key    = Constants.BusinessRole.AdstreamAdmin,
                    Value  = Constants.BusinessRole.AdstreamAdmin,
                    RoleId = costCreaterRole.Id,
                    Role   = costCreaterRole
                },
                new BusinessRole
                {
                    Id     = Guid.NewGuid(),
                    Key    = Constants.BusinessRole.CostConsultant,
                    Value  = Constants.BusinessRole.CostConsultant,
                    RoleId = costApproverRole.Id,
                    Role   = costApproverRole
                },
                new BusinessRole
                {
                    Id     = Guid.NewGuid(),
                    Key    = Constants.BusinessRole.AgencyAdmin,
                    Value  = Constants.BusinessRole.AgencyAdmin,
                    RoleId = agencyAdminRole.Id,
                    Role   = agencyAdminRole
                }
            };

            var userWithOneClientRole = new CostUser
            {
                Id    = _UserWithOneRoleId,
                Email = "*****@*****.**",

                UserUserGroups = new List <UserUserGroup>
                {
                    new UserUserGroup
                    {
                        UserId    = _UserWithOneRoleId,
                        Id        = Guid.NewGuid(),
                        UserGroup = new UserGroup
                        {
                            Id       = Guid.NewGuid(),
                            ObjectId = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id
                        }
                    }
                },

                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole   = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyOwner),
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyOwner).Id,
                        Id             = Guid.NewGuid(),
                        CostUserId     = _UserWithOneRoleId,
                        ObjectType     = core.Constants.AccessObjectType.Client,
                        ObjectId       = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id
                    }
                },
                Agency = new Agency
                {
                    Id     = Guid.NewGuid(),
                    Labels = new[] { "costPG" },
                    Name   = "AgencyName_11111"
                },
                ApprovalLimit = 0m,
                UserGroups    = new string[0]
            };

            var userWithOneRegionRole = new CostUser
            {
                Id    = _UserWithOneRegionRoleId,
                Email = "*****@*****.**",

                UserUserGroups = new List <UserUserGroup>
                {
                    new UserUserGroup
                    {
                        UserId    = _UserWithOneRoleId,
                        Id        = Guid.NewGuid(),
                        UserGroup = new UserGroup
                        {
                            Id       = Guid.NewGuid(),
                            ObjectId = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id,
                            Label    = "RegionOne"
                        }
                    }
                },

                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole   = _businessRoles.First(a => a.Value == Constants.BusinessRole.FinanceManager),
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.FinanceManager).Id,
                        Id             = Guid.NewGuid(),
                        CostUserId     = _UserWithOneRegionRoleId,
                        Labels         = new[] { "RegionOne" },
                        ObjectType     = core.Constants.AccessObjectType.Region,
                    }
                },
                Agency = new Agency
                {
                    Id     = Guid.NewGuid(),
                    Labels = new[] { "costPG" },
                    Name   = "AgencyName_11111"
                },
                ApprovalLimit = 0m,
                UserGroups    = new string[0]
            };

            var userWithTwoRegionRoles = new CostUser
            {
                Id    = _UserWithTwoRegionRolesId,
                Email = "*****@*****.**",

                UserUserGroups = new List <UserUserGroup>
                {
                    new UserUserGroup
                    {
                        UserId    = _UserWithTwoRegionRolesId,
                        Id        = Guid.NewGuid(),
                        UserGroup = new UserGroup
                        {
                            Id       = Guid.NewGuid(),
                            ObjectId = agencies.First(a => a.Name == "SmoName2").Id
                        }
                    }
                },

                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole   = _businessRoles.First(a => a.Value == Constants.BusinessRole.FinanceManager),
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.FinanceManager).Id,
                        Id             = Guid.NewGuid(),
                        CostUserId     = _UserWithTwoRegionRolesId,
                        Labels         = new[] { "RegionOne", "RegionTwo" },
                        ObjectType     = core.Constants.AccessObjectType.Region,
                    }
                },
                Agency = new Agency
                {
                    Id     = Guid.NewGuid(),
                    Labels = new[] { "costPG" },
                    Name   = "AgencyName_11111"
                },
                ApprovalLimit = 0m,
                UserGroups    = new string[0]
            };

            var userWithTwoRoles = new CostUser
            {
                Id    = _UserWithTwoRolesId,
                Email = "*****@*****.**",

                UserUserGroups = new List <UserUserGroup>
                {
                    new UserUserGroup
                    {
                        Id        = Guid.NewGuid(),
                        UserId    = _UserWithTwoRolesId,
                        UserGroup = new UserGroup
                        {
                            ObjectId = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id,
                            Name     = "Name",
                            Id       = Guid.NewGuid()
                        }
                    },
                    new UserUserGroup
                    {
                        Id        = Guid.NewGuid(),
                        UserId    = _UserWithTwoRolesId,
                        UserGroup = new UserGroup
                        {
                            Name     = "Name2",
                            Id       = Guid.NewGuid(),
                            Label    = "RegionOne",
                            ObjectId = _costs.First(a => a.CostNumber == "number1").Id
                        }
                    }
                },

                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole   = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyFinanceManager),
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyFinanceManager).Id,
                        Id             = Guid.NewGuid(),
                        CostUserId     = _UserWithTwoRolesId,
                        Labels         = new[] { "RegionOne" },
                        ObjectType     = core.Constants.AccessObjectType.Region
                    },
                    new UserBusinessRole
                    {
                        BusinessRole   = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyOwner),
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyOwner).Id,
                        Id             = Guid.NewGuid(),
                        CostUserId     = _UserWithTwoRolesId,
                        ObjectType     = core.Constants.AccessObjectType.Client,
                        ObjectId       = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id
                    }
                },
                Agency = new Agency
                {
                    Id     = Guid.NewGuid(),
                    Labels = new[] { "costPG" },
                    Name   = "AgencyName_11111"
                },
                ApprovalLimit = 0m,
                UserGroups    = new string[0]
            };

            var userWithAgencyAdminRole = new CostUser
            {
                Id    = UserWithAgencyAdminRoleId,
                Email = "*****@*****.**",

                UserUserGroups = new List <UserUserGroup>
                {
                    new UserUserGroup
                    {
                        UserId    = UserWithAgencyAdminRoleId,
                        Id        = Guid.NewGuid(),
                        UserGroup = new UserGroup
                        {
                            Id       = Guid.NewGuid(),
                            ObjectId = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id
                        }
                    }
                },

                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        Id             = Guid.NewGuid(),
                        BusinessRole   = _businessRoles.First(a => a.Key == Constants.BusinessRole.AgencyAdmin),
                        BusinessRoleId = _businessRoles.First(a => a.Key == Constants.BusinessRole.AgencyAdmin).Id,
                        CostUserId     = UserWithAgencyAdminRoleId,
                        ObjectType     = core.Constants.AccessObjectType.Client,
                        ObjectId       = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id
                    }
                },
                Agency = new Agency
                {
                    Id     = Guid.NewGuid(),
                    Labels = new[] { "costPG" },
                    Name   = "AgencyName_11111"
                },
                ApprovalLimit = 0m,
                UserGroups    = new string[0]
            };

            var userPerformingUpdate = new CostUser
            {
                Id                = _xUserId,
                Email             = "*****@*****.**",
                UserUserGroups    = new List <UserUserGroup>(),
                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        Id           = Guid.NewGuid(),
                        BusinessRole = _businessRoles.First(a => a.Value == Constants.BusinessRole.GovernanceManager)
                    }
                },
                Agency = new Agency
                {
                    Id     = Guid.NewGuid(),
                    Labels = new[] { "costPG", "CM_Prime_P&G" },
                    Name   = "P&GBU"
                },
                ApprovalLimit = 1111100m,
                UserGroups    = new string[0]
            };

            _roles = new List <Role> {
                costOwnerRole, adminRole
            };
            _users = new List <CostUser>
            {
                userBeingUpdated,
                userPerformingUpdate,
                userWithOneClientRole,
                userWithTwoRoles,
                userWithOneRegionRole,
                userWithTwoRegionRoles,
                userWithAgencyAdminRole
            };

            EfContext = EFContextFactory.CreateInMemoryEFContextTest();

            _appSettingsMock.Setup(a => a.Value).Returns(new AppSettings {
                CostsAdminUserId = Guid.NewGuid().ToString()
            });
            _aclClientMock.Setup(a => a.Access).Returns(new Access(new AccessApi(new RequestHelper("http://localhost:9999/")), new FunctionHelper()));
            _aclClientMock.Setup(a => a.Get).Returns(new Get(new GetApi(new RequestHelper("http://localhost:9999/")), new FunctionHelper()));
            _pgUserService = new PgUserService(
                EfContext,
                _mapperMock.Object,
                _permissionServiceMock.Object,
                _loggerMock.Object,
                _costStageRevisionServiceMock.Object,
                ActivityLogServiceMock.Object,
                _eventServiceMock.Object,
                _pgAgencyServiceMock.Object);
        }
        private void SetupDataSharedAcrossTests()
        {
            const string     agencyLocation      = "United Kingdom";
            const string     agencyName          = "Saatchi";
            const string     brandName           = "P&G";
            const string     costNumber          = "P101";
            const CostStages costStageName       = CostStages.OriginalEstimate;
            const string     costOwnerGdamUserId = "57e5461ed9563f268ef4f19d";
            const string     costOwnerFullName   = "Mr Cost Owner";
            const string     projectName         = "Pampers";
            const string     projectGdamId       = "57e5461ed9563f268ef4f19c";
            const string     projectNumber       = "PandG01";

            var projectId = Guid.NewGuid();

            _cost = new Cost();
            var costOwner = new CostUser
            {
                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole = new BusinessRole
                        {
                            Key   = Constants.BusinessRole.FinanceManager,
                            Value = Constants.BusinessRole.FinanceManager
                        }
                    }
                }
            };
            var approverUser = new CostUser
            {
                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole = new BusinessRole
                        {
                            Key   = Constants.BusinessRole.Ipm,
                            Value = Constants.BusinessRole.Ipm
                        }
                    }
                }
            };
            var insuranceUser = new CostUser
            {
                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole = new BusinessRole
                        {
                            Key   = Constants.BusinessRole.InsuranceUser,
                            Value = Constants.BusinessRole.InsuranceUser
                        }
                    }
                }
            };

            var latestRevision = new CostStageRevision();
            var costStage      = new CostStage();
            var project        = new Project();
            var brand          = new Brand();
            var agency         = new Agency();
            var country        = new Country();

            agency.Country                = country;
            approverUser.Id               = _approverUserId;
            _cost.CreatedBy               = costOwner;
            _cost.CreatedById             = _costOwnerId;
            _cost.Owner                   = costOwner;
            _cost.OwnerId                 = _costOwnerId;
            _cost.CostNumber              = costNumber;
            _cost.LatestCostStageRevision = latestRevision;
            _cost.Project                 = project;
            costOwner.Agency              = agency;
            costOwner.Id                  = _costOwnerId;
            insuranceUser.Id              = _insuranceUserId;
            latestRevision.CostStage      = costStage;
            project.Brand                 = brand;

            agency.Name           = agencyName;
            brand.Name            = brandName;
            _cost.Id              = _costId;
            costStage.Name        = costStageName.ToString();
            costOwner.FullName    = costOwnerFullName;
            costOwner.GdamUserId  = costOwnerGdamUserId;
            costOwner.Id          = _costOwnerId;
            latestRevision.Id     = _costStageRevisionId;
            project.Id            = projectId;
            project.Name          = projectName;
            project.GdamProjectId = projectGdamId;
            project.AdCostNumber  = projectNumber;
            country.Name          = agencyLocation;

            var agencies = new List <Agency> {
                agency
            };
            var brands = new List <Brand> {
                brand
            };
            var costs = new List <Cost> {
                _cost
            };
            var costStages = new List <CostStageRevision> {
                latestRevision
            };
            var costUsers = new List <CostUser> {
                approverUser, costOwner, insuranceUser
            };
            var countries = new List <Country> {
                country
            };
            var projects = new List <Project> {
                project
            };

            _efContextMock.MockAsyncQueryable(agencies.AsQueryable(), c => c.Agency);
            _efContextMock.MockAsyncQueryable(brands.AsQueryable(), c => c.Brand);
            _efContextMock.MockAsyncQueryable(costs.AsQueryable(), c => c.Cost);
            _efContextMock.MockAsyncQueryable(costStages.AsQueryable(), c => c.CostStageRevision);
            _efContextMock.MockAsyncQueryable(costUsers.AsQueryable(), c => c.CostUser);
            _efContextMock.MockAsyncQueryable(countries.AsQueryable(), c => c.Country);
            _efContextMock.MockAsyncQueryable(projects.AsQueryable(), c => c.Project);

            _efContextMock.MockAsyncQueryable(new List <NotificationSubscriber>
            {
                new NotificationSubscriber
                {
                    CostId     = _cost.Id,
                    CostUserId = _costOwnerId,
                    CostUser   = costOwner
                }
            }.AsQueryable(), a => a.NotificationSubscriber);

            _stageDetails = new PgStageDetailsForm
            {
                Title        = "Test Title",
                BudgetRegion = new AbstractTypeValue
                {
                    Name = Constants.BudgetRegion.AsiaPacific
                },
                ContentType = new core.Builders.DictionaryValue
                {
                    Value = Constants.ContentType.Audio
                },
                ProductionType = new core.Builders.DictionaryValue
                {
                    Value = Constants.ProductionType.PostProductionOnly
                }
            };
            _costStageRevisionServiceMock.Setup(c => c.GetStageDetails <PgStageDetailsForm>(_cost.LatestCostStageRevision)).Returns(_stageDetails);
        }
        protected void InitDataForReopenedFA(
            bool isAipe                                             = false,
            string stageKey                                         = "Aipe",
            string budgetRegion                                     = "AAK (Asia)",
            List <CostLineItemView> items                           = null,
            List <CostLineItemView> previousFAItems                 = null,
            string targetBudget                                     = "0",
            List <CostStageRevisionPaymentTotal> payments           = null,
            List <CostStageRevisionPaymentTotal> previousFAPayments = null,
            string contentType                                      = Constants.ContentType.Video,
            string productionType                                   = Constants.ProductionType.FullProduction,
            CostType costType                                       = CostType.Production,
            string agencyCurrency                                   = "USD",
            Guid?dpvCurrency                                        = null,
            Guid?dpvId            = null,
            string vendorCategory = null
            )
        {
            SetupCurrencies();

            var previousCostStageRevisionId = Guid.NewGuid();

            _costStageRevisionId = Guid.NewGuid();
            var _costPreviousStageRevisionId = Guid.NewGuid();

            var costId            = Guid.NewGuid();
            var costStageId       = Guid.NewGuid();
            var paymentCurrencyId = dpvCurrency ?? _efContext.Currency.FirstOrDefault(c => c.Code == agencyCurrency)?.Id;

            _stage = new CostStage {
                Key = stageKey, Id = costStageId
            };
            _contentType       = contentType;
            _productionType    = productionType;
            _stageDetails      = GetStageDetails(isAipe, budgetRegion, targetBudget, costType, agencyCurrency);
            _productionDetails = GetProductionDetails(dpvCurrency, dpvId, vendorCategory);
            _revision          = new CostStageRevision
            {
                Id           = _costStageRevisionId,
                StageDetails = new CustomFormData {
                    Data = JsonConvert.SerializeObject(_stageDetails)
                },
                ProductDetails = new CustomFormData {
                    Data = JsonConvert.SerializeObject(_productionDetails)
                },
                CostStage = _stage,
                Status    = CostStageRevisionStatus.Approved,
                Approvals = new List <Approval>()
            };

            _previousRevision = new CostStageRevision
            {
                Id           = _costPreviousStageRevisionId,
                StageDetails = new CustomFormData {
                    Data = JsonConvert.SerializeObject(_stageDetails)
                },
                ProductDetails = new CustomFormData {
                    Data = JsonConvert.SerializeObject(_productionDetails)
                },
                CostStage = _stage,
                Status    = CostStageRevisionStatus.Approved,
                Approvals = new List <Approval>()
            };

            _cost = new Cost
            {
                Id       = costId,
                CostType = costType,
                LatestCostStageRevisionId = _costStageRevisionId,
                LatestCostStageRevision   = _revision,

                Project = new Project(),
                Parent  = new AbstractType
                {
                    Agency = new Agency()
                },
                PaymentCurrencyId = paymentCurrencyId,
                ExchangeRate      = _efContext.ExchangeRate.FirstOrDefault(er => er.FromCurrency == paymentCurrencyId)?.Rate
            };
            _stage.Cost = _cost;
            _stage.Name = "Final Actual";

            var previousRevision = new CostStageRevision {
                Id = previousCostStageRevisionId
            };

            //add previous stage revision to the stage
            _stage.CostStageRevisions.Add(_previousRevision);

            _costApprovedEvent = new CostStageRevisionStatusChanged(_cost.Id, _previousRevision.Id, CostStageRevisionStatus.Approved, BuType.Pg);
            _costApprovedEvent = new CostStageRevisionStatusChanged(_cost.Id, _revision.Id, CostStageRevisionStatus.Approved, BuType.Pg);

            _paymentDetailsData = new PgPaymentDetails();
            _costLineItems      = new List <CostLineItemView>();
            if (items != null)
            {
                _costLineItems.AddRange(items);
            }
            var _previousCostLineItems = new List <CostLineItemView>();

            if (items != null)
            {
                _previousCostLineItems.AddRange(previousFAItems);
            }

            var paymentsList = new List <CostStageRevisionPaymentTotal>();

            if (payments != null)
            {
                foreach (var payment in payments)
                {
                    payment.CostStageRevision = _revision;
                }
                paymentsList.AddRange(payments);
            }
            var previousPaymentsList = new List <CostStageRevisionPaymentTotal>();

            if (previousFAPayments != null)
            {
                foreach (var payment in previousFAPayments)
                {
                    payment.CostStageRevision = _previousRevision;
                }
                previousPaymentsList.AddRange(previousFAPayments);
            }
            //set upp last stage revision data
            _costStageRevisionServiceMock.Setup(csr => csr.GetRevisionById(_costPreviousStageRevisionId)).ReturnsAsync(_previousRevision);
            _costStageRevisionServiceMock.Setup(csr => csr.GetPreviousRevision(costStageId)).ReturnsAsync(previousRevision);
            _costStageRevisionServiceMock.Setup(csr =>
                                                csr.GetStageDetails <PgStageDetailsForm>(It.Is <CostStageRevision>(r => r.Id == _costPreviousStageRevisionId)))
            .Returns(_stageDetails);
            _costStageRevisionServiceMock.Setup(csr =>
                                                csr.GetProductionDetails <PgProductionDetailsForm>(It.Is <CostStageRevision>(r => r.Id == _costPreviousStageRevisionId)))
            .Returns(_productionDetails);
            _costStageRevisionServiceMock.Setup(csr => csr.GetCostStageRevisionPaymentTotals(_costPreviousStageRevisionId, It.IsAny <bool>())).ReturnsAsync((List <CostStageRevisionPaymentTotal>)null);
            _costStageRevisionServiceMock.Setup(csr => csr.GetCostStageRevisionPaymentTotals(previousCostStageRevisionId, It.IsAny <bool>())).ReturnsAsync(previousPaymentsList);
            _costStageRevisionServiceMock.Setup(csr => csr.GetAllCostPaymentTotals(costId, costStageId)).ReturnsAsync(previousPaymentsList);
            _costStageRevisionServiceMock.Setup(csr => csr.GetAllCostPaymentTotalsFinalActual(costId, costStageId)).ReturnsAsync(previousPaymentsList);
            _customDataServiceMock.Setup(cd => cd.GetCustomData <PgPaymentDetails>(_costPreviousStageRevisionId, CustomObjectDataKeys.PgPaymentDetails))
            .ReturnsAsync(_paymentDetailsData);
            _costStageRevisionServiceMock.Setup(csr => csr.GetCostLineItems(_costPreviousStageRevisionId)).ReturnsAsync(_previousCostLineItems);

            //set up latest stage revision data
            _costStageRevisionServiceMock.Setup(csr => csr.GetRevisionById(_costStageRevisionId)).ReturnsAsync(_revision);
            _costStageRevisionServiceMock.Setup(csr => csr.GetPreviousRevision(costStageId)).ReturnsAsync(previousRevision);
            _costStageRevisionServiceMock.Setup(csr =>
                                                csr.GetStageDetails <PgStageDetailsForm>(It.Is <CostStageRevision>(r => r.Id == _costStageRevisionId)))
            .Returns(_stageDetails);
            _costStageRevisionServiceMock.Setup(csr =>
                                                csr.GetProductionDetails <PgProductionDetailsForm>(It.Is <CostStageRevision>(r => r.Id == _costStageRevisionId)))
            .Returns(_productionDetails);
            _costStageRevisionServiceMock.Setup(csr => csr.GetCostStageRevisionPaymentTotals(_costStageRevisionId, It.IsAny <bool>())).ReturnsAsync((List <CostStageRevisionPaymentTotal>)null);
            _costStageRevisionServiceMock.Setup(csr => csr.GetCostStageRevisionPaymentTotals(previousCostStageRevisionId, It.IsAny <bool>())).ReturnsAsync(paymentsList);
            _costStageRevisionServiceMock.Setup(csr => csr.GetAllCostPaymentTotals(costId, costStageId)).ReturnsAsync(paymentsList);
            _customDataServiceMock.Setup(cd => cd.GetCustomData <PgPaymentDetails>(_costStageRevisionId, CustomObjectDataKeys.PgPaymentDetails))
            .ReturnsAsync(_paymentDetailsData);
            _costStageRevisionServiceMock.Setup(csr => csr.GetCostLineItems(_costStageRevisionId)).ReturnsAsync(_costLineItems);


            _efContext.Cost.Add(_cost);
            _efContext.SaveChanges();
        }
Exemplo n.º 30
0
        private void SetUpCost(bool addCCApprover,
                               bool addCurrentTechFeeLineItem,
                               bool addNonZeroFormerTechFeeLineItem,
                               TechnicalFee applicableFee,
                               string localCurrencyCode,
                               CostType costType,
                               string contentType,
                               string productionType,
                               string budgetRegion,
                               decimal technicalFeeLineItemValue = 0)
        {
            var cost = new Cost
            {
                Id = _costId,
                LatestCostStageRevisionId = _latestRevisionId,
                CostType = costType
            };

            var ccApproverUser = new CostUser
            {
                UserBusinessRoles = new List <UserBusinessRole>
                {
                    new UserBusinessRole
                    {
                        BusinessRole = new BusinessRole
                        {
                            Key   = Constants.BusinessRole.CostConsultant,
                            Value = Constants.BusinessRole.CostConsultant
                        }
                    }
                }
            };

            _costStageLatestRevision = new CostStageRevision
            {
                Id        = _latestRevisionId,
                Approvals = new List <Approval>
                {
                    new Approval
                    {
                        Type = ApprovalType.IPM,
                        ValidBusinessRoles = new[] { Constants.BusinessRole.CostConsultant, "Some other guy" },
                        ApprovalMembers    = addCCApprover ? new List <ApprovalMember>()
                        {
                            new ApprovalMember()
                            {
                                CostUser = ccApproverUser
                            }
                        } : new List <ApprovalMember>()
                    }
                }
            };

            _costStagePreviousRevision = new CostStageRevision
            {
                Id        = Guid.NewGuid(),
                Approvals = new List <Approval>
                {
                    new Approval
                    {
                        Type = ApprovalType.IPM,
                        ValidBusinessRoles = new[] { Constants.BusinessRole.CostConsultant, "Some other guy" },
                        ApprovalMembers    = addCCApprover ? new List <ApprovalMember>()
                        {
                            new ApprovalMember()
                            {
                                CostUser = ccApproverUser
                            }
                        } : new List <ApprovalMember>()
                    }
                }
            };

            var costStageRevisions = new List <CostStageRevision> {
                _costStageLatestRevision
            };

            var feeCurrency = new Currency
            {
                Id = Guid.NewGuid(),
                DefaultCurrency = applicableFee.CurrencyCode == "USD",
                Code            = applicableFee.CurrencyCode
            };
            var feeCurrencyExchangeRate = new ExchangeRate
            {
                Rate = 2m
            };

            var localCurrency = new Currency
            {
                Id = Guid.NewGuid(),
                DefaultCurrency = localCurrencyCode == "USD",
                Code            = localCurrencyCode
            };
            var localCurrencyExchangeRate = new ExchangeRate
            {
                Rate = 10m
            };

            _costLineItems = new List <CostLineItem>();
            if (addCurrentTechFeeLineItem)
            {
                _costLineItems.Add(new CostLineItem
                {
                    Name = Constants.CostSection.TechnicalFee,
                    CostStageRevisionId    = _costStageLatestRevision.Id,
                    LocalCurrencyId        = localCurrency.Id,
                    ValueInDefaultCurrency = technicalFeeLineItemValue,
                    ValueInLocalCurrency   = technicalFeeLineItemValue
                });
            }

            if (addNonZeroFormerTechFeeLineItem)
            {
                _costLineItems.Add(new CostLineItem
                {
                    Name = Constants.CostSection.TechnicalFee,
                    CostStageRevisionId    = _costStagePreviousRevision.Id,
                    LocalCurrencyId        = localCurrency.Id,
                    ValueInLocalCurrency   = 1000m,
                    ValueInDefaultCurrency = 1000m
                });
            }

            var stageDetails = new PgStageDetailsForm
            {
                ContentType = new DictionaryValue {
                    Key = contentType
                },
                ProductionType = new DictionaryValue {
                    Key = productionType
                },
                BudgetRegion = new AbstractTypeValue {
                    Key = budgetRegion
                }
            };


            var techFees = new List <TechnicalFee> {
                applicableFee
            };

            _efContext.MockAsyncQueryable(costStageRevisions.AsQueryable(), x => x.CostStageRevision);
            _costStageRevisionServiceMock.Setup(x => x.GetStageDetails <PgStageDetailsForm>(_latestRevisionId)).ReturnsAsync(stageDetails);
            _costStageRevisionServiceMock.Setup(x => x.GetPreviousRevision(_costStageId)).ReturnsAsync(_costStagePreviousRevision);

            _efContext.MockAsyncQueryable(_costLineItems.AsQueryable(), c => c.CostLineItem);
            _efContext.MockAsyncQueryable(techFees.AsQueryable(), c => c.TechnicalFee);

            _currencyServiceMock.Setup(x => x.GetCurrency(It.IsAny <string>())).ReturnsAsync(feeCurrency);
            _currencyServiceMock.Setup(x => x.GetCurrency(It.IsAny <Guid>())).ReturnsAsync(localCurrency);

            _costExchangeRateServiceMock.Setup(x => x.GetExchangeRateByCurrency(cost.Id, feeCurrency.Id)).ReturnsAsync(feeCurrencyExchangeRate);
            _costExchangeRateServiceMock.Setup(x => x.GetExchangeRateByCurrency(cost.Id, localCurrency.Id)).ReturnsAsync(localCurrencyExchangeRate);
            _efContext.MockAsyncQueryable(new[] { cost }.AsQueryable(), c => c.Cost);

            _efContext.Setup(x => x.SaveChangesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(1);
        }