private async Task CreateTemplateIfNotCreated(CostUser owner)
 {
     if (CostTemplate == null)
     {
         CostTemplate = await CreateTemplate(owner);
     }
     if (UsageCostTemplate == null)
     {
         UsageCostTemplate = await CreateUsageTemplate(owner);
     }
     if (TrafficCostTemplate == null)
     {
         TrafficCostTemplate = await CreateTrafficTemplate(owner);
     }
 }
        protected async Task <Cost> CreateUsageCostEntity(CostUser owner)
        {
            if (UsageCostTemplate == null)
            {
                UsageCostTemplate = await CreateUsageTemplate(owner);
            }

            var createCostResult = await CreateCost(owner, new CreateCostModel
            {
                TemplateId   = UsageCostTemplate.Id,
                StageDetails = new StageDetails
                {
                    Data = new Dictionary <string, dynamic>
                    {
                        { "budgetRegion", new AbstractTypeValue {
                              Key = "AAK (Asia)"
                          } },
                        { "isNewBuyout", "true" },
                        { "isAIPE", false },
                        { "initialBudgetCurrencySymbol", "$" },
                        { "IsCurrencyChanged", false },
                        { "initialBudget", 12312313 },
                        { "agencyTrackingNumber", "Creating Buyout" },
                        { "targetBudget", "<10000" },
                        { "projectId", "123456789" },
                        { "approvalStage", "OriginalEstimate" },
                        { "organisation", new DictionaryValue {
                              Key = "Other"
                          } },
                        { "usageType", new { key = "Celebrity" } },
                        { "usageBuyoutType", new DictionaryValue {
                              Key = "Buyout"
                          } },
                        { "title", "Creating Buyout" },
                        { "description", "Creating Buyout" },
                        { "agencyProducer", new [] { "Agency Producer 2" } },
                        { "agency", new PgStageDetailsForm.AbstractTypeAgency
                          {
                              Id             = owner.AgencyId,
                              AbstractTypeId = owner.Agency.AbstractTypes.First().Id,
                              Name           = owner.Agency.Name
                          } }
                    }
                }
            });

            return(Deserialize <Cost>(createCostResult, HttpStatusCode.Created));
        }
Exemple #3
0
 private Cost GetCost(CostUser user)
 {
     return(new Cost
     {
         Id = Guid.NewGuid(),
         ParentId = Guid.NewGuid(),
         CostNumber = "number",
         CostType = CostType.Production,
         CostStages = new List <CostStage>(),
         Created = DateTime.Now,
         CreatedById = user.Id,
         OwnerId = user.Id,
         UserGroups = new[] { $"{Guid.NewGuid()}" },
         Deleted = false
     });
 }
        public void Valid_Entry_BuildLogMessage_ReturnsJson()
        {
            //Arrange
            var costUserId = Guid.NewGuid();
            var costId     = Guid.NewGuid();
            var costUser   = new CostUser
            {
                Email = "*****@*****.**",
                Id    = costUserId
            };
            var data = new Dictionary <string, object>();

            data[Constants.ActivityLogData.CostId] = costId;
            var delivery = new ActivityLogDelivery
            {
                RetryCount = 0,
                Status     = ActivityLogDeliveryStatus.New
            };
            var entry = new ActivityLog
            {
                ActivityLogType     = ActivityLogType.CostCreated,
                IpAddress           = "127.0.0.1",
                Data                = JsonConvert.SerializeObject(data),
                Timestamp           = DateTime.UtcNow,
                Created             = DateTime.UtcNow,
                CostUserId          = costUserId,
                CostUser            = costUser,
                ActivityLogDelivery = delivery
            };

            _templates.Add(new ActivityLogMessageTemplate
            {
                ActivityLogType = ActivityLogType.CostCreated,
                Id       = 1,
                Template = "{\"timestamp\":\"{{ timestamp | date: \"yyyy-MM-ddTHH:mm:ss.fffZ\" }}\",\"id\":\"{ { messageId } }\",\"type\":\"costCreated\",\"object\":{\"id\":\"{{ objectId }}\",\"type\":\"activity\", \"message\":\"cost ''{{ costId | escape }}'' has been created\", \"costId\":\"{{ costId || escape }}\"},\"subject\":{\"id\":\"{{ subjectId }}\",\"application\":\"adcosts\"}}"
            });

            //Act
            var result = _target.BuildLogMessage(entry);

            //Assert
            result.Should().NotBeNull();
            result.Message.Should().NotBeNull();
            var resultJson = JsonConvert.DeserializeObject(result.Message);

            resultJson.Should().NotBeNull();;
        }
        // TODO cover this logc by unit tests
        private void AddCoupaApprovalEmail(List <EmailNotificationMessage <CostNotificationObject> > notifications,
                                           Cost cost, CostUser costOwner, Guid costStageRevisionId, DateTime timestamp)
        {
            var previousCostStage = _costStageService.GetPreviousCostStage(cost.LatestCostStageRevision.CostStageId).Result;

            if (previousCostStage == null)
            {
                // No need to send COUPA apprvoal email because this is the first time cost gets submitted for Brand Approval
                return;
            }

            var latestRevisionOfPreviousStage = CostStageRevisionService.GetLatestRevision(previousCostStage.Id).Result;

            if (latestRevisionOfPreviousStage == null)
            {
                throw new Exception($"Couldn't find latest revision for stage {previousCostStage.Id}");
            }

            var previousPaymentAmount = _pgPaymentService.GetPaymentAmount(latestRevisionOfPreviousStage.Id, false).Result;
            var currentPaymentAmount  = _pgPaymentService.GetPaymentAmount(costStageRevisionId, false).Result;

            if (currentPaymentAmount.TotalCostAmount == previousPaymentAmount.TotalCostAmount)
            {
                return;
            }

            // Send COUPA approval email because total amount changed
            var paymentDetails = _customObjectDataService.GetCustomData <PgPaymentDetails>(costStageRevisionId, CustomObjectDataKeys.PgPaymentDetails).Result;

            if (!string.IsNullOrEmpty(paymentDetails?.PoNumber))
            {
                var actionType        = core.Constants.EmailNotificationActionType.Submitted;
                var parent            = core.Constants.EmailNotificationParents.Coupa;
                var coupaNotification = new EmailNotificationMessage <CostNotificationObject>(actionType);

                MapEmailNotificationObject(coupaNotification.Object, cost, costOwner);
                PopulateOtherFields(coupaNotification, parent, timestamp, cost.Id, cost.LatestCostStageRevision.Id);
                AddSharedTo(coupaNotification);
                var notificationCost = coupaNotification.Object.Cost;
                notificationCost.PurchaseOrder = new PurchaseOrder();
                Mapper.Map(currentPaymentAmount, notificationCost.PurchaseOrder);
                Mapper.Map(paymentDetails, notificationCost.PurchaseOrder);
                coupaNotification.Parameters.EmailService.AdditionalEmails.Add(AppSettings.CoupaApprovalEmail);

                notifications.Add(coupaNotification);
            }
        }
Exemple #6
0
        public void ChangeOwner_WhenCostIsNotInDB_ShouldThrowException()
        {
            // Arrange
            var costId  = Guid.NewGuid();
            var ownerId = Guid.NewGuid();
            var owner   = new CostUser {
                Id = ownerId
            };

            _efContext.CostUser.Add(owner);
            _efContext.SaveChanges();
            _pgUserService.Setup(s => s.IsUserAgencyAdmin(_identityUser)).Returns(true);

            // Act
            // Assert
            _costOwnerService.Awaiting(s => s.ChangeOwner(_userIdentity, costId, ownerId)).ShouldThrow <EntityNotFoundException <Cost> >();
        }
        private CostUser[] BuildCostUsers()
        {
            const string costOwnerGdamUserId = "57e5461ed9563f268ef4f19d";
            const string costOwnerFullName   = "Mr Cost Owner";

            var costOwner     = new CostUser();
            var approverUser  = new CostUser();
            var insuranceUser = new CostUser();

            approverUser.Id      = Guid.NewGuid();
            costOwner.FullName   = costOwnerFullName;
            costOwner.GdamUserId = costOwnerGdamUserId;
            costOwner.Id         = Guid.NewGuid();
            insuranceUser.Id     = Guid.NewGuid();

            return(new[] { costOwner, approverUser, insuranceUser });
        }
        public void Init()
        {
            _efContextMock = new Mock <EFContext>();
            _customObjectDataServiceMock = new Mock <ICustomObjectDataService>();
            var adminUser = new CostUser {
                Id = Guid.NewGuid(), Email = ApprovalMemberModel.BrandApprovalUserEmail
            };
            var users = new List <CostUser> {
                adminUser
            };

            _efContextMock.MockAsyncQueryable(users.AsQueryable(), c => c.CostUser);

            SetupDictionaries();

            _sut = new PgLedgerMaterialCodeService(_efContextMock.Object, _customObjectDataServiceMock.Object);
        }
Exemple #9
0
            public async Task ChangeOwner_WhenUserAndCostAreValid_ShouldChageOwnerOfTheCost()
            {
                // Arrange
                var cost = new Cost {
                    Owner = new CostUser(), CostOwners = new List <CostOwner>()
                };
                var ownerId = Guid.NewGuid();
                var owner   = new CostUser {
                    Id = ownerId
                };

                // Act
                var result = await CostService.ChangeOwner(User, cost, owner);

                // Assert
                result.Owner.Should().Be(owner);
                result.OwnerId.Should().Be(ownerId);
            }
        protected async Task <Cost> CreateCostEntity(CostUser owner)
        {
            if (CostTemplate == null)
            {
                CostTemplate = await CreateTemplate(owner);
            }

            var videoContentTypeId = EFContext.DictionaryEntry
                                     .First(de =>
                                            de.Dictionary.Name == plugins.Constants.DictionaryNames.ContentType &&
                                            de.Key == plugins.Constants.ContentType.Video).Id;

            var createCostResult = await CreateCost(owner, new CreateCostModel
            {
                TemplateId   = CostTemplate.Id,
                StageDetails = new StageDetails
                {
                    Data = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(JsonConvert.SerializeObject(new PgStageDetailsForm
                    {
                        BudgetRegion = new AbstractTypeValue
                        {
                            Key  = plugins.Constants.BudgetRegion.AsiaPacific,
                            Name = plugins.Constants.BudgetRegion.AsiaPacific
                        },
                        ContentType = new DictionaryValue {
                            Id = videoContentTypeId, Value = "Video", Key = plugins.Constants.ContentType.Video
                        },
                        ProductionType = new DictionaryValue {
                            Id = Guid.NewGuid(), Value = "Full Production", Key = plugins.Constants.ProductionType.FullProduction
                        },
                        ProjectId     = "123456789",
                        ApprovalStage = "OriginalEstimate",
                        Agency        = new PgStageDetailsForm.AbstractTypeAgency
                        {
                            Id             = owner.AgencyId,
                            AbstractTypeId = owner.Agency.AbstractTypes.First().Id,
                            Name           = owner.Agency.Name
                        }
                    }))
                }
            });

            return(Deserialize <Cost>(createCostResult, HttpStatusCode.Created));
        }
        public void GetRemovedApprovers_HasRemovedApprovers()
        {
            //Arrange
            var x                = new CostStageRevision();
            var y                = new CostStageRevision();
            var xApproval1       = new Approval();
            var xApproval2       = new Approval();
            var xApprovalMember1 = new ApprovalMember();
            var xApprovalMember2 = new ApprovalMember();
            var xCostUser1       = new CostUser();
            var removedCostUser  = new CostUser();

            var target = new CostStageRevisionAnalyser();

            x.Approvals = new List <Approval>();
            y.Approvals = new List <Approval>();
            xApproval1.ApprovalMembers = new List <ApprovalMember>();
            xApproval2.ApprovalMembers = new List <ApprovalMember>();

            xApproval1.ApprovalMembers.Add(xApprovalMember1);
            xApproval2.ApprovalMembers.Add(xApprovalMember2);
            xApprovalMember1.CostUser = xCostUser1;
            xApprovalMember2.CostUser = removedCostUser;

            xCostUser1.Id      = Guid.NewGuid();
            removedCostUser.Id = Guid.NewGuid();

            x.Approvals.Add(xApproval1);
            x.Approvals.Add(xApproval2);
            y.Approvals.Add(xApproval1);

            //Act
            var result = target.GetRemovedApprovers(x, y);

            //Assert
            result.Should().NotBeNull();
            result.Should().HaveCount(1);

            var removedApprover = result.First();

            removedApprover.Should().NotBeNull();
            removedApprover.CostUser.Should().NotBeNull();
            removedApprover.CostUser.Should().Be(removedCostUser);
        }
Exemple #12
0
 private List <Approval> SetUpApprovals(CostUser creator, CostUser ipmUser, CostUser brandUser)
 {
     return(new List <Approval>()
     {
         new Approval {
             Id = Guid.NewGuid(),
             ApprovalMembers = new List <ApprovalMember>()
             {
                 new ApprovalMember()
                 {
                     Id = Guid.NewGuid(),
                     CostUser = ipmUser,
                     ApprovalDetails = new ApprovalDetails()
                     {
                         Id = Guid.NewGuid()
                     },
                     Status = ApprovalStatus.Approved
                 },
                 new ApprovalMember()
                 {
                     Id = Guid.NewGuid(),
                     CostUser = brandUser,
                     ApprovalDetails = new ApprovalDetails()
                     {
                         Id = Guid.NewGuid()
                     },
                     Status = ApprovalStatus.Approved
                 }
             },
             Requisitioners = new List <Requisitioner> {
                 new Requisitioner {
                     Id = Guid.NewGuid(),
                     CostUser = creator,
                     ApprovalDetails = new ApprovalDetails()
                     {
                         Id = Guid.NewGuid()
                     }
                 }
             },
             Status = ApprovalStatus.Approved
         },
     });
 }
Exemple #13
0
        public async Task Create_Notification_For_Coupa_For_Non_NA_Non_Cyclone_Agency_When_Cost_Total_Amount_Decreased()
        {
            //Arrange
            decimal?previousPaymentAmount = 10.00M;
            decimal?latestPaymentAmount   = 5.00M; //Decreased from 10
            var     timestamp             = DateTime.UtcNow;

            var cost           = new Cost();
            var costOwner      = new CostUser();
            var latestRevision = new CostStageRevision();

            var previousRevisionId = Guid.NewGuid();
            var latestRevisionId   = Guid.NewGuid();

            SetupPurchaseOrderCost(cost, latestRevision, costOwner, previousRevisionId, latestRevisionId, PoNumber);

            var costUsers = new CostNotificationUsers
            {
                CostOwner = costOwner
            };

            var previousPaymentResult = new PaymentAmountResult
            {
                TotalCostAmount = previousPaymentAmount
            };
            var latestPaymentResult = new PaymentAmountResult
            {
                TotalCostAmount = latestPaymentAmount
            };

            PgPaymentServiceMock.Setup(ppsm => ppsm.GetPaymentAmount(previousRevisionId, false)).Returns(Task.FromResult(previousPaymentResult));
            PgPaymentServiceMock.Setup(ppsm => ppsm.GetPaymentAmount(latestRevisionId, false)).Returns(Task.FromResult(latestPaymentResult));

            //Act
            IEnumerable <EmailNotificationMessage <CostNotificationObject> > result = await EmailNotificationBuilder.BuildPendingBrandApprovalNotification(costUsers, cost,
                                                                                                                                                           latestRevision, timestamp);

            //Assert
            result.Should().NotBeNull();
            var notifications = result.ToArray();

            notifications.Should().HaveCount(1);
        }
        internal async Task <IEnumerable <EmailNotificationMessage <CostNotificationObject> > > Build(
            Cost cost,
            CostNotificationUsers costUsers,
            CostStageRevision costStageRevision,
            DateTime timestamp,
            CostUser changeApprover,
            CostUser previousOwner)
        {
            var    notifications = new List <EmailNotificationMessage <CostNotificationObject> >();
            string actionType    = core.Constants.EmailNotificationActionType.CostOwnerChanged;
            var    costOwner     = costUsers.CostOwner;

            //add recipients
            var recipients = new List <string> {
                costOwner.GdamUserId
            };

            if (costUsers.Watchers != null)
            {
                recipients.AddRange(costUsers.Watchers);
            }
            if (costUsers.Approvers != null)
            {
                recipients.AddRange(costUsers.Approvers);
            }
            recipients.Add(previousOwner.GdamUserId);

            var costOwnerNotification = new EmailNotificationMessage <CostNotificationObject>(actionType, recipients.Distinct());

            AddSharedTo(costOwnerNotification);
            MapEmailNotificationObject(costOwnerNotification.Object, cost, costOwner);
            costOwnerNotification.Object.Cost.PreviousOwner = previousOwner.FullName;
            var approver = costOwnerNotification.Object.Approver;

            approver.Name = changeApprover.FullName;
            PopulateOtherFields(costOwnerNotification, core.Constants.EmailNotificationParents.CostOwner, timestamp, cost.Id, costStageRevision.Id);
            await PopulateMetadata(costOwnerNotification.Object, cost.Id);

            notifications.Add(costOwnerNotification);

            return(notifications);
        }
        public void Init()
        {
            _efContext                    = EFContextFactory.CreateInMemoryEFContext();
            _customDataServiceMock        = new Mock <ICustomObjectDataService>();
            _mapperMock                   = new Mock <IMapper>();
            _approvalServiceMock          = new Mock <IApprovalService>();
            _emailNotificationServiceMock = new Mock <IEmailNotificationService>();
            _costActionServiceMock        = new Mock <ICostActionService>();
            _eventServiceMock             = new Mock <IEventService>();
            _pgPaymentServiceMock         = new Mock <IPgPaymentService>();
            _activityLogServiceMock       = new Mock <IActivityLogService>();

            _costId          = Guid.NewGuid();
            _brandApproverId = Guid.NewGuid();

            _cost = new Cost
            {
                Id         = _costId,
                CostNumber = CostNumber,
                LatestCostStageRevisionId = Guid.NewGuid()
            };
            var brandApprover = new CostUser
            {
                Id    = _brandApproverId,
                Email = ApprovalMemberModel.BrandApprovalUserEmail
            };

            _efContext.Cost.Add(_cost);
            _efContext.CostUser.Add(brandApprover);
            _efContext.SaveChanges();
            _consumer = new PgPurchaseOrderResponseConsumer(
                _efContext,
                _customDataServiceMock.Object,
                _mapperMock.Object,
                _approvalServiceMock.Object,
                _emailNotificationServiceMock.Object,
                _costActionServiceMock.Object,
                _eventServiceMock.Object,
                _pgPaymentServiceMock.Object,
                _activityLogServiceMock.Object
                );
        }
Exemple #16
0
        public void Log_WithValidTemplate_Returns_Json_Message()
        {
            //Arrange
            var costUserId = Guid.NewGuid();
            var costId     = Guid.NewGuid();
            var costUser   = new CostUser
            {
                Email = "*****@*****.**",
                Id    = costUserId
            };
            var data = new Dictionary <string, object>();

            data[Constants.ActivityLogData.CostId] = costId;
            ActivityLog log = new ActivityLog
            {
                ActivityLogType = ActivityLogType.CostCreated,
                IpAddress       = "127.0.0.1",
                Data            = JsonConvert.SerializeObject(data),
                Timestamp       = DateTime.UtcNow,
                Created         = DateTime.UtcNow,
                CostUserId      = costUserId,
                CostUser        = costUser
            };

            _templates.Clear(); //Clear the templates provided by EFContext
            _templates.Add(new ActivityLogMessageTemplate
            {
                ActivityLogType = ActivityLogType.CostCreated,
                Id       = 1,
                Template = "{\"timestamp\":\"{{ timestamp | date: \"yyyy-MM-ddTHH:mm:ss.fffZ\" }}\",\"id\":\"{{ messageId }}\",\"type\":\"costCreated\",\"object\":{\"id\":\"{{ objectId }}\",\"type\":\"activity\", \"message\":\"cost ''{{ costId | escape }}'' has been created\", \"costId\":\"{{ costId || escape }}\"},\"subject\":{\"id\":\"{{ subjectId }}\",\"application\":\"adcosts\"}}"
            });

            //Act
            var result = _target.Build(log);

            //Assert
            result.Should().NotBeNull();
            result.Message.Should().NotBeNull();
            var resultJson = JsonConvert.DeserializeObject(result.Message);

            resultJson.Should().NotBeNull();
        }
        public async Task Handle_ErrorMessageFromXmg_ShouldRejectCost(ResponseErrorType errorType)
        {
            // Arrange
            var cost = MockCost();

            var payload = new { errorMessages = new[] { new { type = ((int)errorType).ToString(), message = "Error messages" } } };

            var message = new PurchaseOrderErrorResponse
            {
                ActivityType   = "Error",
                ClientName     = BuType.Pg.ToString(),
                EventTimeStamp = DateTime.Now,
                CostNumber     = cost.CostNumber,
                Payload        = JObject.Parse(JsonConvert.SerializeObject(payload))
            };
            var response = new ApprovalServiceActionResult {
                Success = true, ApprovalType = "Brand"
            };

            var costUser = new CostUser {
                GdamUserId = "alsjdnaljsdn"
            };
            var adminUser = new CostUser {
                Email = ApprovalMemberModel.BrandApprovalUserEmail
            };
            var adminUserIdentity = new SystemAdminUserIdentity(adminUser);

            var costUserSetMock = _efContextMock.MockAsyncQueryable(new List <CostUser> {
                costUser, adminUser
            }.AsQueryable(), context => context.CostUser);

            costUserSetMock.Setup(u => u.FindAsync(It.IsAny <Guid>())).ReturnsAsync(costUser);

            _approvalServiceMock.Setup(a => a.Reject(cost.Id, adminUserIdentity, BuType.Pg, "Error messages", SourceSystem.Coupa)).ReturnsAsync(response);

            // Act
            await _handler.Handle(message);

            // Assert
            _approvalServiceMock.Verify(s => s.Reject(cost.Id, adminUserIdentity, BuType.Pg, "Error messages", SourceSystem.Coupa));
        }
Exemple #18
0
        public async Task GetBusinessRoles_When_AgencyUser_Should_ReturnCorrespondingBusinessRoles()
        {
            // Arrange
            var currentUserId = Guid.NewGuid();
            var userId        = Guid.NewGuid();
            var user          = new CostUser
            {
                Id     = userId,
                Agency = new Agency()
            };

            _efContextMock.MockAsyncQueryable(new[] { user }.AsQueryable(), d => d.CostUser);

            // Act
            var businessRoles = await _sut.GetBusinessRoles(currentUserId, userId);

            // Assert
            businessRoles.Should().NotBeNull();
            businessRoles.Should().HaveSameCount(_agencyUserBusinessRoles);
            businessRoles.Select(br => br.Key).ShouldBeEquivalentTo(_agencyUserBusinessRoles);
        }
Exemple #19
0
        public async Task GetBusinessRoles_WhenPlatformAdmin_Should_ReturnAllBusinessRoles()
        {
            // Arrange
            var currentUserId = Guid.NewGuid();
            var userId        = Guid.NewGuid();
            var user          = new CostUser
            {
                Id     = userId,
                Agency = new Agency()
            };

            _efContextMock.MockAsyncQueryable(new[] { user }.AsQueryable(), d => d.CostUser);
            _appSettings.CostsAdminUserId = currentUserId.ToString();

            // Act
            var businessRoles = await _sut.GetBusinessRoles(currentUserId, userId);

            // Assert
            businessRoles.Should().NotBeNull();
            businessRoles.Should().HaveSameCount(_allBusinessRoles);
            businessRoles.Select(br => br.Key).ShouldBeEquivalentTo(_allBusinessRoles);
        }
Exemple #20
0
            public async Task ChangeOwner_WhenUserAndCostAreValid_GrantAccessToNewOwner()
            {
                // Arrange
                var costId = Guid.NewGuid();
                var cost   = new Cost
                {
                    Id         = costId,
                    Owner      = new CostUser(),
                    CostOwners = new List <CostOwner>(),
                };
                var ownerId = Guid.NewGuid();
                var owner   = new CostUser {
                    Id = ownerId
                };

                // Act
                await CostService.ChangeOwner(User, cost, owner);

                // Assert
                CostStageRevisionPermissionServiceMock.Verify(p =>
                                                              p.GrantCostPermission(costId, Roles.CostEditor, new[] { owner }, User.BuType, null, false));
            }
        public void GetRemovedApprovers_InYAndNotInX()
        {
            //Arrange
            var x                = new CostStageRevision();
            var y                = new CostStageRevision();
            var xApproval1       = new Approval();
            var xApproval2       = new Approval();
            var xApprovalMember1 = new ApprovalMember();
            var xApprovalMember2 = new ApprovalMember();
            var xCostUser1       = new CostUser();
            var xCostUser2       = new CostUser();

            var target = new CostStageRevisionAnalyser();

            x.Approvals = new List <Approval>();
            y.Approvals = new List <Approval>();
            xApproval1.ApprovalMembers = new List <ApprovalMember>();
            xApproval2.ApprovalMembers = new List <ApprovalMember>();

            xApproval1.ApprovalMembers.Add(xApprovalMember1);
            xApproval2.ApprovalMembers.Add(xApprovalMember2);
            xApprovalMember1.CostUser = xCostUser1;
            xApprovalMember2.CostUser = xCostUser2;

            xCostUser1.Id = Guid.NewGuid();
            xCostUser2.Id = Guid.NewGuid();

            x.Approvals.Add(xApproval1);

            y.Approvals.Add(xApproval1);
            y.Approvals.Add(xApproval2);

            //Act
            var result = target.GetRemovedApprovers(x, y);

            //Assert
            result.Should().NotBeNull();
            result.Should().BeEmpty();
        }
        public async Task <GrantAccessResponse> GrantUserAccess <T>(
            Guid roleId, Guid objectId, CostUser costUser, BuType buType, Guid?xUserId, string labels = null, bool saveChanges = true)
            where T : Entity, IUserGroup
        {
            var dbUser = await _efContext.CostUser.FindAsync(costUser.Id);

            var existingUserGroup = _efContext.UserGroup.FirstOrDefault(a => a.ObjectId == objectId && a.RoleId == roleId);

            if (existingUserGroup == null)
            {
                existingUserGroup = new UserGroup
                {
                    Id         = Guid.NewGuid(),
                    ObjectId   = objectId,
                    RoleId     = roleId,
                    ObjectType = typeof(T).Name.ToSnakeCase(),
                    Label      = labels
                };
                existingUserGroup.SetName();
            }
            _efContext.UserUserGroup.Add(new UserUserGroup
            {
                UserGroupId = existingUserGroup.Id,
                UserId      = costUser.Id,
                UserGroup   = existingUserGroup
            });

            dbUser.UserGroups = new[] { existingUserGroup.Id.ToString() };

            if (saveChanges)
            {
                await _efContext.SaveChangesAsync();
            }

            return(new GrantAccessResponse {
                UserGroups = new[] { existingUserGroup.Id.ToString() }, New = true, UserGroup = existingUserGroup
            });
        }
        public async Task Get_always_shouldQueryUserByEmailFromDB()
        {
            // Arrange
            const string email  = "*****@*****.**";
            var          dbUser = new CostUser
            {
                Email = email,
                Id    = Guid.NewGuid()
            };

            _efContext.CostUser.Add(dbUser);
            _efContext.SaveChanges();

            _mapper.Setup(m => m.Map <CostUserModel>(It.Is <CostUser>(u => u.Email == dbUser.Email))).Returns(new CostUserModel {
                Email = dbUser.Email
            });

            // Act
            var user = await _userService.Get(email, BuType.Pg);

            // Assert
            user.Email.Should().Be(email);
        }
Exemple #24
0
        public void ChangeOwner_ChangeToTheCurrentOwner_ShouldThorwException()
        {
            // Arrange
            var costId  = Guid.NewGuid();
            var ownerId = Guid.NewGuid();
            var owner   = new CostUser()
            {
                Id = ownerId
            };
            var cost = new Cost
            {
                Id      = costId,
                OwnerId = ownerId,
                Owner   = owner
            };

            _efContext.Cost.Add(cost);
            _efContext.SaveChanges();

            // Act
            // Assert
            _costOwnerService.Awaiting(os => os.ChangeOwner(_userIdentity, costId, ownerId)).ShouldThrow <Exception>();
        }
Exemple #25
0
        public void ChangeOwner_WhenUserCanNotChangeOwner_ShouldThrowException()
        {
            // Arrange
            var costId = Guid.NewGuid();
            var cost   = new Cost
            {
                Id    = costId,
                Owner = new CostUser()
            };
            var ownerId = Guid.NewGuid();
            var owner   = new CostUser {
                Id = ownerId
            };

            _efContext.Cost.Add(cost);
            _efContext.CostUser.Add(owner);
            _efContext.SaveChanges();
            _pgUserService.Setup(s => s.IsUserAgencyAdmin(_identityUser)).Returns(false);

            // Act
            // Assert
            _costOwnerService.Awaiting(s => s.ChangeOwner(_userIdentity, costId, ownerId)).ShouldThrow <Exception>();
        }
        protected Task <BrowserResponse> ExecuteAction(Guid costId, CostAction action, CostUser user)
        {
            var url = $"{CostWorkflowUrl(costId)}/actions";

            return(Browser.Post(url, w =>
            {
                w.User(user);
                w.JsonBody(new ExecuteActionModel
                {
                    Action = action
                });
            }));
        }
        protected async Task ExecuteActionAndValidateResponse(Guid costId, CostAction action, CostUser user)
        {
            var url             = $"{CostWorkflowUrl(costId)}/actions";
            var browserResponse = await Browser.Post(url, w =>
            {
                w.User(user);
                w.JsonBody(new ExecuteActionModel
                {
                    Action = action
                });
            });

            Deserialize <object>(browserResponse, HttpStatusCode.OK);
        }
        protected async Task <CostTemplateDetailsModel> CreateTemplate(CostUser user, CostType costType = CostType.Production)
        {
            var model = new CreateCostTemplateModel
            {
                Name = "Production Cost",
                Type = costType,

                CostDetails = new CostTemplateModel
                {
                    Name   = "cost",
                    Label  = "Cost Details",
                    Fields = new List <FormFieldDefintionModel>
                    {
                        new FormFieldDefintionModel
                        {
                            Label = "Cost Number",
                            Name  = "costNumber",
                            Type  = "string"
                        }
                    }
                },
                Forms = new[]
                {
                    new FormDefinitionModel
                    {
                        Name   = "Test",
                        Label  = "test",
                        Fields = new List <FormFieldDefintionModel>
                        {
                            new FormFieldDefintionModel
                            {
                                Name  = "Test field one",
                                Label = "testFieldOne",
                                Type  = "string"
                            }
                        },
                        Sections = new List <FormSectionDefinitionModel>
                        {
                            new FormSectionDefinitionModel
                            {
                                Name   = "Section",
                                Label  = "section",
                                Fields = new List <FormFieldDefintionModel>
                                {
                                    new FormFieldDefintionModel
                                    {
                                        Name  = "Section one",
                                        Label = "sectionOne",
                                        Type  = "string"
                                    }
                                }
                            }
                        }
                    }
                },
                ProductionDetails =
                    new[]
                {
                    new ProductionDetailsTemplateModel
                    {
                        Type  = "video",
                        Forms = new List <ProductionDetailsFormDefinitionModel>
                        {
                            new ProductionDetailsFormDefinitionModel
                            {
                                Name   = "fullProductionWithShoot",
                                Label  = "Full Production",
                                Fields = new List <FormFieldDefintionModel>
                                {
                                    new FormFieldDefintionModel
                                    {
                                        Label = "Shoot Date",
                                        Name  = "shootDate",
                                        Type  = "string"
                                    }
                                },
                                CostLineItemSections = new List <CostLineItemSectionTemplateModel>
                                {
                                    new CostLineItemSectionTemplateModel
                                    {
                                        Name  = "production",
                                        Label = "Production",
                                        Items = new List <CostLineItemSectionTemplateItemModel>
                                        {
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Art Department (Location /studio)",
                                                Name  = "artDepartmentStudio"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Art Department (set dressing)",
                                                Name  = "artDepartmentSetDressing"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Casting",
                                                Name  = "casting"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Crew Costs",
                                                Name  = "crewCost"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Equipment",
                                                Name  = "equiment"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Photographer",
                                                Name  = "photographer"
                                            }
                                        }
                                    },
                                    new CostLineItemSectionTemplateModel
                                    {
                                        Name  = "postProduction",
                                        Label = "Post Production",
                                        Items = new List <CostLineItemSectionTemplateItemModel>
                                        {
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Retouching",
                                                Name  = "retouching"
                                            }
                                        }
                                    },
                                    new CostLineItemSectionTemplateModel
                                    {
                                        Name  = "agencyCosts",
                                        Label = "Agency Costs",
                                        Items = new List <CostLineItemSectionTemplateItemModel>
                                        {
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Foreign exchange loss/gain",
                                                Name  = "foreignExchangeLossGain"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Insurance",
                                                Name  = "insurance"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Offline costs",
                                                Name  = "offlineCosts"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Online costs",
                                                Name  = "onlineCosts"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Tax/importation tax",
                                                Name  = "taxImportationTax"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
            };

            var result = await Browser.Post("/v1/costtemplate/create", with =>
            {
                with.User(user);
                with.JsonBody(model);
            });

            return(Deserialize <CostTemplateDetailsModel>(result, HttpStatusCode.Created));
        }
        protected async Task <OperationResponse> CreateCostLineItems(Guid costId, Guid costStageId, Guid costStageRevisionId, IEnumerable <CostLineItemModel> lineItems, CostUser owner)
        {
            var url = CostLineItemsUrl(costId, costStageId, costStageRevisionId);
            var updateLineItemsResult = await Browser.Put(url, w =>
            {
                w.User(owner);
                w.JsonBody(new UpdateCostLineItemsModel
                {
                    CostLineItemData = new List <CostLineItemModel>(lineItems)
                });
            });

            var updateLineItemsResponse = Deserialize <OperationResponse>(updateLineItemsResult, HttpStatusCode.OK);

            return(updateLineItemsResponse);
        }
        protected async Task <CostTemplateDetailsModel> CreateTrafficTemplate(CostUser user, CostType costType = CostType.Trafficking)
        {
            var model = new CreateCostTemplateModel
            {
                Name        = "costDetails",
                Type        = costType,
                CostDetails = new CostTemplateModel
                {
                    Name   = "costDetails",
                    Label  = "Cost Details",
                    Fields = new List <FormFieldDefintionModel>
                    {
                        new FormFieldDefintionModel
                        {
                            Label = "Agency Name",
                            Name  = "agencyName",
                            Type  = "string"
                        },
                        new FormFieldDefintionModel
                        {
                            Label = "Agency Location",
                            Name  = "agencyLocation",
                            Type  = "string"
                        },
                        new FormFieldDefintionModel
                        {
                            Label = "Agency producer/art buyer",
                            Name  = "agencyProducerArtBuyer",
                            Type  = "string"
                        },
                        new FormFieldDefintionModel
                        {
                            Label = "Budget Region",
                            Name  = "budgetRegion",
                            Type  = "string"
                        },
                        new FormFieldDefintionModel
                        {
                            Label = "Target Budget",
                            Name  = "targetBudget",
                            Type  = "string"
                        },
                        new FormFieldDefintionModel
                        {
                            Label = "Agency Tracking Number",
                            Name  = "contentType",
                            Type  = "string"
                        },
                        new FormFieldDefintionModel
                        {
                            Label = "Organisation",
                            Name  = "organisation",
                            Type  = "string"
                        },
                        new FormFieldDefintionModel
                        {
                            Label = "Agency Currency",
                            Name  = "agencyCurrency",
                            Type  = "string"
                        }
                    }
                },
                ProductionDetails =
                    new[]
                {
                    new ProductionDetailsTemplateModel
                    {
                        Type  = "Trafficking",
                        Forms = new List <ProductionDetailsFormDefinitionModel>
                        {
                            new ProductionDetailsFormDefinitionModel
                            {
                                Name   = "Trafficking",
                                Label  = "Trafficking",
                                Fields = new List <FormFieldDefintionModel>(),
                                CostLineItemSections = new List <CostLineItemSectionTemplateModel>
                                {
                                    new CostLineItemSectionTemplateModel
                                    {
                                        Name          = "distributionCosts",
                                        Label         = "Distribution",
                                        CurrencyLabel = "Trafficking Distribution Currency",
                                        Items         = new List <CostLineItemSectionTemplateItemModel>
                                        {
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Trafficking/Distribution Costs",
                                                Name  = "distributionCosts"
                                            }
                                        }
                                    },
                                    new CostLineItemSectionTemplateModel
                                    {
                                        Name  = "OtherCosts",
                                        Label = "Other",
                                        Items = new List <CostLineItemSectionTemplateItemModel>
                                        {
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "Tax (if applicable)",
                                                Name  = "taxIfApplicable"
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label    = "Technical Fee (when applicable)",
                                                Name     = "technicalFee",
                                                ReadOnly = true
                                            },
                                            new CostLineItemSectionTemplateItemModel
                                            {
                                                Label = "FX (Loss) and Gain",
                                                Name  = "foreignExchange"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
            };

            var result = await Browser.Post("/v1/costtemplate/create", with =>
            {
                with.User(user);
                with.JsonBody(model);
            });

            return(Deserialize <CostTemplateDetailsModel>(result, HttpStatusCode.Created));
        }