예제 #1
0
        public bool CreateWorkDefinition(WorkDefinitionEvent workDefinitionEvent)
        {
            var workDefinition = GetDbModel(workDefinitionEvent);

            _loggingService.Info($"Create Work Definition: {JsonConvert.SerializeObject(workDefinition)}", "WorkDefinitionServices.CreateWorkDefinition");

            var messages = new List <KafkaMessage>(workdefintionTopicNames?.Select((topic) =>
                                                                                   new KafkaMessage
            {
                Key     = workDefinition.AssetUID.ToString(),
                Message = new
                {
                    CreateWorkDefinitionEvent = new
                    {
                        AssetUID           = workDefinition.AssetUID.ToString(),
                        WorkDefinitionType = workDefinitionEvent.WorkDefinitionType,
                        SensorNumber       = workDefinition.SwitchNumber,
                        StartIsOn          = workDefinition.SwitchWorkStartState,
                        ActionUTC          = workDefinition.InsertUTC,
                        ReceivedUTC        = workDefinition.InsertUTC,
                    }
                },
                Topic = topic
            }
                                                                                   ));

            var actions = new List <Action>()
            {
                () => _transaction.Upsert(workDefinition),
                () => _transaction.Publish(messages)
            };

            return(_transaction.Execute(actions));
        }
예제 #2
0
        public bool AssociateCustomerAsset(AssociateCustomerAssetEvent associateCustomerAsset)
        {
            try
            {
                var customer = GetCustomer(associateCustomerAsset.CustomerUID);
                if (customer?.CustomerID > 0)
                {
                    Enum.TryParse(associateCustomerAsset.RelationType, true,
                                  out CustomerEnum.RelationType relationType);

                    var messages = CustomerTopics
                                   ?.Select(topic => new KafkaMessage
                    {
                        Key     = associateCustomerAsset.CustomerUID.ToString(),
                        Message = new
                        {
                            AssociateCustomerAssetEvent = new
                            {
                                associateCustomerAsset.CustomerUID,
                                associateCustomerAsset.AssetUID,
                                RelationType = relationType.ToString(),
                                associateCustomerAsset.ActionUTC,
                                associateCustomerAsset.ReceivedUTC
                            }
                        },
                        Topic = topic
                    })
                                   ?.ToList();
                    var assetCustomer = new DbAssetCustomer
                    {
                        Fk_CustomerUID         = associateCustomerAsset.CustomerUID,
                        Fk_AssetUID            = associateCustomerAsset.AssetUID,
                        fk_AssetRelationTypeID = (int)relationType,
                        LastCustomerUTC        = DateTime.UtcNow
                    };

                    var actions = new List <Action>()
                    {
                        () => transaction.Upsert(assetCustomer),
                        () => transaction.Publish(messages)
                    };
                    return(transaction.Execute(actions));
                }

                logger.LogInformation($"Skipping the CustomerAsset Association as the required customeruid" +
                                      $" {associateCustomerAsset.CustomerUID} has not been received yet.");
                return(false);
            }
            catch (Exception ex)
            {
                logger.LogError($"Error while associating asset to customer : {ex.Message}, {ex.StackTrace}");
                throw;
            }
        }
예제 #3
0
        public bool CreateAssetSubscriptions(List <CreateAssetSubscriptionEvent> createSubscriptionList)
        {
            SubscriptionSource subscriptionSource;
            var kafkaMessageList = new List <KafkaMessage>();
            var currentUtc       = DateTime.UtcNow;

            var subscriptionList = new List <DbAssetSubscription>();

            foreach (var createSubscription in createSubscriptionList)
            {
                if (createSubscription.SubscriptionType == null ||
                    !_assetSubscriptionTypeCache.ContainsKey(createSubscription.SubscriptionType))
                {
                    throw new Exception("Invalid Asset Subscription Type for the SubscriptionUID:- " +
                                        createSubscription.SubscriptionUID);
                }

                Enum.TryParse(createSubscription.Source, true, out subscriptionSource);
                var createSubscriptionModel = new DbAssetSubscription
                {
                    AssetSubscriptionUID    = createSubscription.SubscriptionUID.Value,
                    fk_AssetUID             = createSubscription.AssetUID.Value,
                    fk_DeviceUID            = createSubscription.DeviceUID.Value,
                    fk_CustomerUID          = createSubscription.CustomerUID.Value,
                    fk_SubscriptionSourceID = (int)subscriptionSource,
                    StartDate         = createSubscription.StartDate.Value,
                    EndDate           = createSubscription.EndDate.Value,
                    InsertUTC         = currentUtc,
                    UpdateUTC         = currentUtc,
                    fk_ServiceTypeID  = _assetSubscriptionTypeCache[createSubscription.SubscriptionType],
                    LastProcessStatus = 0
                };
                subscriptionList.Add(createSubscriptionModel);

                topics.ToList().ForEach(topic =>
                {
                    var kafkaMessage = new KafkaMessage()
                    {
                        Key     = createSubscription.SubscriptionUID.ToString(),
                        Message = new { CreateAssetSubscriptionEvent = createSubscription },
                        Topic   = topic
                    };
                    kafkaMessageList.Add(kafkaMessage);
                });
            }

            var actions = new List <Action>();

            actions.Add(() => transaction.Upsert <DbAssetSubscription>(subscriptionList));
            actions.Add(() => transaction.Publish(kafkaMessageList));

            return(transaction.Execute(actions));
        }
예제 #4
0
        public bool CreateAsset(CreateAssetEvent asset)
        {
            try
            {
                var owningCustomerUID = asset.OwningCustomerUID.HasValue ?
                                        asset.OwningCustomerUID.Value : new Guid();

                DateTime actionUTC = DateTime.UtcNow;

                //Db Object
                var assetObject = new DbModel.AssetPayload
                {
                    AssetUID                = new Guid(asset.AssetUID.ToString()),
                    OwningCustomerUID       = owningCustomerUID,
                    AssetName               = string.IsNullOrWhiteSpace(asset.AssetName) ? null : asset.AssetName,
                    LegacyAssetID           = asset.LegacyAssetID == -9999999 ? 0 : asset.LegacyAssetID,
                    SerialNumber            = asset.SerialNumber,
                    MakeCode                = asset.MakeCode,
                    Model                   = string.IsNullOrWhiteSpace(asset.Model) ? null : asset.Model,
                    AssetTypeName           = string.IsNullOrWhiteSpace(asset.AssetType) ? null : asset.AssetType,
                    IconKey                 = asset.IconKey == -9999999 ? null : asset.IconKey,
                    EquipmentVIN            = string.IsNullOrWhiteSpace(asset.EquipmentVIN) ? null : asset.EquipmentVIN,
                    ModelYear               = asset.ModelYear == -9999999 ? null : asset.ModelYear,
                    InsertUTC               = actionUTC,
                    UpdateUTC               = actionUTC,
                    StatusInd               = true,
                    ObjectType              = asset.ObjectType,
                    Category                = asset.Category,
                    ProjectStatus           = asset.ProjectStatus,
                    SortField               = asset.SortField,
                    Source                  = asset.Source,
                    UserEnteredRuntimeHours = asset.UserEnteredRuntimeHours,
                    Classification          = asset.Classification,
                    PlanningGroup           = asset.PlanningGroup
                };

                var actions = new List <Action>()
                {
                    () => _transaction.Upsert(assetObject),
                    () => _transaction.Publish(GetGetAssetSourceSnapshotTopublish(assetObject, asset.ReceivedUTC.Value, false))
                };
                return(_transaction.Execute(actions));
            }
            catch (MySqlException ex)
            {
                _logger.LogError("error while creating asset in db: ", ex);
                throw ex;
            }
            finally
            {
            }
        }
예제 #5
0
        public void AssociateCustomerAsset_ValidPayload_ExpectedTransactionStatus(
            bool hasValidCustomer, bool transactionStatus, int upsertCalls, int publishCalls, bool hasException,
            string relType)
        {
            //Arrange
            var customerUid        = Guid.NewGuid();
            var assetUid           = Guid.NewGuid();
            var assetCustomerEvent = new AssociateCustomerAssetEvent
            {
                CustomerUID  = customerUid,
                AssetUID     = assetUid,
                RelationType = relType,
                ActionUTC    = DateTime.UtcNow,
                ReceivedUTC  = DateTime.UtcNow
            };
            DbCustomer customerData = hasValidCustomer ? new DbCustomer()
            {
                CustomerID = 109
            } : null;

            transaction.Get <DbCustomer>(Arg.Any <string>()).Returns(new List <DbCustomer> {
                customerData
            });
            transaction.Execute(Arg.Any <List <Action> >())
            .Returns(a =>
            {
                if (hasException)
                {
                    a.Arg <List <Action> >().ForEach(action => action.Returns(e => throw new Exception()));
                    return(false);
                }
                else
                {
                    a.Arg <List <Action> >().ForEach(action => action.Invoke());
                    return(true);
                }
            });

            //Act
            var resultData = customerAssetService.AssociateCustomerAsset(assetCustomerEvent);

            //Assert
            Assert.Equal(transactionStatus, resultData);
            transaction.Received(upsertCalls).Upsert(
                Arg.Is <DbAssetCustomer>(assetCust => ValidateCustomerAssetObject(assetCustomerEvent, assetCust)));
            transaction.Received(publishCalls).Publish(
                Arg.Is <List <KafkaMessage> >(messages => messages
                                              .TrueForAll(m => ValidateCustomerAssetKafkaObject(false, m, assetCustomerEvent))));
        }
예제 #6
0
        public void AssociateCustomerUser_GivenPayload_ExpectedTransactionStatus(AssociateCustomerUserEvent userEvent,
                                                                                 bool hasValidCustomer, bool transactionStatus, int upsertCalls, int publishCalls, bool hasException)
        {
            //Arrange
            DbCustomer customerData = hasValidCustomer ? new DbCustomer()
            {
                CustomerID = 109
            } : null;

            if (hasException)
            {
                transaction.Get <DbCustomer>(Arg.Any <string>()).Returns(e => throw new Exception());
            }
            else
            {
                transaction.Get <DbCustomer>(Arg.Any <string>()).Returns(new List <DbCustomer> {
                    customerData
                });
            }
            transaction.Execute(Arg.Any <List <Action> >())
            .Returns(a =>
            {
                a.Arg <List <Action> >().ForEach(action => action.Invoke());
                return(true);
            });

            //Act
            if (hasException)
            {
                Assert.Throws <Exception>(() => userCustomerService.AssociateCustomerUser(userEvent));
            }
            else
            {
                var resultData = userCustomerService.AssociateCustomerUser(userEvent);

                Assert.Equal(transactionStatus, resultData);
            }

            //Assert
            transaction.Received(upsertCalls).Upsert(
                Arg.Is <DbUserCustomer>(userCust => ValidateCustomerUserObject(userEvent, userCust, customerData)));
            transaction.Received(publishCalls).Publish(
                Arg.Is <List <KafkaMessage> >(messages => messages
                                              .TrueForAll(m => ValidateCustomerUserKafkaObject(false, m, userEvent))));
        }
예제 #7
0
        public void Create_Asset()
        {
            //Arrange for Create

            var assetObject = new CreateAssetEvent()
            {
                AssetName               = "TestAssetName",
                AssetType               = "loader",
                SerialNumber            = "TestSerialNumber",
                AssetUID                = Guid.NewGuid(),
                MakeCode                = "TestMake",
                Model                   = "model",
                EquipmentVIN            = "equipmentVIN",
                IconKey                 = 1,
                LegacyAssetID           = 1,
                ActionUTC               = DateTime.UtcNow,
                ModelYear               = 2016,
                ReceivedUTC             = DateTime.UtcNow,
                OwningCustomerUID       = Guid.NewGuid(),
                ObjectType              = "test",
                Category                = "test",
                ProjectStatus           = "test",
                SortField               = "test",
                Source                  = "test",
                Classification          = "test",
                PlanningGroup           = "test",
                UserEnteredRuntimeHours = "1234"
            };

            _transaction.Execute(Arg.Any <List <Action> >()).Returns(x =>
            {
                foreach (var action in x.Arg <List <Action> >())
                {
                    action();
                }
                return(true);
            });

            //Act
            Assert.True(_assetServices.CreateAsset(assetObject));
        }
예제 #8
0
        public bool AssociateCustomerUser(AssociateCustomerUserEvent associateCustomerUser)
        {
            try
            {
                var customer = GetCustomer(associateCustomerUser.CustomerUID);
                if (customer?.CustomerID > 0)
                {
                    List <KafkaMessage> messages = CustomerTopics
                                                   ?.Select(topic => new KafkaMessage
                    {
                        Key     = associateCustomerUser.CustomerUID.ToString(),
                        Message = new { AssociateCustomerUserEvent = associateCustomerUser },
                        Topic   = topic
                    })
                                                   ?.ToList();

                    var userCustomer = new DbUserCustomer
                    {
                        fk_CustomerID  = customer.CustomerID,
                        fk_CustomerUID = associateCustomerUser.CustomerUID,
                        fk_UserUID     = associateCustomerUser.UserUID,
                        LastUserUTC    = DateTime.UtcNow
                    };

                    var actions = new List <Action>
                    {
                        () => transaction.Upsert(userCustomer),
                        () => transaction.Publish(messages)
                    };
                    return(transaction.Execute(actions));
                }

                return(false);
            }
            catch (Exception ex)
            {
                logger.LogError($"Error while associating user for customer : {ex.Message}, {ex.StackTrace}");
                throw;
            }
        }
예제 #9
0
        private void PersistAndPublishWeeklySettings(List <AssetSettingsGetDBResponse> assetSettingsGetDBResponses)
        {
            var currentDateTime = DateTime.UtcNow;

            var deleteSettings = assetSettingsGetDBResponses.Where(x => x.OperationType == AssetSettingsOperationType.Delete).ToList();
            var upsertSettings = assetSettingsGetDBResponses.Where(x => x.OperationType == AssetSettingsOperationType.Insert || x.OperationType == AssetSettingsOperationType.Update).ToList();

            List <Action> actions = new List <Action>();

            //delete query
            if (deleteSettings.Count > 0)
            {
                var deleteWeeklySettings = this.BuildAssetWeeklySettings(deleteSettings, currentDateTime);
                actions.Add(() => _transactions.Delete(deleteWeeklySettings));
            }

            //upsert query
            if (upsertSettings.Count > 0)
            {
                var upsertWeeklySettingsList = this.BuildAssetWeeklySettings(upsertSettings, currentDateTime);
                actions.Add(() => _transactions.Upsert <AssetWeeklySettingsDto>(upsertWeeklySettingsList));
            }

            List <AssetWeeklyTargetsDto> targetsDto = new List <AssetWeeklyTargetsDto>();

            foreach (var value in assetSettingsGetDBResponses)
            {
                targetsDto.Add(new AssetWeeklyTargetsDto
                {
                    AssetTargetUID       = Guid.Parse(value.AssetWeeklyConfigUID),
                    AssetUID             = value.AssetUID,
                    EndDate              = value.EndDate,
                    StartDate            = value.StartDate,
                    TargetType           = (AssetTargetType)Enum.Parse(typeof(AssetTargetType), value.ConfigType),
                    SundayTargetValue    = value.Sunday,
                    MondayTargetValue    = value.Monday,
                    TuesdayTargetValue   = value.Tuesday,
                    WednesdayTargetValue = value.Wednesday,
                    ThursdayTargetValue  = value.Thursday,
                    FridayTargetValue    = value.Friday,
                    SaturdayTargetValue  = value.Saturday,
                    Status = value.Status
                });
            }

            actions.Add(() => _assetSettingsPublisher.publishAssetWeeklySettings(targetsDto));

            if (actions.Count > 0)
            {
                _transactions.Execute(actions);
            }
        }
예제 #10
0
 public AssetOwnerServicesTests()
 {
     _configuration = Substitute.For <IConfiguration>();
     _logger        = Substitute.For <ILogger>();
     _transaction   = Substitute.For <ITransactions>();
     _configuration["AssetOwnerTopicName"] = "VSS.Interfaces.Events.MasterData.IAssetOwnerEvent.V1-Alpha,VSS.Interfaces.Events.MasterData.IAssetOwnerEvent.V2-Alpha";
     _assetOwnerServices = new AssetOwnerServices(_transaction, _configuration, _logger);
     string[] topics = _configuration["AssetOwnerTopicName"].Split(',');
     _transaction.Execute(Arg.Any <List <Action> >()).Returns(x =>
     {
         return(true);
     });
 }
예제 #11
0
        private bool PersistAndPublish(IEnumerable <AssetSettingsDto> assetSettings, AssetSettingsRequestBase request)
        {
            bool          result  = true;
            List <Action> actions = new List <Action>();

            if (assetSettings.Any())
            {
                actions.Add(() => _transactions.Upsert(assetSettings));
                actions.Add(() => this._assetSettingsPublisher.PublishAssetSettings(assetSettings));
                actions.Add(() => this._assetSettingsPublisher.PublishUserAssetSettings(request));                 //history record

                result = _transactions.Execute(actions);
            }

            return(result);
        }
예제 #12
0
        public void Create_Update_Delete_AssetOwnerEvent()
        {
            //Arrange for Create

            var assetOwnerEvent = new AssetOwnerEvent()
            {
                Action           = Operation.Create,
                ActionUTC        = DateTime.UtcNow,
                AssetUID         = new Guid(),
                AssetOwnerRecord = new VSS.MasterData.WebAPI.ClientModel.AssetOwner()
                {
                    AccountName         = "Sam",
                    AccountUID          = new Guid("a162eb79-0317-11e9-a988-029d68d36a0c"),
                    CustomerName        = "Cat",
                    CustomerUID         = new Guid("a162eb79-0317-11e9-a988-029d68d36a0d"),
                    DealerAccountCode   = "TD00",
                    DealerName          = "DemoDeler",
                    DealerUID           = new Guid("a162eb79-0317-11e9-a988-029d68d36a0e"),
                    NetworkCustomerCode = "SAP",
                    NetworkDealerCode   = "TeT",
                }
            };

            _transaction.Execute(Arg.Any <List <Action> >()).Returns(x =>
            {
                foreach (var action in x.Arg <List <Action> >())
                {
                    action();
                }
                return(true);
            });

            //Act
            Assert.True(_assetOwnerServices.CreateAssetOwnerEvent(assetOwnerEvent));

            //Arrange for Update
            assetOwnerEvent.Action = Operation.Update;

            //Act
            Assert.True(_assetOwnerServices.UpdateAssetOwnerEvent(assetOwnerEvent));

            //Arrange for Delete
            assetOwnerEvent.Action = Operation.Delete;

            //Act
            Assert.True(_assetOwnerServices.DeleteAssetOwnerEvent(assetOwnerEvent));
        }
예제 #13
0
 public PreferenceServiceTests()
 {
     configuration = Substitute.For <IConfiguration>();
     logger        = Substitute.For <ILogger>();
     transaction   = Substitute.For <ITransactions>();
     configuration["PreferenceKafkaTopicNames"] = "VSS.Interfaces.Events.Preference.IPreferenceEvent";
     configuration["TopicSuffix"] = "-Test";
     preferenceService            = new PreferenceService(configuration, logger, transaction);
     string[] topics = configuration["PreferenceKafkaTopicNames"].Split(',');
     transaction.Execute(Arg.Any <List <Action> >()).Returns(x =>
     {
         foreach (var action in x.Arg <List <Action> >())
         {
             action();
         }
         return(true);
     });
 }
예제 #14
0
        private void SaveDeviceConfigAndDeviceConfigMessage(List <DeviceConfigDto> revisedAssetGroupedDeviceConfigDtos, List <DeviceConfigMsg> deviceDetails)
        {
            List <Action> transactStatements = new List <Action>();

            if (revisedAssetGroupedDeviceConfigDtos.Any())
            {
                //using (var dbConnection = _databaseManager.GetConnection())

                if (deviceDetails != null && deviceDetails.Any())
                {
                    this._loggingService.Info("Started updating Device Config Message table for insertion / updation", "DeviceConfigRepositoryServiceBase.Save");
                    //var deviceConfigMessageQuery = _transactions.GetUpsertBuilder<DeviceConfigMessageDto>();
                    var deviceConfigMessages = (deviceDetails.Select(x => new DeviceConfigMessageDto
                    {
                        DeviceConfigMessageUID = x.MessageUid,
                        DeviceUID = x.DeviceUid,
                        UserUID = x.UserUid,
                        DeviceTypeID = _deviceTypeFamilyContainer[x.DeviceType].DeviceTypeId,                                 //Rephrase
                        EventUTCString = x.EventUtc.ToDateTimeStringWithYearMonthDayFormat(),
                        MessageContent = x.MessageContent,
                        StatusID = 0,
                        LastMessageUTCString = DateTime.UtcNow.ToDateTimeStringWithYearMonthDayFormat()
                    }));
                    transactStatements.Add(() => _transactions.Upsert(deviceConfigMessages));
                    this._loggingService.Info("Ended updating Device Config Message table for insertion / updation", "DeviceConfigRepositoryServiceBase.Save");
                }

                if (revisedAssetGroupedDeviceConfigDtos != null && revisedAssetGroupedDeviceConfigDtos.Any())
                {
                    this._loggingService.Info("Started updating Device Config table for insertion / updation", "DeviceConfigRepositoryServiceBase.Save");
                    //var upsertQuery = _databaseManager.GetUpsertBuilder<DeviceConfigDto>();
                    //upsertQuery.AddRows(revisedAssetGroupedDeviceConfigDtos);
                    transactStatements.Add(() => _transactions.Upsert <DeviceConfigDto>(revisedAssetGroupedDeviceConfigDtos));
                    this._loggingService.Info("Ended updating Device Config table for insertion / updation", "DeviceConfigRepositoryServiceBase.Save");
                }

                if ((deviceDetails != null && deviceDetails.Any()) || (revisedAssetGroupedDeviceConfigDtos != null && revisedAssetGroupedDeviceConfigDtos.Any()))
                {
                    _transactions.Execute(transactStatements);
                    //dbConnection.Commit(); //TODO: need to check if its really needed
                }
            }
        }
예제 #15
0
        public bool CreateAccount(CreateCustomerEvent createAccount)
        {
            try
            {
                FieldHelper.ReplaceEmptyFieldsByNull(createAccount);

                var message = new KafkaMessage
                {
                    Key     = createAccount.CustomerUID.ToString(),
                    Topic   = AccountTopic,
                    Message = new
                    {
                        AccountEvent = new AccountEvent
                        {
                            AccountName         = createAccount.CustomerName,
                            AccountUID          = createAccount.CustomerUID,
                            Action              = Operation.Create.ToString(),
                            BSSID               = createAccount.BSSID,
                            DealerAccountCode   = createAccount.DealerAccountCode,
                            NetworkCustomerCode = createAccount.NetworkCustomerCode,
                            ActionUTC           = createAccount.ActionUTC,
                            ReceivedUTC         = createAccount.ReceivedUTC
                        }
                    }
                };

                var accountObj = new DbAccount
                {
                    CustomerAccountUID = createAccount.CustomerUID,
                    BSSID               = createAccount.BSSID,
                    AccountName         = createAccount.CustomerName,
                    NetworkCustomerCode = createAccount.NetworkCustomerCode,
                    DealerAccountCode   = createAccount.DealerAccountCode,
                    RowUpdatedUTC       = DateTime.UtcNow
                };

                var actions = new List <Action>()
                {
                    () => transaction.Upsert(accountObj),
                    () => transaction.Publish(message)
                };
                return(transaction.Execute(actions));
            }
            catch (Exception ex)
            {
                logger.LogError($"Error while creating account customer : {ex.Message}, {ex.StackTrace}");
                throw;
            }
        }
예제 #16
0
        public void CreateCustomer_ValidPayload_TransactionSuccess(string customerType)
        {
            //Arrange
            var customerEvent = new CreateCustomerEvent
            {
                CustomerName        = $"{customerType}01",
                CustomerUID         = Guid.NewGuid(),
                CustomerType        = customerType,
                BSSID               = "BSS01",
                DealerNetwork       = "None",
                NetworkDealerCode   = "NDC01",
                PrimaryContactEmail = $"{customerType}[email protected]",
                FirstName           = $"{customerType}FN01",
                LastName            = $"{customerType}LN01",
                IsActive            = true,
                ActionUTC           = DateTime.UtcNow,
                ReceivedUTC         = DateTime.UtcNow
            };

            transaction.Execute(Arg.Any <List <Action> >())
            .Returns(a =>
            {
                a.Arg <List <Action> >().ForEach(action => action.Invoke());
                return(true);
            });

            //Act
            var resultData = customerService.CreateCustomer(customerEvent);

            //Assert
            Assert.True(resultData);
            transaction.Received(1).Upsert(
                Arg.Is <DbCustomer>(o =>
                                    ValidateCustomerObject(customerEvent, o, customerType, false, true, null)));
            transaction.Received(1).Publish(Arg.Is <List <KafkaMessage> >(messages =>
                                                                          messages.TrueForAll(m =>
                                                                                              ValidateCustomerKafkaObject(customerEvent, m, customerType, false, null))));
        }
예제 #17
0
        public bool?CreateUserPreference(CreateUserPreferenceEvent userPreference)
        {
            var preference = GetPreferenceKey(userPreference.PreferenceKeyUID, userPreference.PreferenceKeyName);

            if (preference == null || userPreference.PreferenceKeyUID.HasValue &&
                !preference.PreferenceKeyUID.Equals(userPreference.PreferenceKeyUID))
            {
                return(null);
            }

            if (string.IsNullOrEmpty(userPreference.SchemaVersion))
            {
                userPreference.SchemaVersion = "1.0";
            }

            var currentUtc           = DateTime.UtcNow;
            var insertUserPreference = new DbUserPreference()
            {
                fk_UserUID         = userPreference.UserUID,
                fk_PreferenceKeyID = preference.PreferenceKeyID,
                PreferenceValue    = userPreference.PreferenceJson,
                SchemaVersion      = userPreference.SchemaVersion,
                InsertUTC          = currentUtc,
                UpdateUTC          = currentUtc
            };

            var kafkaMessage = new KafkaMessage()
            {
                Key     = userPreference.UserUID.ToString(),
                Message = new { CreateUserPreferenceEvent = userPreference }
            };

            var actions = new List <Action>();

            actions.Add(() => transaction.Upsert <DbUserPreference>(insertUserPreference));
            actions.Add(() => topics.ToList().ForEach(topic =>
            {
                kafkaMessage.Topic = topic;
                transaction.Publish(kafkaMessage);
            }));

            return(transaction.Execute(actions));
        }
예제 #18
0
        public void CreateAccount_ValidPayload_TransactionSuccess()
        {
            //Arrange
            var accountEvent = new CreateCustomerEvent
            {
                CustomerName        = "ACC01",
                CustomerUID         = Guid.NewGuid(),
                BSSID               = "BSS01",
                DealerAccountCode   = "DAC01",
                NetworkCustomerCode = "NCC01",
                ActionUTC           = DateTime.UtcNow,
                ReceivedUTC         = DateTime.UtcNow
            };

            transaction.Execute(Arg.Any <List <Action> >())
            .Returns(a =>
            {
                a.Arg <List <Action> >().ForEach(action => action.Invoke());
                return(true);
            });

            //Act
            var resultData = accountService.CreateAccount(accountEvent);

            //Assert
            Assert.True(resultData);
            transaction.Received(1).Upsert(Arg.Is <DbAccount>(o => ValidateAccountObject(accountEvent, o, false, null)));
            transaction.Received(1).Publish(
                Arg.Is <KafkaMessage>(m => ValidateAccountKafkaObject(accountEvent, m, false, null)));
        }
예제 #19
0
        public bool CreateDevice(CreateDeviceEvent device, DeviceStateEnum deviceState)
        {
            DbDeviceType deviceType = deviceTypesCache.First(x => string.Equals(x.Key, device.DeviceType, StringComparison.InvariantCultureIgnoreCase)).Value;

            var currentUTC    = DateTime.UtcNow;
            var devicePayload = new CreateDevicePayload
            {
                ActionUTC     = currentUTC,
                CellModemIMEI = device.CellModemIMEI,
                CellularFirmwarePartnumber = device.CellularFirmwarePartnumber,
                DataLinkType                = device.DataLinkType,
                DeviceState                 = deviceState.ToString(),
                DeregisteredUTC             = device.DeregisteredUTC,
                DevicePartNumber            = device.DevicePartNumber,
                DeviceSerialNumber          = device.DeviceSerialNumber,
                DeviceType                  = device.DeviceType,
                DeviceUID                   = device.DeviceUID.Value,
                FirmwarePartNumber          = device.FirmwarePartNumber,
                GatewayFirmwarePartNumber   = device.GatewayFirmwarePartNumber,
                MainboardSoftwareVersion    = device.MainboardSoftwareVersion,
                ModuleType                  = device.ModuleType,
                NetworkFirmwarePartnumber   = device.NetworkFirmwarePartnumber,
                RadioFirmwarePartNumber     = device.RadioFirmwarePartNumber,
                ReceivedUTC                 = device.ReceivedUTC,
                SatelliteFirmwarePartnumber = device.SatelliteFirmwarePartnumber
            };

            var devicePersonality = GetDevicePersonalities(devicePayload, null, deviceType);

            devicePayload = SetNullIfPropertyEmpty(devicePayload);
            //DeviceSerialNumber will be persisited as NULL in masterdata and send it as Empty to Kafka
            devicePayload.DeviceSerialNumber = string.IsNullOrEmpty(devicePayload.DeviceSerialNumber) ? string.Empty : devicePayload.DeviceSerialNumber;
            var deviceModel = new DbDevice
            {
                SerialNumber              = devicePayload.DeviceSerialNumber,
                DeregisteredUTC           = devicePayload.DeregisteredUTC,
                ModuleType                = devicePayload.ModuleType,
                fk_DeviceStatusID         = deviceState.GetHashCode(),
                MainboardSoftwareVersion  = devicePayload.MainboardSoftwareVersion,
                FirmwarePartNumber        = devicePayload.RadioFirmwarePartNumber == null ? devicePayload.FirmwarePartNumber : devicePayload.RadioFirmwarePartNumber,
                GatewayFirmwarePartNumber = devicePayload.GatewayFirmwarePartNumber,
                DataLinkType              = devicePayload.DataLinkType,
                InsertUTC                   = currentUTC,
                UpdateUTC                   = currentUTC,
                fk_DeviceTypeID             = deviceType.DeviceTypeID,
                CellModemIMEI               = devicePayload.CellModemIMEI,
                DevicePartNumber            = devicePayload.DevicePartNumber,
                CellularFirmwarePartnumber  = devicePayload.CellularFirmwarePartnumber,
                NetworkFirmwarePartnumber   = devicePayload.NetworkFirmwarePartnumber,
                SatelliteFirmwarePartnumber = devicePayload.SatelliteFirmwarePartnumber,
                DeviceUID                   = devicePayload.DeviceUID
            };

            var kafkaMessageList = new List <KafkaMessage>();

            kafkaTopicNames.ForEach(topic =>
            {
                var kafkaMessage = new KafkaMessage()
                {
                    Key     = device.DeviceUID.ToString(),
                    Message = new { CreateDeviceEvent = mapper.Map <CreateDevicePayload, CreateDeviceEvent>(devicePayload) },
                    Topic   = topic
                };
                kafkaMessageList.Add(kafkaMessage);
            });

            kafkaTopicNamesV2.ForEach(topic =>
            {
                var kafkaMessage = new KafkaMessage()
                {
                    Key     = device.DeviceUID.ToString(),
                    Message = ToDevicePayloadV2(devicePayload, devicePersonality),
                    Topic   = topic
                };
                kafkaMessageList.Add(kafkaMessage);
            });


            var actions = new List <Action>();

            actions.Add(() => transactions.Upsert(deviceModel));
            actions.Add(() => transactions.Upsert <DbDevicePersonality>(devicePersonality));
            actions.Add(() => transactions.Publish(kafkaMessageList));

            return(transactions.Execute(actions));
        }
예제 #20
0
        public virtual bool CreateAssetOwnerEvent(AssetOwnerEvent assetOwnerEvent)
        {
            string networkCustomerCode = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.NetworkCustomerCode) ? null : assetOwnerEvent.AssetOwnerRecord.NetworkCustomerCode;
            string dealerAccountCode   = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.DealerAccountCode) ? null : assetOwnerEvent.AssetOwnerRecord.DealerAccountCode;
            string networkDealerCode   = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.NetworkDealerCode)? null : assetOwnerEvent.AssetOwnerRecord.NetworkDealerCode;
            string accountName         = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.AccountName)? null : assetOwnerEvent.AssetOwnerRecord.AccountName;
            string dealerName          = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.DealerName)? null : assetOwnerEvent.AssetOwnerRecord.DealerName;
            string customerName        = string.IsNullOrWhiteSpace(assetOwnerEvent.AssetOwnerRecord.CustomerName)? null : assetOwnerEvent.AssetOwnerRecord.CustomerName;

            Guid?customerUid = assetOwnerEvent.AssetOwnerRecord.CustomerUID == null || assetOwnerEvent.AssetOwnerRecord.CustomerUID == Guid.Empty ? (Guid?)null : assetOwnerEvent.AssetOwnerRecord.CustomerUID;
            Guid?accountUid  = assetOwnerEvent.AssetOwnerRecord.AccountUID == null || assetOwnerEvent.AssetOwnerRecord.AccountUID == Guid.Empty ? (Guid?)null : assetOwnerEvent.AssetOwnerRecord.AccountUID;
            Guid?dealerUid   = assetOwnerEvent.AssetOwnerRecord.DealerUID == Guid.Empty ? (Guid?)null : assetOwnerEvent.AssetOwnerRecord.DealerUID;

            try
            {
                var assetOwnerPayload = new AssetOwnerEvent
                {
                    AssetUID         = assetOwnerEvent.AssetUID,
                    AssetOwnerRecord = new ClientModel.AssetOwner
                    {
                        NetworkCustomerCode = networkCustomerCode,
                        DealerAccountCode   = dealerAccountCode,
                        NetworkDealerCode   = networkDealerCode,
                        AccountName         = accountName,
                        DealerName          = dealerName,
                        DealerUID           = dealerUid,
                        CustomerName        = customerName,
                        CustomerUID         = customerUid,
                        AccountUID          = accountUid
                    },
                    Action      = Operation.Create,
                    ActionUTC   = DateTime.UtcNow,
                    ReceivedUTC = DateTime.UtcNow
                };

                var assetOwnerDBModel = GetAssetOwnerDBModel(assetOwnerPayload);

                var message = new KafkaMessage
                {
                    Key     = assetOwnerEvent.AssetUID.ToString(),
                    Message = new {
                        AssetUID         = assetOwnerEvent.AssetUID,
                        AssetOwnerRecord = new ClientModel.AssetOwner
                        {
                            NetworkCustomerCode = networkCustomerCode,
                            DealerAccountCode   = dealerAccountCode,
                            NetworkDealerCode   = networkDealerCode,
                            AccountName         = accountName,
                            DealerName          = dealerName,
                            DealerUID           = assetOwnerEvent.AssetOwnerRecord.DealerUID,
                            CustomerName        = customerName,
                            CustomerUID         = customerUid,
                            AccountUID          = accountUid
                        },
                        Action      = "Create",
                        ActionUTC   = assetOwnerDBModel.UpdateUTC,
                        ReceivedUTC = assetOwnerDBModel.UpdateUTC
                    }
                };

                var actions = new List <Action>()
                {
                    () => _transaction.Upsert(assetOwnerDBModel),
                    () => assetOwnerTopicNames?.ForEach((topic) => { message.Topic = topic; _transaction.Publish(message); })
                };
                _logger.LogInformation($"Create Asset Owner: {JsonSerializer.Serialize(assetOwnerPayload)}");

                return(_transaction.Execute(actions));
            }
            catch (MySqlException ex)
            {
                _logger.LogError("error while creating asset in db: ", ex);
                throw ex;
            }
            finally
            {
            }
        }