Esempio n. 1
0
        public IResult Handle(InactivateAddressCommand command)
        {
            int clientId = SessionRepository.GetClientIdOfSession(command.sessionToken);

            if (clientId == -1)
            {
                throw new Exception();
            }

            var address = DatabaseQueryProcessor.GetAddress(command.addressKey);

            if (address != null && address.clientId == clientId)
            {
                DatabaseQueryProcessor.UpdateAddress(address.addressId, false);
                return(new GetAddressBookQueryHandler().Handle(new GetAddressBookQuery()
                {
                    sessionToken = command.sessionToken
                }));
            }

            return(new SuccessInfoDto()
            {
                isSuccess = false
            });
        }
Esempio n. 2
0
        public void UpdatePersonalData_WrongData_Exception(string _email, string _firstName, string _lastName, bool _changePassword, string _newPassword, bool _receiveNewsletterEmail, string _newsletterEmail)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            int clientId         = 0;
            var testSessionToken = SessionRepository.StartNewSession(clientId);

            var updatePersonalDataCommand = new UpdatePersonalDataCommand
            {
                sessionToken           = testSessionToken,
                email                  = _email,
                firstName              = _firstName,
                lastName               = _lastName,
                changePassword         = _changePassword,
                newPassword            = _newPassword,
                receiveNewsletterEmail = _receiveNewsletterEmail,
                newsletterEmail        = _newsletterEmail
            };

            var          handler = new UpdatePersonalDataCommandHandler();
            TestDelegate result  = () => handler.Handle(updatePersonalDataCommand);

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
        public void AddPayment_CorrectAttributes_Success(int _clientId, string _paymentId)
        {
            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var addPaymentCommand = new AddPaymentCommand
            {
                sessionToken = testSessionToken,
                paymentId    = _paymentId
            };

            var lastOrder = DatabaseQueryProcessor.GetTheMostRecentOrder(_clientId);
            var total     = DatabaseQueryProcessor.GetTotal(lastOrder.orderId);

            var isSuccessfulPayment = PaymentMethod.Check(_paymentId, total);
            var handler             = new AddPaymentCommandHandler();
            var result = (SuccessInfoDto)handler.Handle(addPaymentCommand);

            DatabaseQueryProcessor.Erase();

            SessionRepository.RemoveSession(testSessionToken);
            Assert.IsTrue(result.isSuccess);
            Assert.IsTrue(isSuccessfulPayment);
        }
Esempio n. 4
0
        public void UpdatePersonalData_ChangePassword_Success(string _email, string _firstName, string _lastName, bool _changePassword, string _newPassword, bool _receiveNewsletterEmail, string _newsletterEmail)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            int clientId         = 0;
            var testSessionToken = SessionRepository.StartNewSession(clientId);

            var updatePersonalDataCommand = new UpdatePersonalDataCommand
            {
                sessionToken           = testSessionToken,
                email                  = _email,
                firstName              = _firstName,
                lastName               = _lastName,
                changePassword         = _changePassword,
                newPassword            = _newPassword,
                receiveNewsletterEmail = _receiveNewsletterEmail,
                newsletterEmail        = _newsletterEmail
            };

            var handler = new UpdatePersonalDataCommandHandler();
            var result  = (PersonalDataDto)handler.Handle(updatePersonalDataCommand);

            var foundClient = DatabaseQueryProcessor.GetClient(_email, PasswordEncryptor.encryptSha256(_newPassword));

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.IsNotNull(result);
            Assert.AreEqual(_email, result.email);
            Assert.AreEqual(_firstName, result.firstName);
            Assert.AreEqual(_lastName, result.lastName);
            Assert.AreEqual(_newsletterEmail, result.newsletterEmail);
            Assert.IsNotNull(foundClient);
        }
        public void RegisterNewClient_CorrectData_Success(string _email, string _firstName, string _lastName, string _password, bool _receiveNewsletterEmail, string _newsletterEmail)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var registerNewClient = new RegisterNewClientCommand
            {
                email     = _email,
                firstName = _firstName,
                lastName  = _lastName,
                password  = _password,
                receiveNewsletterEmail = _receiveNewsletterEmail,
                newsletterEmail        = _newsletterEmail
            };

            var handler = new RegisterNewClientCommandHandler();
            var result  = (SuccessInfoDto)handler.Handle(registerNewClient);

            var newClient = DatabaseQueryProcessor.GetClient(_email, PasswordEncryptor.encryptSha256(_password));

            DatabaseQueryProcessor.Erase();

            Assert.IsNotNull(newClient);
            Assert.IsTrue(result.isSuccess);
            Assert.AreEqual(_firstName, newClient.firstName);
            Assert.AreEqual(_lastName, newClient.lastName);
            Assert.AreEqual(_newsletterEmail, newClient.newsletterEmail);
        }
        public IResult Handle(RegisterNewClientCommand command)
        {
            if (!InputChecker.isValidEmail(command.email) ||
                !InputChecker.isValidName(command.firstName) ||
                !InputChecker.isValidName(command.lastName) ||
                (command.receiveNewsletterEmail &&
                 !InputChecker.isValidEmail(command.newsletterEmail)))
            {
                throw new Exception();
            }

            var clients      = DatabaseQueryProcessor.GetClients();
            var foundClients = clients.FindAll(c => c.email == command.email);

            if (foundClients.Count != 0)
            {
                throw new Exception();
            }

            var clientId = DatabaseQueryProcessor.CreateNewClient(
                command.email,
                command.firstName,
                command.lastName,
                PasswordEncryptor.encryptSha256(command.password),
                command.receiveNewsletterEmail ? command.newsletterEmail : ""
                );

            ThreadPool.QueueUserWorkItem(o => new RegistrationEmail().Send(clientId));


            return(new SuccessInfoDto()
            {
                isSuccess = true
            });
        }
Esempio n. 7
0
        public void AddComplaint_CorrectArgs_Success(int _clientId, int _orderId, string _description)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            var addComplaintCommand = new AddComplaintCommand
            {
                sessionToken = testSessionToken,
                orderId      = _orderId,
                description  = _description
            };

            var handler           = new AddComplaintCommandHandler();
            var result            = (SuccessInfoDto)handler.Handle(addComplaintCommand);
            var receivedComplaint = DatabaseQueryProcessor.GetComplaint(_orderId);

            SessionRepository.RemoveSession(testSessionToken);

            DatabaseQueryProcessor.Erase();

            Assert.AreEqual(receivedComplaint.description, _description);
            Assert.AreEqual(receivedComplaint.openDate, DateTime.Now.ToString("yyyy-MM-dd"));
            Assert.IsTrue(result.isSuccess);
        }
Esempio n. 8
0
        public static void FillTheDatabase()
        {
            DatabaseQueryProcessor.CreateNewProduct("Lavazza", 1500, "./img.jpg", "100% Arabica", "Good");
            DatabaseQueryProcessor.CreateNewProduct("Vergnano", 2500, "./img.jpg", "100% Robusta", "Strong");

            DatabaseQueryProcessor.CreateNewWorker(WorkerRole.a, "*****@*****.**", "240be518fabd2724ddb6f04eeb1da5967448d7e831c08c8fa822809f74c720a9");
            DatabaseQueryProcessor.CreateNewWorker(WorkerRole.b, "*****@*****.**", "240be518fabd2724ddb6f04eeb1da5967448d7e831c08c8fa822809f74c720a9");

            DatabaseQueryProcessor.CreateNewClient("*****@*****.**", "Jane", "Doe", "240be518fabd2724ddb6f04eeb1da5967448d7e831c08c8fa822809f74c720a9", "*****@*****.**");
            DatabaseQueryProcessor.CreateNewAddress(0, "Poland", "Gdynia", "Rzemieslnicza", 30445, 12, "1a");
            DatabaseQueryProcessor.CreateNewAddress(0, "Poland", "Warsaw", "Grodzka", 25487, 23, "");

            DatabaseQueryProcessor.CreateNewOrder(0, 0, 0, 1, "2018-05-12");
            DatabaseQueryProcessor.CreateNewOrderEntry(0, 0, 1);
            DatabaseQueryProcessor.CreateNewOrderEntry(0, 1, 2);

            DatabaseQueryProcessor.CreateNewOrder(0, 1, 1, 0, "2018-10-12");
            DatabaseQueryProcessor.CreateNewOrderEntry(1, 0, 1);
            DatabaseQueryProcessor.UpdateOrder(1, 1);
            DatabaseQueryProcessor.UpdateOrder(1, "2018-10-14");
            DatabaseQueryProcessor.CreateNewComplaint(1, 1, "I am dissatisfied", "2018-10-15", true);

            DatabaseQueryProcessor.CreateNewClient("*****@*****.**", "John", "Doe", "240be518fabd2724ddb6f04eeb1da5967448d7e831c08c8fa822809f74c720a9", "*****@*****.**");
            DatabaseQueryProcessor.CreateNewAddress(1, "Poland", "Cracow", "Krakowska", 30000, 1, "");

            DatabaseQueryProcessor.CreateNewOrder(1, 0, 2, 0, "2018-06-12");
            DatabaseQueryProcessor.CreateNewOrderEntry(2, 1, 1);

            DatabaseQueryProcessor.CreateNewClient("*****@*****.**", "Anne", "Bottom", "240be518fabd2724ddb6f04eeb1da5967448d7e831c08c8fa822809f74c720a9", "*****@*****.**");
        }
Esempio n. 9
0
        public void AddAddress_DuplicateAddress_Success(int _clientId, string _country, string _city, string _street, int _ZIPCode, int _buildingNumber, string _apartmentNumber)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var testSessionToken = SessionRepository.StartNewSession(_clientId);
            var addressExists    = DatabaseQueryProcessor.GetAddress(_clientId, _country, _city, _street, _ZIPCode, _buildingNumber, _apartmentNumber);

            if (addressExists != null)
            {
                DatabaseQueryProcessor.UpdateAddress(addressExists.addressId, false);
            }

            var addAddressCommand = new AddAddressCommand
            {
                sessionToken    = testSessionToken,
                country         = _country,
                city            = _city,
                street          = _street,
                ZIPCode         = _ZIPCode,
                buildingNumber  = _buildingNumber,
                apartmentNumber = _apartmentNumber
            };

            var handler     = new AddAddressCommandHandler();
            var addressBook = (AddressBookDto)handler.Handle(addAddressCommand);

            var record = DatabaseQueryProcessor.GetAddress(_clientId, _country, _city, _street, _ZIPCode, _buildingNumber, _apartmentNumber);

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.IsTrue(record.isActive);
        }
Esempio n. 10
0
        public void AddAddress_ClientDoesntExist_Exception(int _clientId)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            var addAddressCommand = new AddAddressCommand
            {
                sessionToken    = testSessionToken,
                country         = "Poland",
                city            = "Cracow",
                street          = "Urzednicza",
                ZIPCode         = 34040,
                buildingNumber  = 100,
                apartmentNumber = ""
            };

            var          handler = new AddAddressCommandHandler();
            TestDelegate result  = () => handler.Handle(addAddressCommand);

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
Esempio n. 11
0
        public void AddAddress_AddNewAddress_Success(int _clientId, string _country, string _city, string _street, int _ZIPCode, int _buildingNumber, string _apartmentNumber)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            var addAddressCommand = new AddAddressCommand
            {
                sessionToken    = testSessionToken,
                country         = _country,
                city            = _city,
                street          = _street,
                ZIPCode         = _ZIPCode,
                buildingNumber  = _buildingNumber,
                apartmentNumber = _apartmentNumber
            };

            var handler     = new AddAddressCommandHandler();
            var addressBook = (AddressBookDto)handler.Handle(addAddressCommand);

            var record = DatabaseQueryProcessor.GetAddress(_clientId, _country, _city, _street, _ZIPCode, _buildingNumber, _apartmentNumber);

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.IsNotNull(record);
            Assert.AreEqual(_clientId, record.clientId);
            Assert.AreEqual(_country, record.country);
            Assert.AreEqual(_city, record.city);
            Assert.AreEqual(_street, record.street);
            Assert.AreEqual(_ZIPCode, record.ZIPCode);
            Assert.AreEqual(_buildingNumber, record.buildingNumber);
            Assert.AreEqual(_apartmentNumber, record.apartmentNumber);
        }
        public override void PerformFunction(MySqlDataManipulator manipulator)
        {
            //Ensure that all KeywordPredictor models are loaded
            //If one is not, then a company requesting that model through its settings will cause an error
            if (!GlobalModelHelper.LoadOrTrainGlobalModels(ReflectionHelper.GetAllKeywordPredictors()))
            {
                throw new NullReferenceException("One or more global models failed to load. Server cannot start.");
            }
            DatabaseQueryProcessor processor = new DatabaseQueryProcessor(DatabaseQueryProcessorSettings.RetrieveCompanySettings(manipulator, CompanyId));

            List <RepairJobEntry> validatedData = manipulator.GetDataEntriesWhere(CompanyId, "id > 0", validated: true);
            List <string>         sentences;

            if (Flag.ToLower().Equals("complaint"))
            {
                //train model
                sentences = validatedData.Select(entry => entry.Complaint).ToList();
                if (!processor.TrainClusteringModels(manipulator, CompanyId, sentences, false))
                {
                    Console.WriteLine("Failed to train problem prediction models for company " + CompanyId);
                    return;
                }
                //register the complaint groups that the clusterer predicts with the repair job entry in the database
                foreach (RepairJobEntry entry in validatedData)
                {
                    string groups = JsonDataObjectUtil <List <int> > .ConvertObject(processor.PredictGroupsInJobData(entry, CompanyId, manipulator));

                    entry.ComplaintGroups = groups;
                    manipulator.UpdateDataEntryGroups(CompanyId, entry, complaint: true);
                }
            }
            Console.WriteLine("Trained clustering models for company " + CompanyId);
        }
        public IResult Handle(GetOrdersQuery query)
        {
            int clientId = SessionRepository.GetClientIdOfSession(query.sessionToken);

            if (clientId == -1)
            {
                throw new Exception();
            }

            var clients      = DatabaseQueryProcessor.GetClients();
            var foundClients = clients.FindAll(c => c.clientId == clientId);

            if (foundClients.Count != 1)
            {
                throw new Exception();
            }

            var orderRecords = DatabaseQueryProcessor.GetOrders(foundClients[0].clientId);
            var orderDtos    = new OrderDto[orderRecords.Count];

            for (var i = 0; i < orderRecords.Count; i++)
            {
                orderDtos[i]     = new OrderDto();
                orderDtos[i].key = orderRecords[i].orderId;
                var addressRecord = DatabaseQueryProcessor.GetAddress(orderRecords[i].addressId);
                orderDtos[i].address = new AddressDto()
                {
                    country         = addressRecord.country,
                    city            = addressRecord.city,
                    ZIPCode         = addressRecord.ZIPCode,
                    apartmentNumber = addressRecord.apartmentNumber,
                    buildingNumber  = addressRecord.buildingNumber,
                    street          = addressRecord.street,
                    key             = addressRecord.addressId
                };
                orderDtos[i].openDate  = orderRecords[i].openDate;
                orderDtos[i].closeDate = orderRecords[i].closeDate;
                orderDtos[i].status    = orderRecords[i].status;

                var orderEntriesRecords = DatabaseQueryProcessor.GetOrderEntries(orderRecords[i].orderId);
                var orderEntriesDtos    = new OrderEntryDto[orderEntriesRecords.Count];
                for (int j = 0; j < orderEntriesRecords.Count; j++)
                {
                    orderEntriesDtos[j] = new OrderEntryDto();
                    var product = DatabaseQueryProcessor.GetProduct(orderEntriesRecords[j].productId);
                    orderEntriesDtos[j].key      = orderEntriesRecords[j].orderEntryId;
                    orderEntriesDtos[j].name     = product.name;
                    orderEntriesDtos[j].price    = product.price;
                    orderEntriesDtos[j].quantity = orderEntriesRecords[j].quantity;
                }
                orderDtos[i].orderEntries = orderEntriesDtos;
                orderDtos[i].totalPrice   = orderEntriesDtos.Sum(orderEntry => orderEntry.price * orderEntry.quantity);
            }

            return(new OrdersDto()
            {
                isSuccess = true,
                orders = orderDtos
            });
        }
Esempio n. 14
0
        public IResult Handle(GetPersonalDataQuery query)
        {
            int clientId = SessionRepository.GetClientIdOfSession(query.sessionToken);

            if (clientId == -1)
            {
                throw new Exception();
            }

            var clients      = DatabaseQueryProcessor.GetClients();
            var foundClients = clients.FindAll(c => c.clientId == clientId);

            if (foundClients.Count != 1)
            {
                throw new Exception();
            }

            return(new PersonalDataDto()
            {
                isSuccess = true,
                email = foundClients[0].email,
                lastName = foundClients[0].lastName,
                firstName = foundClients[0].firstName,
                receiveNewsletterEmail = foundClients[0].isSignedUpForNewsletter,
                newsletterEmail = foundClients[0].newsletterEmail
            });
        }
Esempio n. 15
0
 static void PerformTraining()
 {
     try
     {
         while (true)
         {
             MySqlDataManipulator manipulator = new MySqlDataManipulator();
             if (!manipulator.Connect(MySqlDataManipulator.GlobalConfiguration.GetConnectionString()))
             {
                 throw new ArgumentException("MySqlDataManipulator failed to connect to the database");
             }
             Console.WriteLine("Checking company training statuses");
             List <CompanyId> companies = manipulator.GetCompaniesWithNamePortion("");
             foreach (CompanyId company in companies)
             {
                 if (manipulator.GetCountInTable(TableNameStorage.CompanyValidatedRepairJobTable.Replace("(n)", company.Id.ToString())) != 0)
                 {
                     DateTime             lastTrainedTime = DateTime.Parse(company.LastTrainedTime);
                     CompanySettingsEntry trainInterval   = manipulator.GetCompanySettingsWhere(company.Id, "SettingKey=\"" + CompanySettingsKey.RetrainInterval + "\"")[0];
                     bool shouldTrain = lastTrainedTime.AddDays(int.Parse(trainInterval.SettingValue)) <= DateTime.Now;
                     if (shouldTrain)
                     {
                         Console.WriteLine("Performing training for company " + company.LegalName);
                         DatabaseQueryProcessor processor = new DatabaseQueryProcessor(DatabaseQueryProcessorSettings.RetrieveCompanySettings(manipulator, company.Id));
                         CompanyModelUtils.TrainClusteringModel(manipulator, processor, company.Id, training: false);
                         company.LastTrainedTime = DateTime.Now.ToString();
                         manipulator.UpdateCompanyTrainingTime(company);
                         double automatedTestingResults = CompanyModelUtils.PerformAutomatedTesting(manipulator, company.Id, processor);
                         company.ModelAccuracy = (float)(100 - automatedTestingResults);
                         manipulator.UpdateCompanyAutomatedTestingResults(company);
                         Console.WriteLine("Accuracy after training: " + company.ModelAccuracy);
                     }
                 }
                 if (manipulator.GetCountInTable(TableNameStorage.CompanyNonValidatedRepairJobTable.Replace("(n)", company.Id.ToString())) != 0)
                 {
                     DateTime lastValidatedTime = DateTime.Parse(company.LastValidatedTime);
                     bool     shouldValidate    = lastValidatedTime.AddDays(14) <= DateTime.Now;
                     if (shouldValidate)
                     {
                         Console.WriteLine("Attempting to validate some non-validated data for company " + company.LegalName);
                         DatabaseQueryProcessor processor = new DatabaseQueryProcessor(DatabaseQueryProcessorSettings.RetrieveCompanySettings(manipulator, company.Id));
                         CompanyModelUtils.PerformDataValidation(manipulator, company.Id, processor);
                     }
                 }
             }
             manipulator.Close();
             Thread.Sleep(TimeSpan.FromMinutes(120));
         }
     }
     catch (ThreadInterruptedException)
     {
         Console.WriteLine("Retraining Thread Exiting");
     }
 }
Esempio n. 16
0
        string getOrderInfo(int orderId)
        {
            var orderEntries = DatabaseQueryProcessor.GetOrderEntries(orderId);
            var builder      = new StringBuilder();


            foreach (var entry in orderEntries)
            {
                builder.Append(String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", "", "product", "quantity", "price"));
            }
            return(builder.ToString());
        }
        public IResult Handle(AddPaymentCommand command)
        {
            int clientId = SessionRepository.GetClientIdOfSession(command.sessionToken);

            if (clientId == -1)
            {
                throw new Exception();
            }

            var order = DatabaseQueryProcessor.GetTheMostRecentOrder(clientId);

            if (order == null)
            {
                throw new Exception();
            }

            var totalPrice = DatabaseQueryProcessor.GetTotal(order.orderId);

            DatabaseQueryProcessor.CreateNewPayment(
                command.paymentId,
                order.orderId,
                totalPrice,
                DateTime.Now.ToString("yyyy-MM-dd")
                );

            ThreadPool.QueueUserWorkItem(
                o => new OrderPlacementEmail().Send(clientId));



            var isSuccessPayment = PaymentMethod.Check(command.paymentId, totalPrice);

            if (isSuccessPayment)
            {
                DatabaseQueryProcessor.UpdateOrder(order.orderId, 1);
                ThreadPool.QueueUserWorkItem(o =>
                                             new SuccessfullPaymentEmail().Send(clientId));
            }
            else
            {
                ThreadPool.QueueUserWorkItem(o =>
                                             new UnsuccessfullPaymentEmail().Send(clientId));
            }

            return(new SuccessInfoDto
            {
                isSuccess = true
            });
        }
Esempio n. 18
0
        public void AddOrder_AddressDoesntExist_Exception(int _clientId)
        {
            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var testOrderEntry = new OrderEntryDto
            {
                key      = 0,
                name     = "Lavazza",
                quantity = 1,
                price    = 15
            };
            var testOrderEntries = new OrderEntryDto[1];

            testOrderEntries[0] = testOrderEntry;

            var testAddress = new AddressDto
            {
                key             = 0,
                country         = "Poland",
                city            = "Gdansk",
                street          = "Rzemieslnicza",
                ZIPCode         = 30445,
                buildingNumber  = 12,
                apartmentNumber = "1a"
            };

            var addOrderCommand = new AddOrderCommand
            {
                sessionToken = testSessionToken,
                orderEntries = testOrderEntries,
                totalPrice   = "15.00",
                address      = testAddress
            };

            var          handler = new AddOrderCommandHandler();
            TestDelegate result  = () => handler.Handle(addOrderCommand);

            DatabaseQueryProcessor.Erase();

            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
Esempio n. 19
0
        public void SignIn_WrongData_Fail(string _email, string _password)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var signInCommand = new SignInCommand
            {
                email    = _email,
                password = _password
            };

            var handler = new SignInCommandHandler();
            var result  = (SignInInfoDto)handler.Handle(signInCommand);

            DatabaseQueryProcessor.Erase();
            Assert.IsFalse(result.isSuccess);
        }
Esempio n. 20
0
        public void GetShopItems_EmptyDatabase_Success()
        {
            int productsCount = 0;

            DatabaseQueryProcessor.Erase();

            var getShopItemsQuery = new GetShopItemsQuery
            {
            };

            var handler = new GetShopItemsQueryHandler();
            var result  = (ShopItemsDto)handler.Handle(getShopItemsQuery);

            DatabaseQueryProcessor.Erase();

            Assert.IsTrue(result.isSuccess);
            Assert.AreEqual(productsCount, result.shopItems.Length);
        }
        public void AddAddressBook_ClientDoesntExist_Exception(int _clientId)
        {
            DatabaseQueryProcessor.Erase();

            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            var getAddressBookQuery = new GetAddressBookQuery
            {
                sessionToken = testSessionToken,
            };

            var          handler = new GetAddressBookQueryHandler();
            TestDelegate result  = () => handler.Handle(getAddressBookQuery);

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
        public void AddPayment_ClientHasNoOrders_Success(int _clientId, string _paymentId)
        {
            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var addPaymentCommand = new AddPaymentCommand
            {
                sessionToken = testSessionToken,
                paymentId    = _paymentId
            };

            var          handler = new AddPaymentCommandHandler();
            TestDelegate result  = () => handler.Handle(addPaymentCommand);

            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
Esempio n. 23
0
        public IResult Handle(AddAddressCommand command)
        {
            int clientId = SessionRepository.GetClientIdOfSession(command.sessionToken);

            if (clientId == -1)
            {
                throw new Exception();
            }

            if (!InputChecker.isValidName(command.country) ||
                !InputChecker.isValidName(command.city) ||
                !InputChecker.isValidName(command.street) ||
                !InputChecker.isValidApartmentNumber(command.apartmentNumber))
            {
                throw new Exception();
            }

            var duplicate = DatabaseQueryProcessor.GetAddress(clientId, command.country, command.city, command.street, command.ZIPCode, command.buildingNumber, command.apartmentNumber);

            if (duplicate != null)
            {
                DatabaseQueryProcessor.UpdateAddress(duplicate.addressId, true);
            }
            else
            {
                DatabaseQueryProcessor.CreateNewAddress(
                    clientId,
                    command.country,
                    command.city,
                    command.street,
                    command.ZIPCode,
                    command.buildingNumber,
                    command.apartmentNumber
                    );
            }

            return(new GetAddressBookQueryHandler().Handle(new GetAddressBookQuery()
            {
                sessionToken = command.sessionToken
            }));
        }
Esempio n. 24
0
        public IResult Handle(GetAddressBookQuery query)
        {
            int clientId = SessionRepository.GetClientIdOfSession(query.sessionToken);

            if (clientId == -1)
            {
                throw new Exception();
            }

            var clients      = DatabaseQueryProcessor.GetClients();
            var foundClients = clients.FindAll(c => c.clientId == clientId);

            if (foundClients.Count != 1)
            {
                throw new Exception();
            }

            var addresses = DatabaseQueryProcessor.GetAddresses(foundClients[0].clientId);

            var foundActiveAddresses = addresses.FindAll(a => a.isActive == true);

            var addressesDto = new AddressDto[foundActiveAddresses.Count];

            for (var i = 0; i < foundActiveAddresses.Count; i++)
            {
                addressesDto[i]                 = new AddressDto();
                addressesDto[i].key             = foundActiveAddresses[i].addressId;
                addressesDto[i].country         = foundActiveAddresses[i].country;
                addressesDto[i].city            = foundActiveAddresses[i].city;
                addressesDto[i].street          = foundActiveAddresses[i].street;
                addressesDto[i].ZIPCode         = foundActiveAddresses[i].ZIPCode;
                addressesDto[i].buildingNumber  = foundActiveAddresses[i].buildingNumber;
                addressesDto[i].apartmentNumber = foundActiveAddresses[i].apartmentNumber;
            }

            return(new AddressBookDto()
            {
                isSuccess = true,
                addresses = addressesDto
            });
        }
        public IResult Handle(AddComplaintCommand command)
        {
            int clientId = SessionRepository.GetClientIdOfSession(command.sessionToken);

            if (clientId == -1)
            {
                throw new Exception();
            }

            var order = DatabaseQueryProcessor.GetOrder(command.orderId);

            if (order == null)
            {
                throw new Exception();
            }

            if (order.clientId != clientId)
            {
                throw new Exception();
            }

            var foundComplaint = DatabaseQueryProcessor.GetComplaint(order.orderId);

            if (foundComplaint != null)
            {
                throw new Exception();
            }

            DatabaseQueryProcessor.CreateNewComplaint(
                command.orderId,
                0,
                command.description,
                DateTime.Now.ToString("yyyy-MM-dd"),
                false
                );

            return(new SuccessInfoDto()
            {
                isSuccess = true
            });
        }
        public void RegisterNewClient_IncorrectNewsletterEmail_Exception(string _newsletterEmail)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var registerNewClient = new RegisterNewClientCommand
            {
                email     = "*****@*****.**",
                firstName = "Jane",
                lastName  = "Doe",
                password  = "******",
                receiveNewsletterEmail = true,
                newsletterEmail        = _newsletterEmail
            };

            var          handler = new RegisterNewClientCommandHandler();
            TestDelegate result  = () => handler.Handle(registerNewClient);

            DatabaseQueryProcessor.Erase();
            Assert.Throws <Exception>(result);
        }
Esempio n. 27
0
        public void AddComplaint_DifferentClientId_Exception(int _orderId)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var testSessionToken = SessionRepository.StartNewSession(0);

            var addComplaintCommand = new AddComplaintCommand
            {
                sessionToken = testSessionToken,
                orderId      = _orderId,
                description  = "I am dissatisfied"
            };

            var          handler = new AddComplaintCommandHandler();
            TestDelegate result  = () => handler.Handle(addComplaintCommand);

            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
Esempio n. 28
0
        public void AddComplaint_ComplaintAlreadyExist_Exception(int _clientId, int _orderId, string _description)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var testSessionToken = SessionRepository.StartNewSession(_clientId);

            var addComplaintCommand = new AddComplaintCommand
            {
                sessionToken = testSessionToken,
                orderId      = _orderId,
                description  = _description
            };

            var          handler = new AddComplaintCommandHandler();
            TestDelegate result  = () => handler.Handle(addComplaintCommand);

            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
Esempio n. 29
0
        public void GetOrders_ClientDoesntExist_Exception(int _clientId)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            int clientId         = _clientId;
            var testSessionToken = SessionRepository.StartNewSession(clientId);

            var getOrdersQuery = new GetOrdersQuery
            {
                sessionToken = testSessionToken,
            };

            var          handler = new GetOrdersQueryHandler();
            TestDelegate result  = () => handler.Handle(getOrdersQuery);

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.Throws <Exception>(result);
        }
Esempio n. 30
0
        public override void Build(int clientId)
        {
            var client = DatabaseQueryProcessor.GetClient(clientId);

            header  = "Dear " + client.firstName + ", \n";
            content = "We are glad that you have joined Coffeeland community! If you have any questions do not hesitate to contact us.\n";
            footer  = "Best regards,\n"
                      + "Jane Doe \n"
                      + "Customer Service Coordinator";
            subject = "Welcome in CoffeeLand " + client.firstName + "!";

            body.Append(header);
            body.AppendLine();
            body.Append(content);
            body.AppendLine();
            body.Append(footer);

            SetSubject(subject);
            SetBody();
            AddReceiver(client.firstName, client.email);
        }