public void Init()
        {
            storage = new Storage("Тестовое место хранения", StorageType.DistributionCenter)
            {
                Id = 1
            };
            user                = new User(new Employee("Иван", "Иванов", "Иванович", new EmployeePost("Менеджер"), null), "Иванов Иван", "ivanov", "pa$$w0rd", new Team("Тестовая команда", null), null);
            economicAgent       = new PhysicalPerson(new LegalForm("Легал форм", EconomicAgentType.PhysicalPerson));
            accountOrganization = new AccountOrganization("Орг1 кор имя", "орг1 длин имя", economicAgent)
            {
                Id = 1
            };
            clientOrganization = new ClientOrganization("client org", "cllll", economicAgent)
            {
                Id = 3
            };
            storage.AddAccountOrganization(accountOrganization);
            deal = new Deal("Тестовая сделка", user)
            {
                Id = 2
            };
            client        = new Client("клиент1", new ClientType("основной тип клиента"), ClientLoyalty.Follower, new ClientServiceProgram("программа 1"), new ClientRegion("Регион 1"), 10);
            deal.Contract = new ClientContract(accountOrganization, clientOrganization, "Договор 1", "1", DateTime.Now, DateTime.Now);
            client.AddDeal(deal);
            quota = new DealQuota("Тестовая квота", 20, 14, 20000.0M)
            {
                Id = 3
            };
            deal.AddQuota(quota);
            team = new Mock <Team>();

            expenditureWaybill = new ExpenditureWaybill("123", DateTime.Today, storage, deal, team.Object, quota, false, user, DeliveryAddressType.ClientAddress, "", DateTime.Today, user);
        }
Example #2
0
        public void Init()
        {
            clientType = new ClientType("Тестовый тип клиента")
            {
                Id = 1
            };
            serviceProgram = new ClientServiceProgram("Тестовая программа")
            {
                Id = 2
            };
            region = new ClientRegion("Тестовый регион")
            {
                Id = 3
            };
            legal = new LegalForm("ООО", EconomicAgentType.JuridicalPerson)
            {
                Id = 5
            };
            juridicalPerson = new JuridicalPerson(legal)
            {
                Id = 6
            };
            client = new Client("Тестовый клиент", clientType, ClientLoyalty.Customer, serviceProgram, region, 5)
            {
                Id = 4
            };
            clientOrganization = new ClientOrganization("Тестовая организация клиента", "Тестовая организация клиента", juridicalPerson)
            {
                Id = 7
            };
            var employee = new Employee("Иван", "Рюрикович", "Васильевич", new EmployeePost("Царь"), null);

            user = new User(employee, "И.В. Грозный", "ivanvas", "ivanvas", new Team("Тестовая команда", null), null);
        }
Example #3
0
        /// <summary>
        /// Получить список сделок для организации клиента
        /// </summary>
        /// <param name="clientOrganization">Организация клиента</param>
        /// <param name="user">Пользователь</param>
        /// <returns>Список сделок</returns>
        public IEnumerable <Deal> GetDealListForClientOrganization(ClientOrganization clientOrganization, User user)
        {
            var clientContractSQ = clientOrganizationRepository.SubQuery <ClientContract>().Where(x => x.ContractorOrganization.Id == clientOrganization.Id)
                                   .Select(x => x.Id);
            var deals = clientOrganizationRepository.Query <Deal>().PropertyIn(x => x.Contract.Id, clientContractSQ).ToList <Deal>();

            return(dealService.FilterByUser(deals, user, Permission.Deal_List_Details));
        }
Example #4
0
        /// <summary>
        /// Проверка, есть ли невидимые для пользователя сделки по организации клиента
        /// </summary>
        /// <param name="clientOrganization"></param>
        /// <param name="user"></param>
        public bool AreAnyRestrictedDeals(ClientOrganization clientOrganization, IEnumerable <Permission> permissionList, User user)
        {
            // Подсчитываем количества сделок, видимых пользователю с правом "все", "только командные" и "только свои"
            var allDealCount      = dealRepository.GetDealCountOnAllPermissionByClientOrganization(user.Id, clientOrganization.Id);
            var teamDealCount     = dealRepository.GetDealCountOnTeamPermissionByClientOrganization(user.Id, clientOrganization.Id);
            var personalDealCount = dealRepository.GetDealCountOnPersonalPermissionByClientOrganization(user.Id, clientOrganization.Id);

            return(AreAnyRestrictedDeals(allDealCount, teamDealCount, personalDealCount, permissionList, user));
        }
Example #5
0
        public void Init()
        {
            var juridicalLegalForm = new LegalForm("ООО", EconomicAgentType.JuridicalPerson);
            var physicalLegalForm  = new LegalForm("ООО", EconomicAgentType.PhysicalPerson);

            juridicalPerson = new JuridicalPerson(juridicalLegalForm)
            {
                Id                 = 1,
                CashierName        = "Кассиров В.В.",
                DirectorName       = "Директоров В.В.",
                DirectorPost       = "Главный директор",
                INN                = "123456789",
                KPP                = "2020202020",
                MainBookkeeperName = "Главбухова А.А.",
                OGRN               = "12345",
                OKPO               = "5431"
            };

            physicalPerson = new PhysicalPerson(physicalLegalForm)
            {
                Id        = 2,
                INN       = "234567890",
                OGRNIP    = "23456",
                OwnerName = "Физиков Ф.Ф.",
                Passport  = new ValueObjects.PassportInfo
                {
                    Series         = "18 00",
                    Number         = "689689",
                    IssuedBy       = "Центральным РОВД г. Волгограда",
                    IssueDate      = DateTime.Parse("04.04.2001"),
                    DepartmentCode = "342-001"
                }
            };

            accountOrganization = new AccountOrganization("short_Name", "full_Name", juridicalPerson)
            {
                Id = 21
            };
            clientOrganization = new ClientOrganization("Короткое имя", "Длинное имя", physicalPerson)
            {
                Id = 22
            };
            providerOrganization = new ProviderOrganization("Краткое имя", "Полное имя", juridicalPerson)
            {
                Id = 23
            };

            provider = new Provider("Тестовый поставщик", new ProviderType("Тестовый тип поставщика"), ProviderReliability.Medium, 5);
            provider.AddContractorOrganization(providerOrganization);

            client = new Client("Тестовый клиент", new ClientType("Тестовый тип клиента"), ClientLoyalty.Follower,
                                new ClientServiceProgram("Программа"), new ClientRegion("Волгоград"), (byte)3);
        }
Example #6
0
        /// <summary>
        /// Проверка возможности удаления организации клиента
        /// </summary>
        private void CheckPossibilityToRemoveClientOrganization(Client client, ClientOrganization clientOrganization, User user)
        {
            user.CheckPermission(Permission.Client_ClientOrganization_Remove);

            var clientContractSQ = clientRepository.SubQuery <ClientContract>().Where(x => x.ContractorOrganization.Id == clientOrganization.Id)
                                   .Select(x => x.Id);
            var dealsQ        = clientRepository.Query <Deal>().PropertyIn(x => x.Contract.Id, clientContractSQ).Where(x => x.Client.Id == client.Id);
            int contractCount = dealsQ.Count();

            if (contractCount > 0)
            {
                throw new Exception(String.Format("Невозможно удалить организацию клиента. Для данного клиента существуют договоры с ее участием в количестве {0} шт.",
                                                  contractCount));
            }
        }
Example #7
0
        public void Init()
        {
            // инициализация IoC
            IoCInitializer.Init();

            var juridicalLegalForm = new LegalForm("ООО", EconomicAgentType.JuridicalPerson);
            var juridicalPerson1   = new JuridicalPerson(juridicalLegalForm)
            {
                Id = 1
            };

            accountOrganization = new AccountOrganization("Тестовая собственная организация", "Тестовая собственная организация", juridicalPerson1)
            {
                Id = 1
            };

            var juridicalPerson2 = new JuridicalPerson(juridicalLegalForm)
            {
                Id = 2
            };

            clientOrganization = new ClientOrganization("Тестовая организация клиента", "Тестовая организация клиента", juridicalPerson2)
            {
                Id = 2
            };

            clientContractRepository = Mock.Get(IoCContainer.Resolve <IClientContractRepository>());
            dealRepository           = Mock.Get(IoCContainer.Resolve <IDealRepository>());

            dealIndicatorService = Mock.Get(IoCContainer.Resolve <IDealIndicatorService>());
            expenditureWaybillIndicatorService = Mock.Get(IoCContainer.Resolve <IExpenditureWaybillIndicatorService>());
            storageService = Mock.Get(IoCContainer.Resolve <IStorageService>());
            clientContractIndicatorService = Mock.Get(IoCContainer.Resolve <IClientContractIndicatorService>());
            taskRepository = Mock.Get(IoCContainer.Resolve <ITaskRepository>());

            dealServiceMock = new Mock <DealService>(dealRepository.Object, clientContractRepository.Object, taskRepository.Object, dealIndicatorService.Object,
                                                     expenditureWaybillIndicatorService.Object, storageService.Object, clientContractIndicatorService.Object);

            dealService = dealServiceMock.Object;

            user = new Mock <User>();
            user.Setup(x => x.GetPermissionDistributionType(It.IsAny <Permission>())).Returns(PermissionDistributionType.All);

            clientContractIndicatorService.Setup(x => x.CalculateCashPaymentLimitExcessByPaymentsFromClient(It.IsAny <ClientContract>())).Returns(0);
        }
Example #8
0
        /// <summary>
        /// Проверка возможности удаления организации клиента
        /// </summary>
        /// <param name="providerOrganization">Организация клиента</param>
        private void CheckPossibilityToDelete(ClientOrganization clientOrganization, User user)
        {
            // TODO: сделать проверки на возможность удаления расчетного счета, принадлежащего организации
            user.CheckPermission(Permission.ClientOrganization_Delete);

            var clientOrganizationContractSubQuery = clientOrganizationRepository.SubQuery <ContractorOrganization>().Where(x => x.Id == clientOrganization.Id);

            var dealQuery = clientOrganizationRepository.Query <Deal>()
                            .Restriction <Contract>(x => x.Contract).Where(x => x.ContractorOrganization.Id == clientOrganization.Id);

            var dealCount = dealQuery.Count();

            if (dealCount > 0)
            {
                throw new Exception(String.Format("Невозможно удалить организацию клиента, так как с ней заключены сделки в количестве {0} шт.",
                                                  dealCount));
            }
        }
Example #9
0
        /// <summary>
        /// Расчет основных показателей
        /// </summary>
        public void CalculateMainIndicators(ClientOrganization clientOrganization, ref decimal saleSum, ref decimal shippingPendingSaleSum,
                                            ref decimal paymentSum, ref decimal balance, ref decimal returnedSum, ref decimal reservedByReturnSum, User user)
        {
            var deals = clientOrganizationRepository.Query <Deal>()
                        .Restriction <ClientContract>(x => x.Contract).Where(x => x.ContractorOrganization == clientOrganization)
                        .ToList <Deal>();

            foreach (Deal deal in deals)
            {
                var allowToViewSales             = dealService.IsPossibilityToViewSales(deal, user);
                var allowToViewPayments          = dealService.IsPossibilityToViewDealPayments(deal, user);
                var allowToViewBalance           = dealService.IsPossibilityToViewBalance(deal, user);
                var allowToViewReturnsFromClient = dealService.IsPossibilityToViewReturnsFromClient(deal, user);

                var ind = dealService.CalculateMainIndicators(deal, calculateSaleSum: allowToViewSales, calculateShippingPendingSaleSum: allowToViewSales,
                                                              calculateBalance: allowToViewBalance, calculateReturnedFromClientSum: allowToViewReturnsFromClient,
                                                              calculateReservedByReturnFromClientSum: allowToViewReturnsFromClient);

                if (allowToViewSales)
                {
                    saleSum += ind.SaleSum;
                    shippingPendingSaleSum += ind.ShippingPendingSaleSum;
                }

                if (allowToViewPayments)
                {
                    paymentSum += deal.DealPaymentSum;
                }

                if (allowToViewBalance)
                {
                    balance += ind.Balance;
                }

                if (allowToViewReturnsFromClient)
                {
                    returnedSum         += ind.ReturnedFromClientSum;
                    reservedByReturnSum += ind.ReservedByReturnFromClientSum;
                }
            }
        }
Example #10
0
        /// <summary>
        /// Расчет суммы продаж для организации по конкретному клиенту
        /// </summary>
        public decimal CalculateSaleSum(ClientOrganization clientOrganization, Client client, User user)
        {
            IEnumerable <Deal> deals = null;

            var userDeals = clientOrganizationRepository.SubQuery <User>();

            userDeals.Restriction <Team>(x => x.Teams)
            .Restriction <Deal>(x => x.Deals)
            .Select(x => x.Id);

            switch (user.GetPermissionDistributionType(Permission.ExpenditureWaybill_List_Details))
            {
            case PermissionDistributionType.None:
                deals = new List <Deal>();
                break;

            case PermissionDistributionType.Personal:
                // если область распространения "Только свои", то делаем еще и ограничение по командам пользователя
                deals = clientOrganizationRepository.Query <Deal>().Where(x => x.Client == client && x.Curator == user)
                        .PropertyIn(x => x.Id, userDeals)
                        .Restriction <ClientContract>(x => x.Contract).Where(x => x.ContractorOrganization == clientOrganization)
                        .ToList <Deal>();

                break;

            case PermissionDistributionType.Teams:
                deals = clientOrganizationRepository.Query <Deal>().Where(x => x.Client == client)
                        .PropertyIn(x => x.Id, userDeals)
                        .Restriction <ClientContract>(x => x.Contract).Where(x => x.ContractorOrganization == clientOrganization)
                        .ToList <Deal>();
                break;

            case PermissionDistributionType.All:
                deals = clientOrganizationRepository.Query <Deal>().Where(x => x.Client == client)
                        .Restriction <ClientContract>(x => x.Contract).Where(x => x.ContractorOrganization == clientOrganization)
                        .ToList <Deal>();
                break;
            }

            return(deals.Sum(x => dealService.CalculateSaleSum(x, user)));
        }
Example #11
0
        public void Init()
        {
            clientType = new ClientType("Тестовый тип клиента")
            {
                Id = 1
            };
            serviceProgram = new ClientServiceProgram("Тестовая программа")
            {
                Id = 2
            };
            region = new ClientRegion("Тестовый регион")
            {
                Id = 3
            };
            client = new Client("Тестовый клиент", clientType, ClientLoyalty.Customer, serviceProgram, region, 5)
            {
                Id = 4
            };
            user = new User(new Employee("Иван", "Иванов", "Иванович", new EmployeePost("Менеджер"), null), "Иванов Иван", "ivanov", "pa$$w0rd", new Team("Тестовая команда", null), null);

            var juridicalLegalForm = new LegalForm("ООО", EconomicAgentType.JuridicalPerson);

            juridicalPerson = new JuridicalPerson(juridicalLegalForm)
            {
                Id = 1
            };
            accountOrganization = new AccountOrganization("Тестовое юридическое лицо", "Тестовое юридическое лицо", juridicalPerson)
            {
                Id = 1
            };
            clientOrganization = new ClientOrganization("Тестовая организация клиента", "Тестовая организация клиента", new JuridicalPerson(juridicalLegalForm)
            {
                Id = 2
            })
            {
                Id = 3
            };
            contract = new ClientContract(accountOrganization, clientOrganization, "12", "1", DateTime.Now, DateTime.Now);
        }
Example #12
0
        public async Task <Unit> Handle(CreateClientOrganizationCommand request, CancellationToken cancellationToken)
        {
            var user = _userAccessor.GetUser();

            //Create entity
            var entity = new ClientOrganization(request.Id, request.Name, request.Address,
                                                request.ContactInfo, Guid.Parse(user.FindFirst(ClaimTypes.NameIdentifier).Value));

            //  await _context.ClientOrganizations.AddAsync(entity, cancellationToken);
            await _context.SaveChangesAsync(cancellationToken);

            //Send notification
            await _mediator.Publish(new ClientCompanyCreated()
            {
                PrimaryEntityId   = entity.Id,
                GroupEntityId     = entity.Id,
                GroupEntityName   = entity.Name,
                PrimaryEntityName = entity.Name,
                UserName          = user.Identity.Name
            }, cancellationToken);

            return(Unit.Value);
        }
Example #13
0
        public void Delete(ClientOrganization clientOrganization, User user)
        {
            CheckPossibilityToDelete(clientOrganization, user);

            // Удаляем все расчетные счета из организации
            var bankAccountList = new List <RussianBankAccount>(clientOrganization.RussianBankAccounts);

            foreach (var bankAccount in bankAccountList)
            {
                clientOrganization.DeleteRussianBankAccount(bankAccount);
            }

            // Удаляем организацию из всех клиентов, где она фигурировала
            var clientOrganizationContractorList = new List <Contractor>(clientOrganization.Contractors);

            foreach (var contractor in clientOrganizationContractorList)
            {
                Client client = contractor.As <Client>();
                client.RemoveContractorOrganization(clientOrganization);
            }

            // Удаляем саму организацию
            clientOrganizationRepository.Delete(clientOrganization);
        }
Example #14
0
 /// <summary>
 /// Рассчитать список балансов по сделкам, принадлежащим данной организации клиента, сгруппированный по сделкам, на дату
 /// (для печатной формы - все сделки, все виды документов)
 /// </summary>
 public IList <InitialBalanceInfo> CalculateBalanceOnDateByClientOrganization(ClientOrganization clientOrganization, DateTime date, User user)
 {
     return(CalculateBalanceOnDate(null, null, new List <int> {
         clientOrganization.Id
     }, date, user, usePermission: false));
 }
        public void Init()
        {
            employee1           = new Employee("Работник 1 имя", "Работник 1 фамилия", "Работник 1 отчество", new EmployeePost("Работник 1 пост"), null);
            curator             = new User(employee1, "Куратор", "log", "pas", new Team("Тестовая команда", null), null);
            team                = new Team("123", curator);
            economicAgent       = new PhysicalPerson(new LegalForm("Легал форм", EconomicAgentType.PhysicalPerson));
            accountOrganization = new AccountOrganization("Орг1 кор имя", "орг1 длин имя", economicAgent)
            {
                Id = 1
            };
            accountOrganizationAnother = new AccountOrganization("Орг2 кор имя", "орг2 длин имя", economicAgent)
            {
                Id = 2
            };
            clientOrganization = new ClientOrganization("client org", "cllll", economicAgent)
            {
                Id = 3
            };
            client = new Client("клиент1", new ClientType("основной тип клиента"), ClientLoyalty.Follower, new ClientServiceProgram("программа 1"), new ClientRegion("Регион 1"), 10);
            deal   = new Deal("Тестовая сделка", curator);
            client.AddDeal(deal);
            storage = new Storage("Склад 1", StorageType.ExtraStorage);
            storage.AddAccountOrganization(accountOrganization);
            storage.AddAccountOrganization(accountOrganizationAnother);
            storage2 = new Storage("Склад 2", StorageType.ExtraStorage);
            returnFromClientReason  = new ReturnFromClientReason("Брак");
            returnFromClientWaybill = new ReturnFromClientWaybill("142", DateTime.Today, accountOrganization, deal, team, storage, returnFromClientReason, curator, curator, DateTime.Now);
            valueAddedTax           = new ValueAddedTax("18%", 18);
            ag     = new ArticleGroup("Группа товаров", "Группа товаров");
            art1   = new Article("Товар 1", ag, new MeasureUnit("шт.", "штуки", "123", 1), false);
            art2   = new Article("Товар 2", ag, new MeasureUnit("шт.", "штуки", "123", 1), false);
            art3   = new Article("Товар 3", ag, new MeasureUnit("шт.", "штуки", "123", 1), false);
            Prices = new List <ArticleAccountingPrice>();
            Prices.Add(new ArticleAccountingPrice(art1, 10M));
            Prices.Add(new ArticleAccountingPrice(art2, 13M));
            Prices.Add(new ArticleAccountingPrice(art3, 15M));

            deal1  = new Deal("Deal1", curator);
            deal2  = new Deal("Deal2", curator);
            quota1 = new DealQuota("qq", 1);
            quota2 = new DealQuota("qq", 2);

            deal1.AddQuota(quota1);
            deal2.AddQuota(quota2);
            deal1.Contract = new ClientContract(accountOrganization, clientOrganization, "Договор", "1", DateTime.Now, DateTime.Now);
            deal2.Contract = new ClientContract(accountOrganizationAnother, clientOrganization, "kk", "22", DateTime.Today, DateTime.Now);

            recRow1 = new ReceiptWaybillRow(art1, 5, 50, new ValueAddedTax("18%", 18))
            {
                Id = Guid.NewGuid()
            };
            recRow1_1 = new ReceiptWaybillRow(art1, 2, 30, new ValueAddedTax("18%", 18))
            {
                Id = Guid.NewGuid()
            };
            recRow2 = new ReceiptWaybillRow(art2, 7, 35, new ValueAddedTax("18%", 18))
            {
                Id = Guid.NewGuid()
            };
            recRow3 = new ReceiptWaybillRow(art3, 9, 90, new ValueAddedTax("18%", 18))
            {
                Id = Guid.NewGuid()
            };
            recRow1.PurchaseCost = 50 / 5;
            recRow1.PurchaseCost = 35 / 7;
            recRow1.PurchaseCost = 90 / 9;

            saleRow1 = new ExpenditureWaybillRow(recRow1, 3, valueAddedTax)
            {
                Id = Guid.NewGuid()
            };
            saleRow1_1 = new ExpenditureWaybillRow(recRow1_1, 1, valueAddedTax)
            {
                Id = Guid.NewGuid()
            };
            saleRow2 = new ExpenditureWaybillRow(recRow2, 4, valueAddedTax)
            {
                Id = Guid.NewGuid()
            };
            saleRow3 = new ExpenditureWaybillRow(recRow3, 5, valueAddedTax)
            {
                Id = Guid.NewGuid()
            };

            saleRowAnother1 = new ExpenditureWaybillRow(recRow1, 3, valueAddedTax)
            {
                Id = Guid.NewGuid()
            };
            saleRowAnother2 = new ExpenditureWaybillRow(recRow2, 4, valueAddedTax)
            {
                Id = Guid.NewGuid()
            };
            saleRowAnother3 = new ExpenditureWaybillRow(recRow3, 5, valueAddedTax)
            {
                Id = Guid.NewGuid()
            };

            sale = new ExpenditureWaybill("1", DateTime.Today, storage, deal1, team, quota1, true, curator, DeliveryAddressType.ClientAddress, "", DateTime.Now, curator)
            {
                Id = Guid.NewGuid()
            };
            saleAnother = new ExpenditureWaybill("1", DateTime.Today, storage, deal2, team, quota2, true, curator, DeliveryAddressType.ClientAddress, "", DateTime.Now, curator)
            {
                Id = Guid.NewGuid()
            };

            sale.As <ExpenditureWaybill>().AddRow((ExpenditureWaybillRow)saleRow1);
            sale.As <ExpenditureWaybill>().AddRow((ExpenditureWaybillRow)saleRow2);
            sale.As <ExpenditureWaybill>().AddRow((ExpenditureWaybillRow)saleRow3);
            saleAnother.As <ExpenditureWaybill>().AddRow((ExpenditureWaybillRow)saleRowAnother1);
            saleAnother.As <ExpenditureWaybill>().AddRow((ExpenditureWaybillRow)saleRowAnother2);
            saleAnother.As <ExpenditureWaybill>().AddRow((ExpenditureWaybillRow)saleRowAnother3);

            sale.As <ExpenditureWaybill>().Accept(Prices, false, curator, DateTime.Now);

            saleAnother.As <ExpenditureWaybill>().Accept(Prices, false, curator, DateTime.Now);
        }
Example #16
0
 /// <summary>
 /// Проверка возможности удаления иностранного расчетного счета
 /// </summary>
 /// <param name="clientOrganization">Организация клиента, которой принадлежит расчетный счет</param>
 /// <param name="bankAccount">Расчетный счет</param>
 private void CheckPossibilityToDeleteForeignBankAccount(ClientOrganization clientOrganization, ForeignBankAccount bankAccount)
 {
     // TODO: сделать проверки на возможность удаления расчетного счета
     //organizationService.CheckBankAccountDeletionPossibility(bankAccount);
 }
Example #17
0
 public void DeleteForeignBankAccount(ClientOrganization clientOrganization, ForeignBankAccount bankAccount)
 {
     CheckPossibilityToDeleteForeignBankAccount(clientOrganization, bankAccount);
     clientOrganization.DeleteForeignBankAccount(bankAccount);
 }
Example #18
0
        public void Save(ClientOrganization clientOrganization)
        {
            organizationService.CheckOrganizationUniqueness(clientOrganization);

            clientOrganizationRepository.Save(clientOrganization);
        }
Example #19
0
 /// <summary>
 /// Получение списка команд для документа сделки (команды пользователя + команды, что могут видеть сделку)
 /// </summary>
 /// <param name="clientOrganization">Организация клиента</param>
 /// <param name="user">Пользователь</param>
 /// <returns>Список команд</returns>
 public IEnumerable <Team> GetTeamListForDealDocumentByClientOrganization(ClientOrganization clientOrganization, User user)
 {
     return(dealRepository.GetTeamListForDealDocumentByClientOrganization(clientOrganization.Id, user.Id));
 }
Example #20
0
        public CCWData GetCCW(string regi, string plate, string vin, string userId, string guid, string directory)
        {
            // check we have the right headers.
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(guid) || string.IsNullOrEmpty(directory))
            {
                return(null);
            }

            var batchUser = _configuration.GetValue <string>("CCW_USER_ID");
            var logPrefix = batchUser == userId ? "[Hangfire]" : "";

            // Check for the following data:
            // 1. registration
            // 2. plate
            // 3. decal

            VehicleDescription vehicle = null;

            if (regi != null)
            {
                // format the regi.
                try
                {
                    int registration = int.Parse(regi);
                    // zero padded, 8 digits
                    regi = registration.ToString("D8");
                }
                catch (Exception)
                {
                    _logger.LogInformation($"{logPrefix} Exception occured parsing registration number {regi}.");
                }

                vehicle = _ccwService.GetBCVehicleForRegistrationNumber(regi, userId, guid, directory);
            }

            if (vehicle == null && plate != null) // check the plate.
            {
                vehicle = _ccwService.GetBCVehicleForLicensePlateNumber(plate, userId, guid, directory);
            }

            if (vehicle == null && vin != null) // check the vin.
            {
                vehicle = _ccwService.GetBCVehicleForSerialNumber(vin, userId, guid, directory);
            }

            if (vehicle == null)
            {
                return(null);
            }

            string icbcRegistrationNumber = vehicle.registrationNumber;

            CCWData ccwdata = null;

            if (_context.CCWDatas.Any(x => x.ICBCRegistrationNumber == icbcRegistrationNumber))
            {
                ccwdata = _context.CCWDatas.First(x => x.ICBCRegistrationNumber == icbcRegistrationNumber);
                _logger.LogInformation($"{logPrefix} Found CCW record for Registration # " + ccwdata.ICBCRegistrationNumber);
            }
            else
            {
                _logger.LogInformation($"{logPrefix} Creating new CCW record");
                ccwdata = new CCWData();
            }

            // update the ccw record.
            ccwdata.ICBCBody               = vehicle.bodyCode;
            ccwdata.ICBCColour             = vehicle.colour;
            ccwdata.ICBCCVIPDecal          = vehicle.inspectionDecalNumber;
            ccwdata.ICBCCVIPExpiry         = vehicle.inspectionExpiryDate;
            ccwdata.ICBCFleetUnitNo        = SanitizeInt(vehicle.fleetUnitNumber);
            ccwdata.ICBCFuel               = vehicle.fuelTypeDescription;
            ccwdata.ICBCGrossVehicleWeight = SanitizeInt(vehicle.grossVehicleWeight);
            ccwdata.ICBCMake               = vehicle.make;
            ccwdata.ICBCModel              = vehicle.model;
            ccwdata.ICBCGrossVehicleWeight = SanitizeInt(vehicle.grossVehicleWeight);
            ccwdata.ICBCModelYear          = SanitizeInt(vehicle.modelYear);
            ccwdata.ICBCNetWt              = SanitizeInt(vehicle.netWeight);
            ccwdata.ICBCNotesAndOrders     = vehicle.cvipDataFromLastInspection;
            ccwdata.ICBCOrderedOn          = vehicle.firstOpenOrderDate;
            ccwdata.ICBCRateClass          = vehicle.rateClass;
            ccwdata.ICBCRebuiltStatus      = vehicle.statusCode;
            ccwdata.ICBCRegistrationNumber = vehicle.registrationNumber;
            ccwdata.ICBCRegOwnerAddr1      = vehicle.owner.mailingAddress1;
            ccwdata.ICBCRegOwnerAddr2      = vehicle.owner.mailingAddress2;
            ccwdata.ICBCRegOwnerCity       = vehicle.owner.mailingAddress3;
            ccwdata.ICBCRegOwnerName       = vehicle.owner.name1;
            ccwdata.ICBCRegOwnerPODL       = vehicle.principalOperatorDlNum;
            ccwdata.ICBCRegOwnerPostalCode = vehicle.owner.postalCode;
            ccwdata.ICBCRegOwnerProv       = vehicle.owner.mailingAddress4;
            ccwdata.ICBCRegOwnerRODL       = vehicle.owner.driverLicenseNumber;
            ccwdata.ICBCSeatingCapacity    = SanitizeInt(vehicle.seatingCapacity);
            ccwdata.ICBCVehicleType        = vehicle.vehicleType + " - " + vehicle.vehicleTypeDescription;

            ccwdata.ICBCVehicleIdentificationNumber = vehicle.serialNumber;

            ccwdata.NSCPlateDecal          = vehicle.decalNumber;
            ccwdata.NSCPolicyEffectiveDate = vehicle.policyStartDate;
            ccwdata.NSCPolicyExpiryDate    = vehicle.policyExpiryDate;
            ccwdata.NSCPolicyStatus        = vehicle.policyStatus + " - " + vehicle.policyStatusDescription;

            // policyAquiredCurrentStatusDate is the preferred field, however it is often null.
            if (vehicle.policyAcquiredCurrentStatusDate != null)
            {
                ccwdata.NSCPolicyStatusDate = vehicle.policyAcquiredCurrentStatusDate;
            }
            else if (vehicle.policyTerminationDate != null)
            {
                ccwdata.NSCPolicyStatusDate = vehicle.policyTerminationDate;
            }
            else if (vehicle.policyReplacedOnDate != null)
            {
                ccwdata.NSCPolicyStatusDate = vehicle.policyReplacedOnDate;
            }
            else if (vehicle.policyStartDate != null)
            {
                ccwdata.NSCPolicyStatusDate = vehicle.policyStartDate;
            }

            if (vehicle.owner != null)
            {
                ccwdata.ICBCRegOwnerRODL = vehicle.owner.driverLicenseNumber;
            }

            ccwdata.ICBCLicencePlateNumber = vehicle.policyNumber;
            // these fields are the same.
            ccwdata.NSCPolicyNumber = vehicle.policyNumber;
            ccwdata.NSCClientNum    = vehicle.nscNumber;

            ccwdata.DateFetched = DateTime.UtcNow;

            // get the nsc client organization data.

            bool foundNSCData = false;

            if (!string.IsNullOrEmpty(ccwdata.NSCPolicyNumber))
            {
                string organizationNameCode = "LE";

                ClientOrganization clientOrganization = _ccwService.GetCurrentClientOrganization(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory);

                if (clientOrganization != null)
                {
                    foundNSCData = true;
                    ccwdata.NSCCarrierConditions   = clientOrganization.nscInformation.carrierStatus;
                    ccwdata.NSCCarrierName         = clientOrganization.displayName;
                    ccwdata.NSCCarrierSafetyRating = clientOrganization.nscInformation.safetyRating;
                }

                // now try the individual service if there was no match.
                if (foundNSCData == false)
                {
                    ClientIndividual clientIndividual = _ccwService.GetCurrentClientIndividual(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory);

                    if (clientIndividual != null)
                    {
                        foundNSCData = true;
                        ccwdata.NSCCarrierConditions   = clientIndividual.nscInformation.carrierStatus;
                        ccwdata.NSCCarrierName         = clientIndividual.displayName;
                        ccwdata.NSCCarrierSafetyRating = clientIndividual.nscInformation.safetyRating;
                    }
                }
            }

            if (ccwdata.Id > 0)
            {
                var bus = _context.SchoolBuss.FirstOrDefault(x => x.CCWDataId == ccwdata.Id);

                var changes = _context.GetChanges(ccwdata, "DateFetched");

                if (bus != null && changes.Count > 0)
                {
                    var ccwNotification = (new CCWNotification
                    {
                        HasBeenViewed = false,
                    });

                    bus.CCWNotifications.Add(ccwNotification);

                    foreach (var change in changes)
                    {
                        ccwNotification.CCWNotificationDetails.Add(new CCWNotificationDetail
                        {
                            ColName        = change.ColName,
                            ColDescription = change.ColDescription,
                            ValueFrom      = change.ValueFrom,
                            ValueTo        = change.ValueTo
                        });
                    }
                }
            }
            else
            {
                _context.Add(ccwdata);
            }

            _logger.LogInformation($"{logPrefix} CCW data has been added/updated.");
            _context.SaveChanges();

            return(ccwdata);
        }
Example #21
0
 public void Delete(ClientOrganization Value)
 {
     Value.DeletionDate = DateTime.Now;
     CurrentSession.SaveOrUpdate(Value);
 }
Example #22
0
 public void Save(ClientOrganization Value)
 {
     CurrentSession.SaveOrUpdate(Value);
 }
Example #23
0
        public virtual IActionResult GetCCW([FromQuery] string regi, [FromQuery] string plate, [FromQuery] string vin)
        {
            // check we have the right headers.
            if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(guid) || string.IsNullOrEmpty(directory))
            {
                return(new UnauthorizedResult());
            }

            // Check for the following data:
            // 1. registration
            // 2. plate
            // 3. decal

            VehicleDescription vehicle = null;

            if (regi != null)
            {
                // format the regi.
                try
                {
                    int registration = int.Parse(regi);
                    // zero padded, 8 digits
                    regi = registration.ToString("D8");
                }
                catch (Exception e)
                {
                    _logger.LogInformation("Exception occured parsing registration number " + regi);
                }

                try
                {
                    vehicle = _service.GetBCVehicleForRegistrationNumber(regi, userId, guid, directory);
                }
                catch (Exception e)
                {
                    vehicle = null;
                }
            }
            if (vehicle == null && plate != null) // check the plate.
            {
                try
                {
                    vehicle = _service.GetBCVehicleForLicensePlateNumber(plate, userId, guid, directory);
                }
                catch (Exception e)
                {
                    vehicle = null;
                }
            }
            if (vehicle == null && vin != null) // check the vin.
            {
                try
                {
                    vehicle = _service.GetBCVehicleForSerialNumber(vin, userId, guid, directory);
                }
                catch (Exception e)
                {
                    vehicle = null;
                }
            }
            if (vehicle == null)
            {
                return(new StatusCodeResult(404)); // Can't find the vehicle.
            }
            else
            {
                string  icbcRegistrationNumber = vehicle.registrationNumber;
                CCWData ccwdata  = null;
                bool    existing = false;
                if (_context.CCWDatas.Any(x => x.ICBCRegistrationNumber == icbcRegistrationNumber))
                {
                    ccwdata  = _context.CCWDatas.First(x => x.ICBCRegistrationNumber == icbcRegistrationNumber);
                    existing = true;

                    _logger.LogInformation("Found record for Registration # " + ccwdata.ICBCRegistrationNumber);
                }
                else
                {
                    _logger.LogInformation("Creating new record");
                    ccwdata = new CCWData();
                }
                // update the ccw record.

                ccwdata.ICBCBody               = vehicle.bodyCode;
                ccwdata.ICBCColour             = vehicle.colour;
                ccwdata.ICBCCVIPDecal          = vehicle.inspectionDecalNumber;
                ccwdata.ICBCCVIPExpiry         = vehicle.inspectionExpiryDate;
                ccwdata.ICBCFleetUnitNo        = SanitizeInt(vehicle.fleetUnitNumber);
                ccwdata.ICBCFuel               = vehicle.fuelTypeDescription;
                ccwdata.ICBCGrossVehicleWeight = SanitizeInt(vehicle.grossVehicleWeight);
                ccwdata.ICBCMake               = vehicle.make;
                ccwdata.ICBCModel              = vehicle.model;
                ccwdata.ICBCGrossVehicleWeight = SanitizeInt(vehicle.grossVehicleWeight);
                ccwdata.ICBCModelYear          = SanitizeInt(vehicle.modelYear);
                ccwdata.ICBCNetWt              = SanitizeInt(vehicle.netWeight);
                ccwdata.ICBCNotesAndOrders     = vehicle.cvipDataFromLastInspection;
                ccwdata.ICBCOrderedOn          = vehicle.firstOpenOrderDate;
                ccwdata.ICBCRateClass          = vehicle.rateClass;
                ccwdata.ICBCRebuiltStatus      = vehicle.statusCode;
                ccwdata.ICBCRegistrationNumber = vehicle.registrationNumber;
                ccwdata.ICBCRegOwnerAddr1      = vehicle.owner.mailingAddress1;
                ccwdata.ICBCRegOwnerAddr2      = vehicle.owner.mailingAddress2;
                ccwdata.ICBCRegOwnerCity       = vehicle.owner.mailingAddress3;
                ccwdata.ICBCRegOwnerName       = vehicle.owner.name1;
                ccwdata.ICBCRegOwnerPODL       = vehicle.principalOperatorDlNum;
                ccwdata.ICBCRegOwnerPostalCode = vehicle.owner.postalCode;
                ccwdata.ICBCRegOwnerProv       = vehicle.owner.mailingAddress4;
                ccwdata.ICBCRegOwnerRODL       = vehicle.owner.driverLicenseNumber;
                ccwdata.ICBCSeatingCapacity    = SanitizeInt(vehicle.seatingCapacity);
                ccwdata.ICBCVehicleType        = vehicle.vehicleType + " - " + vehicle.vehicleTypeDescription;

                ccwdata.ICBCVehicleIdentificationNumber = vehicle.serialNumber;

                ccwdata.NSCPlateDecal          = vehicle.decalNumber;
                ccwdata.NSCPolicyEffectiveDate = vehicle.policyStartDate;
                ccwdata.NSCPolicyExpiryDate    = vehicle.policyExpiryDate;
                ccwdata.NSCPolicyStatus        = vehicle.policyStatus + " - " + vehicle.policyStatusDescription;

                // policyAquiredCurrentStatusDate is the preferred field, however it is often null.
                if (vehicle.policyAcquiredCurrentStatusDate != null)
                {
                    ccwdata.NSCPolicyStatusDate = vehicle.policyAcquiredCurrentStatusDate;
                }
                else if (vehicle.policyTerminationDate != null)
                {
                    ccwdata.NSCPolicyStatusDate = vehicle.policyTerminationDate;
                }
                else if (vehicle.policyReplacedOnDate != null)
                {
                    ccwdata.NSCPolicyStatusDate = vehicle.policyReplacedOnDate;
                }
                else if (vehicle.policyStartDate != null)
                {
                    ccwdata.NSCPolicyStatusDate = vehicle.policyStartDate;
                }

                if (vehicle.owner != null)
                {
                    ccwdata.ICBCRegOwnerRODL = vehicle.owner.driverLicenseNumber;
                }
                ccwdata.ICBCLicencePlateNumber = vehicle.policyNumber;
                // these fields are the same.
                ccwdata.NSCPolicyNumber = vehicle.policyNumber;
                ccwdata.NSCClientNum    = vehicle.nscNumber;

                ccwdata.DateFetched = DateTime.UtcNow;

                // get the nsc client organization data.

                bool foundNSCData = false;

                if (!string.IsNullOrEmpty(ccwdata.NSCPolicyNumber))
                {
                    string organizationNameCode = "LE";
                    try
                    {
                        ClientOrganization clientOrganization = _service.GetCurrentClientOrganization(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory);
                        foundNSCData = true;
                        ccwdata.NSCCarrierConditions   = clientOrganization.nscInformation.carrierStatus;
                        ccwdata.NSCCarrierName         = clientOrganization.displayName;
                        ccwdata.NSCCarrierSafetyRating = clientOrganization.nscInformation.safetyRating;
                    }
                    catch (AggregateException ae)
                    {
                        _logger.LogInformation("Aggregate Exception occured during GetCurrentClientOrganization");
                        ae.Handle((x) =>
                        {
                            if (x is FaultException <CVSECommonException> ) // From the web service.
                            {
                                _logger.LogDebug("CVSECommonException:");
                                FaultException <CVSECommonException> fault = (FaultException <CVSECommonException>)x;
                                _logger.LogDebug("errorId: {0}", fault.Detail.errorId);
                                _logger.LogDebug("errorMessage: {0}", fault.Detail.errorMessage);
                                _logger.LogDebug("systemError: {0}", fault.Detail.systemError);
                                return(true);
                            }
                            return(true); // ignore other exceptions
                        });
                    }
                    catch (Exception e)
                    {
                        _logger.LogInformation("Unknown Error retrieving NSC data.");
                    }

                    // now try the individual service if there was no match.

                    if (foundNSCData == false)
                    {
                        try
                        {
                            ClientIndividual clientIndividual = _service.GetCurrentClientIndividual(ccwdata.NSCClientNum, organizationNameCode, userId, guid, directory);
                            foundNSCData = true;
                            ccwdata.NSCCarrierConditions   = clientIndividual.nscInformation.carrierStatus;
                            ccwdata.NSCCarrierName         = clientIndividual.displayName;
                            ccwdata.NSCCarrierSafetyRating = clientIndividual.nscInformation.safetyRating;
                        }
                        catch (AggregateException ae)
                        {
                            _logger.LogInformation("Aggregate Exception occured during GetCurrentClientIndividual");
                            ae.Handle((x) =>
                            {
                                if (x is FaultException <CVSECommonException> ) // From the web service.
                                {
                                    _logger.LogDebug("CVSECommonException:");
                                    FaultException <CVSECommonException> fault = (FaultException <CVSECommonException>)x;
                                    _logger.LogDebug("errorId: {0}", fault.Detail.errorId);
                                    _logger.LogDebug("errorMessage: {0}", fault.Detail.errorMessage);
                                    _logger.LogDebug("systemError: {0}", fault.Detail.systemError);
                                    return(true);
                                }
                                return(true); // ignore other exceptions
                            });
                        }
                        catch (Exception e)
                        {
                            _logger.LogInformation("Unknown Error retrieving Individual NSC data.");
                        }
                    }
                }

                if (ccwdata.Id > 0)
                {
                    _context.Update(ccwdata);
                }
                else
                {
                    _context.Add(ccwdata);
                }
                _context.SaveChanges();


                return(new ObjectResult(ccwdata));
            }
        }