public List <AssetBase> getFixedIncomeAssetForClient()
        {
            List <AssetBase> assets = new List <AssetBase>();

            Client      client      = edisRepo.GetClientSync(User.Identity.GetUserId(), DateTime.Now);
            ClientGroup clientGroup = edisRepo.GetClientGroupSync(client.ClientGroupId, DateTime.Now);

            if (clientGroup.MainClientId == client.Id)
            {
                List <GroupAccount>  groupAccounts  = edisRepo.GetAccountsForClientGroupSync(clientGroup.ClientGroupNumber, DateTime.Now);
                List <ClientAccount> clientAccounts = new List <ClientAccount>();
                clientGroup.GetClientsSync().ForEach(c => clientAccounts.AddRange(c.GetAccountsSync()));

                groupAccounts.ForEach(a => assets.AddRange(a.GetAssetsSync().OfType <FixedIncome>().Cast <AssetBase>().ToList()));
                clientAccounts.ForEach(a => assets.AddRange(a.GetAssetsSync().OfType <FixedIncome>().Cast <AssetBase>().ToList()));
            }
            else
            {
                List <ClientAccount> accounts = edisRepo.GetAccountsForClientSync(client.ClientNumber, DateTime.Now);
                accounts.ForEach(a => assets.AddRange(a.GetAssetsSync().OfType <FixedIncome>().Cast <AssetBase>().ToList()));
            }

            return(assets);
        }
        public List <LiabilityBase> getMarginLendingLiabilitiesForAdviser(string clientGroupId)
        {
            List <LiabilityBase> liabilities = new List <LiabilityBase>();

            if (string.IsNullOrEmpty(clientGroupId))
            {
                List <GroupAccount>  groupAccounts  = edisRepo.getAllClientGroupAccountsForAdviser(User.Identity.GetUserId(), DateTime.Now);
                List <ClientAccount> clientAccounts = edisRepo.getAllClientAccountsForAdviser(User.Identity.GetUserId(), DateTime.Now);
                groupAccounts.ForEach(a => liabilities.AddRange(a.GetLiabilitiesSync().OfType <MarginLending>().Cast <LiabilityBase>().ToList()));
                clientAccounts.ForEach(a => liabilities.AddRange(a.GetLiabilitiesSync().OfType <MarginLending>().Cast <LiabilityBase>().ToList()));
            }
            else
            {
                ClientGroup          clientGroup    = edisRepo.getClientGroupByGroupId(clientGroupId);
                List <GroupAccount>  accounts       = clientGroup.GetAccountsSync(DateTime.Now);
                List <ClientAccount> clientAccounts = new List <ClientAccount>();
                clientGroup.GetClientsSync().ForEach(c => clientAccounts.AddRange(c.GetAccountsSync()));

                accounts.ForEach(a => liabilities.AddRange(a.GetLiabilitiesSync().OfType <MarginLending>().Cast <LiabilityBase>().ToList()));
                clientAccounts.ForEach(a => liabilities.AddRange(a.GetLiabilitiesSync().OfType <MarginLending>().Cast <LiabilityBase>().ToList()));
            }

            return(liabilities);
        }
Exemplo n.º 3
0
        public async Task RemoveFromGroup(RemoveFromGroupRequest request)
        {
            if (request.UserIds == null)
            {
                request.UserIds = new List <string>();
            }

            FilterDefinition <ClientGroup> builder = Builders <ClientGroup> .Filter.Eq("name", request.GroupName);

            ClientGroup clientGroup = await clientGroupRepository.FindAsync(builder);

            if (clientGroup != null)
            {
                foreach (string userId in request.UserIds)
                {
                    clientGroup.UserIds.Remove(userId);
                }
                await clientGroupRepository.UpdateAsync(clientGroup, clientGroup.Id);
            }
            else
            {
                return;
            }
        }
 public FinishedLoadingScriptServer(ClientGroup ActiveGroup)
     : base(ScriptName)
 {
     this.ActiveGroup = ActiveGroup;
 }
Exemplo n.º 5
0
 public JoinRoomLocalScriptServer(string RoomID, string CurrentDifficulty, List <Player> ListJoiningPlayer, ClientGroup ActiveGroup)
     : base(ScriptName)
 {
     this.RoomID            = RoomID;
     this.CurrentDifficulty = CurrentDifficulty;
     this.ListJoiningPlayer = ListJoiningPlayer;
     this.ActiveGroup       = ActiveGroup;
 }
Exemplo n.º 6
0
        public async Task SendMessage(string clientGroupName, MessageViewModel message)
        {
            FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

            ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

            foreach (string item in clientGroup.UserIds)
            {
                try
                {
                    FilterDefinition <FcmInfo> user = Builders <FcmInfo> .Filter.Eq("user_id", item);

                    string token  = (await fcmInfoRepository.FindAsync(user))?.DeviceToken;
                    User   sender = await userRepository.GetByIdAsync(ObjectId.Parse(message.SenderId));

                    var notifyBody = string.Empty;
                    switch (message.MessageType.Value)
                    {
                    case MessageBaseType.Text:
                        notifyBody = (message.Content as List <string>)[0];
                        break;

                    case MessageBaseType.Image:
                        notifyBody = "Đã gửi một ảnh. ";
                        break;

                    case MessageBaseType.MultiMedia:
                        notifyBody = "Đã gửi một phương tiện. ";
                        break;

                    case MessageBaseType.PostThumbnail:
                        notifyBody = "Đã gửi một liên kết. ";
                        break;

                    case MessageBaseType.ConversationActivity:
                        notifyBody = "Đã có hoạt động mới. ";
                        break;

                    case MessageBaseType.Other:
                        notifyBody = "Đã có thông báo mới. ";
                        break;

                    default:
                        break;
                    }

                    try
                    {
                        FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                        {
                            Token = token,
                            Data  = new Dictionary <string, string>()
                            {
                                { "message", JsonConvert.SerializeObject(message) }
                            },
                            Notification = new Notification()
                            {
                                Title    = sender.LastName,
                                Body     = notifyBody,
                                ImageUrl = sender.AvatarHash
                            }
                        };
                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                    }
                    catch (Exception)
                    {
                        //Do nothing
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }
Exemplo n.º 7
0
 public FinishedLoadingScriptServer(ClientGroup ActiveGroup, PlayerWithID Owner)
     : base(ScriptName)
 {
     this.ActiveGroup = ActiveGroup;
     this.Owner       = Owner;
 }
Exemplo n.º 8
0
 public void CltPayment(ClientGroup grp)
 {
     Console.WriteLine("Le client {0} a payé", grp.Id);
 }
Exemplo n.º 9
0
        public async Task <ClientGroup> EditClientGroupAsync(ClientGroup clientGroup)
        {
            var editClientGroup = await _clientGroupRepository.UpdateAsync(clientGroup);

            return(editClientGroup);
        }
Exemplo n.º 10
0
        public RebalanceModel GetRebalanceModel(List <AssetBase> allAssets, Domain.Portfolio.Rebalance.RebalanceModel savedModel, ClientGroup clientGroup = null, Client client = null)
        {
            var weightings       = allAssets.OfType <Equity>().Cast <AssetBase>().ToList().GetAssetWeightings();
            var totalMarketValue = allAssets.GetTotalMarketValue();

            List <TemplateDetailsItemParameter> parameters                 = new List <TemplateDetailsItemParameter>();
            List <DiversificationDatas>         diversificationDatas       = new List <DiversificationDatas>();
            List <RebalanceDataAnalysisModel>   rebalanceDataAnalysisModel = new List <RebalanceDataAnalysisModel>();
            BalanceSheetAgainstModel            balanceSeetAgainsModel     = new BalanceSheetAgainstModel()
            {
                data = new List <BalanceSheetAgainstModelData>()
            };
            RegionalComparisonModel regionalComparisonModel = new RegionalComparisonModel()
            {
                data = new List <RegionalComparisonData>()
            };
            SectorialComparisonModel sectorialComparisonModel = new SectorialComparisonModel()
            {
                data = new List <SectorialComparisonData>()
            };
            MonthlyCashflowComparison monthlyCashflowComparison = new MonthlyCashflowComparison()
            {
                data = new List <MonthlyCashflowComparisonData>()
            };
            List <TransactionCostData> transactionCostData = new List <TransactionCostData>();

            foreach (var parameter in savedModel.TemplateDetailsItemParameters)
            {
                //DiversificationDatas
                string[] metaKeys = parameter.identityMetaKey.Split('#');

                List <Equity> equitiesForGroup = new List <Equity>();
                if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Sectors))
                {
                    equitiesForGroup = edisRepo.GetAllEquitiesBySectorName(metaKeys[1]);
                }
                else if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Countries))
                {
                    equitiesForGroup = edisRepo.GetAllEquitiesByResearchStringValue(metaKeys[1]);
                }

                double currentWeighting = 0;
                if (metaKeys.Length == 2)
                {
                    currentWeighting = getCurrentWeightingForEquityGroup(equitiesForGroup, weightings);

                    //multiple equities
                }
                else
                {
                    currentWeighting = getCurrentWeightingForEquity(parameter.EquityId, weightings);

                    //RebalanceDataAnalysisModel
                    List <Equity> currentEquities = null;
                    if (clientGroup != null)
                    {
                        currentEquities = edisRepo.GetEquityForGroupAccountSync(parameter.EquityId, clientGroup);
                    }
                    else
                    {
                        currentEquities = edisRepo.GetEquityForClientAccountSync(parameter.EquityId, client);
                    }

                    int    numberOfUnit = 0;
                    double value        = 0;
                    double totalCost    = 0;
                    double rating       = 0;

                    foreach (var currentEquity in currentEquities)
                    {
                        numberOfUnit += (int)currentEquity.TotalNumberOfUnits;
                        value        += currentEquity.GetTotalMarketValue();
                        totalCost    += currentEquity.GetCost().Total;

                        switch (currentEquity.EquityType)
                        {
                        case EquityTypes.AustralianEquity:
                            rating += ((AustralianEquity)currentEquity).GetRating().TotalScore;
                            break;

                        case EquityTypes.InternationalEquity:
                            rating += ((InternationalEquity)currentEquity).GetRating().TotalScore;
                            break;
                        }
                    }

                    Equity selectedEquity = edisRepo.getEquityById(parameter.EquityId);

                    double reValue         = currentWeighting * parameter.CurrentWeighting == 0 ? (double)(totalMarketValue * parameter.CurrentWeighting) : (double)(value / currentWeighting * parameter.CurrentWeighting);//(totalMarketValue * parameter.CurrentWeighting) == null ? 0 : (double)(totalMarketValue * parameter.CurrentWeighting);
                    int    reUnit          = reValue == 0 ? 0 : (int)(reValue / selectedEquity.LatestPrice);
                    double reProfitAndLoss = reValue - totalCost;
                    double differences     = (reValue - value) / value;

                    var analysisGroup = rebalanceDataAnalysisModel.SingleOrDefault(a => a.groupName == metaKeys[1]);
                    if (analysisGroup == null)
                    {
                        analysisGroup = new RebalanceDataAnalysisModel {
                            groupName = metaKeys[1],
                            data      = new List <RebalanceDataAnalysisData>(),
                        };
                        rebalanceDataAnalysisModel.Add(analysisGroup);
                    }
                    var index = rebalanceDataAnalysisModel.IndexOf(analysisGroup);
                    rebalanceDataAnalysisModel[index].data.Add(new RebalanceDataAnalysisData {
                        ticker          = selectedEquity.Ticker,
                        name            = selectedEquity.Name,
                        currentPrice    = selectedEquity.LatestPrice,
                        currentExposure = new RebalanceDataAnalysisDataItem {
                            units         = numberOfUnit,
                            value         = value,
                            profitAndLoss = value - totalCost
                        },
                        rebalance = new RebalanceDataAnalysisDataItem {
                            value         = reValue,
                            units         = reUnit,
                            profitAndLoss = reProfitAndLoss
                        },
                        advantageousAndDisadvantageous = new RebalanceDataAnalysisAdvantageDisadvantage {
                            suitability = currentWeighting * rating,
                            differences = differences
                                          //differenceToTarget = ?,
                                          //target = ?
                        }
                    });


                    //BalanceSheetAgainstModel

                    var balanceSheet = balanceSeetAgainsModel.data.SingleOrDefault(a => a.groupName == metaKeys[1]);
                    if (balanceSheet == null)
                    {
                        balanceSheet = new BalanceSheetAgainstModelData {
                            groupName = metaKeys[1],
                            items     = new List <BalanceSheetAgainstModelItem>()
                        };
                        balanceSeetAgainsModel.data.Add(balanceSheet);
                    }
                    var balanSheetIndex = balanceSeetAgainsModel.data.IndexOf(balanceSheet);
                    balanceSeetAgainsModel.data[balanSheetIndex].items.Add(new BalanceSheetAgainstModelItem {
                        current           = value,
                        currentWeighting  = currentWeighting,
                        proposed          = reValue,
                        proposedWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                        difference        = differences,
                        itemName          = selectedEquity.Name
                    });


                    if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Countries))
                    {
                        //RegionalComparisonModel
                        var regionModel = regionalComparisonModel.data.SingleOrDefault(a => a.groupName == metaKeys[1]);
                        if (regionModel == null)
                        {
                            regionModel = new RegionalComparisonData {
                                groupName = metaKeys[1],
                                items     = new List <RegionalComparisonItem>()
                            };
                            regionalComparisonModel.data.Add(regionModel);
                        }

                        var regionModelIndex = regionalComparisonModel.data.IndexOf(regionModel);
                        regionalComparisonModel.data[regionModelIndex].items.Add(new RegionalComparisonItem {
                            current           = value,
                            currentWeighting  = currentWeighting,
                            proposed          = reValue,
                            proposedWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                            difference        = differences,
                            itemName          = selectedEquity.Name
                        });
                    }
                    else if (metaKeys[0] == edisRepo.GetEnumDescription(RebalanceClassificationType.Sectors))
                    {
                        //SectoralComparisonModel
                        var sectorModel = sectorialComparisonModel.data.SingleOrDefault(a => a.groupName == metaKeys[1]);
                        if (sectorModel == null)
                        {
                            sectorModel = new SectorialComparisonData {
                                groupName = metaKeys[1],
                                items     = new List <SectorialComparisonItem>()
                            };
                            sectorialComparisonModel.data.Add(sectorModel);
                        }

                        var sectorModelIndex = sectorialComparisonModel.data.IndexOf(sectorModel);
                        sectorialComparisonModel.data[sectorModelIndex].items.Add(new SectorialComparisonItem {
                            current           = value,
                            currentWeighting  = currentWeighting,
                            proposed          = reValue,
                            proposedWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                            difference        = differences,
                            itemName          = selectedEquity.Name
                        });
                    }


                    //TransactionCostData
                    var transactionData = transactionCostData.SingleOrDefault(t => t.assetClass == metaKeys[1]);
                    if (transactionData == null)
                    {
                        transactionData = new TransactionCostData {
                            assetClass = metaKeys[1],
                            items      = new List <TransactionCostDataItem>()
                        };
                        transactionCostData.Add(transactionData);
                    }
                    var transactionIndex = transactionCostData.IndexOf(transactionData);
                    transactionCostData[transactionIndex].items.Add(new TransactionCostDataItem {
                        buySell    = reValue - value,
                        name       = selectedEquity.Name,
                        profitLoss = reProfitAndLoss,
                        //transactionCost = ?,
                        netValue = reValue - value //- transactionCost
                    });
                }

                var sameGroup = diversificationDatas.FirstOrDefault(d => d.group == metaKeys[1]);
                if (sameGroup != null)
                {
                    sameGroup.modelWeighting     += parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting;
                    sameGroup.portfolioWeighting += currentWeighting;
                }
                else
                {
                    diversificationDatas.Add(new DiversificationDatas {
                        group              = metaKeys[1],
                        modelWeighting     = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                        portfolioWeighting = currentWeighting
                    });
                }


                //TemplateDetailsItemParameter
                parameters.Add(new TemplateDetailsItemParameter {
                    id               = parameter.EquityId,
                    itemName         = parameter.ItemName,
                    identityMetaKey  = parameter.identityMetaKey,
                    currentWeighting = parameter.CurrentWeighting == null ? 0 : (double)parameter.CurrentWeighting,
                });
            }


            for (int i = 0; i < balanceSeetAgainsModel.data.Count; i++)
            {
                for (int j = 0; j < balanceSeetAgainsModel.data[i].items.Count; j++)
                {
                    balanceSeetAgainsModel.data[i].current           += balanceSeetAgainsModel.data[i].items[j].current;
                    balanceSeetAgainsModel.data[i].currentWeighting  += balanceSeetAgainsModel.data[i].items[j].currentWeighting;
                    balanceSeetAgainsModel.data[i].proposed          += balanceSeetAgainsModel.data[i].items[j].proposed;
                    balanceSeetAgainsModel.data[i].proposedWeighting += balanceSeetAgainsModel.data[i].items[j].proposedWeighting;
                }
                balanceSeetAgainsModel.data[i].difference = (balanceSeetAgainsModel.data[i].proposed - balanceSeetAgainsModel.data[i].current) / balanceSeetAgainsModel.data[i].current;

                balanceSeetAgainsModel.current           += balanceSeetAgainsModel.data[i].current;
                balanceSeetAgainsModel.currentWeighting  += balanceSeetAgainsModel.data[i].currentWeighting;
                balanceSeetAgainsModel.proposed          += balanceSeetAgainsModel.data[i].proposed;
                balanceSeetAgainsModel.proposedWeighting += balanceSeetAgainsModel.data[i].proposedWeighting;
            }
            balanceSeetAgainsModel.difference = (balanceSeetAgainsModel.proposed - balanceSeetAgainsModel.current) / balanceSeetAgainsModel.current;


            for (int i = 0; i < regionalComparisonModel.data.Count; i++)
            {
                for (int j = 0; j < regionalComparisonModel.data[i].items.Count; j++)
                {
                    regionalComparisonModel.data[i].current           += regionalComparisonModel.data[i].items[j].current;
                    regionalComparisonModel.data[i].currentWeighting  += regionalComparisonModel.data[i].items[j].currentWeighting;
                    regionalComparisonModel.data[i].proposed          += regionalComparisonModel.data[i].items[j].proposed;
                    regionalComparisonModel.data[i].proposedWeighting += regionalComparisonModel.data[i].items[j].proposedWeighting;
                }

                regionalComparisonModel.data[i].difference = (regionalComparisonModel.data[i].proposed - regionalComparisonModel.data[i].current) / regionalComparisonModel.data[i].current;

                regionalComparisonModel.current           += regionalComparisonModel.data[i].current;
                regionalComparisonModel.currentWeighting  += regionalComparisonModel.data[i].currentWeighting;
                regionalComparisonModel.proposed          += regionalComparisonModel.data[i].proposed;
                regionalComparisonModel.proposedWeighting += regionalComparisonModel.data[i].proposedWeighting;
            }


            for (int i = 0; i < sectorialComparisonModel.data.Count; i++)
            {
                for (int j = 0; j < sectorialComparisonModel.data[i].items.Count; j++)
                {
                    sectorialComparisonModel.data[i].current           += sectorialComparisonModel.data[i].items[j].current;
                    sectorialComparisonModel.data[i].currentWeighting  += sectorialComparisonModel.data[i].items[j].currentWeighting;
                    sectorialComparisonModel.data[i].proposed          += sectorialComparisonModel.data[i].items[j].proposed;
                    sectorialComparisonModel.data[i].proposedWeighting += sectorialComparisonModel.data[i].items[j].proposedWeighting;
                }

                sectorialComparisonModel.data[i].difference = (sectorialComparisonModel.data[i].proposed - sectorialComparisonModel.data[i].current) / sectorialComparisonModel.data[i].current;

                sectorialComparisonModel.current           += sectorialComparisonModel.data[i].current;
                sectorialComparisonModel.currentWeighting  += sectorialComparisonModel.data[i].currentWeighting;
                sectorialComparisonModel.proposed          += sectorialComparisonModel.data[i].proposed;
                sectorialComparisonModel.proposedWeighting += sectorialComparisonModel.data[i].proposedWeighting;
            }

            for (int i = 0; i < transactionCostData.Count; i++)
            {
                for (int j = 0; j < transactionCostData[i].items.Count; j++)
                {
                    transactionCostData[i].buySell         += transactionCostData[i].items[j].buySell;
                    transactionCostData[i].profitLoss      += transactionCostData[i].items[j].profitLoss;
                    transactionCostData[i].transactionCost += transactionCostData[i].items[j].transactionCost;
                    transactionCostData[i].netValue        += transactionCostData[i].items[j].netValue;
                    transactionCostData[i].extraDividend   += transactionCostData[i].items[j].extraDividend;
                    transactionCostData[i].extraMER        += transactionCostData[i].items[j].extraMER;
                }
                //transactionCostData[i].netValue += (transactionCostData[i].buySell + transactionCostData[i].transactionCost);
            }


            return(new RebalanceModel {
                modelId = savedModel.ModelId,
                profile = new ModelProfile {
                    profileId = savedModel.ProfileId.ToString(), profileName = edisRepo.GetEnumDescription((RebalanceModelProfile)savedModel.ProfileId)
                },
                modelName = savedModel.ModelName,
                itemParameters = parameters,
                diversificationData = diversificationDatas,
                rebalancedDataAnalysis = rebalanceDataAnalysisModel,
                balanceSheet = balanceSeetAgainsModel,
                sectorialData = sectorialComparisonModel,
                regionalData = regionalComparisonModel,
                transactionCost = transactionCostData
            });
        }
        /// <summary>
        /// Add Update Data
        /// </summary>
        /// <param name="model"></param>
        /// <returns>Jsonresponse</returns>
        public JsonResponse AddUpdate(ClientGroup model)
        {
            JsonResponse resp = new JsonResponse();

            try
            {
                if (model.Id == 0)
                {
                    if (!IsExsits(model.GroupName))
                    {
                        model.IsActive  = true;
                        model.CreatedOn = DateTime.Now;
                        model.CreatedBy = GetUserID();
                        _context.Set <ClientGroup>().Add(model);
                        int i = _context.SaveChanges();

                        if (i != 0)
                        {
                            resp.Status  = Constants.ResponseStatus.Success;
                            resp.Message = Constants.Service.Data_insert_success;
                        }
                        else
                        {
                            resp.Message = Constants.Service.Data_insert_failed;
                        }
                    }
                    else
                    {
                        resp.Message = Constants.ControllerMessage.Data_Exsists;
                    }
                }
                else
                {
                    resp.Message = Constants.Service.Data_Update_failed;
                    var models = GetData(model.Id);
                    if (models != null)
                    {
                        models.GroupName    = model.GroupName;
                        models.AddressLine1 = model.AddressLine1;
                        models.AddressLine2 = model.AddressLine2;
                        models.CountryID    = model.CountryID;
                        models.StateID      = model.StateID;
                        models.CityID       = model.CityID;
                        models.IsActive     = true;
                        models.ModifiedOn   = DateTime.Now;
                        models.ModifiedBy   = GetUserID();
                        _context.Set <ClientGroup>().Update(models);
                        int i = _context.SaveChanges();
                        if (i != 0)
                        {
                            resp.Status  = Constants.ResponseStatus.Success;
                            resp.Message = Constants.Service.Data_Update_success;
                        }
                    }
                }
            }
            catch (Exception)
            {
                resp.Message = Constants.Service.Common_message;
            }

            return(resp);
        }
Exemplo n.º 12
0
        private void CreateNewClient(Background.SyncRonService.Model.Contragent.Client client)
        {
            var userInfos = _context.Set <UserInfo>()
                            .Where(x => x.UserId != 1 && x.UserId != 11)
                            .ToList();

            if (client != null)
            {
                NumberOfCalls numberOfCalls = client.Periodichnost_Zvonkov == "0" ? NumberOfCalls.WithoutType : client.Periodichnost_Zvonkov == "10" ? NumberOfCalls.OnePerMonth : client.Periodichnost_Zvonkov == "20"
                            ? NumberOfCalls.OnePerTwoWeek : client.Periodichnost_Zvonkov == "30" ? NumberOfCalls.ThreePerMonth : client.Periodichnost_Zvonkov == "40" ? NumberOfCalls.OnePerWeek : client.Periodichnost_Zvonkov == "50" ?
                                              NumberOfCalls.FivePerMonth : client.Periodichnost_Zvonkov == "60" ? NumberOfCalls.SixPerMonth : client.Periodichnost_Zvonkov == "90" ? NumberOfCalls.TwoPerWeek : NumberOfCalls.WithoutType;

                NumberOfShipments numberOfShipments = client.Periodichnost_Otgruzok == "0" ? NumberOfShipments.WithoutType : client.Periodichnost_Zvonkov == "10" ? NumberOfShipments.OnePerMonth : client.Periodichnost_Zvonkov == "20"
                   ? NumberOfShipments.OnePerTwoWeek : client.Periodichnost_Zvonkov == "30" ? NumberOfShipments.ThreePerMonth : client.Periodichnost_Zvonkov == "40" ? NumberOfShipments.OnePerWeek : client.Periodichnost_Zvonkov == "50" ?
                                                      NumberOfShipments.FivePerMonth : client.Periodichnost_Zvonkov == "60" ? NumberOfShipments.SixPerMonth : client.Periodichnost_Zvonkov == "90" ? NumberOfShipments.TwoPerWeek : NumberOfShipments.WithoutType;
                ClientGroup clientGroup = ClientGroup.NewOrReanimated;

                if (this.client1 != null)
                {
                    numberOfCalls     = this.client1.NumberOfCalls;
                    numberOfShipments = this.client1.NumberOfShipments;
                    clientGroup       = this.client1.Group;
                }

                Data.Entities.Clients.Client client1 = _context.Set <Client>()
                                                       .Add(new Client(new ClientCreate()
                {
                    ClientType        = ClientTypes.Middle1,
                    Title             = client.Contragent,
                    LegalEntity       = client.Contragent_NameFull,
                    NumberOfCalls     = numberOfCalls,
                    NumberOfShipments = numberOfShipments,
                    Group             = clientGroup
                })).Entity;
                client1.IsAcctive = true;
                _context.Set <Client>().Add(client1);
                _context.SaveChanges();
                ClientInfo clientInfo = _context.Set <ClientInfo>()
                                        .Add(new ClientInfo(client1.Id, Guid.Parse(client.Contragent_ID), client.Phones)).Entity;
                _context.SaveChanges();
                if (client.GR_Contragent != "" && _context.Set <ClientGR>().FirstOrDefault(c => c.NameGr == client.GR_Contragent) == null)
                {
                    _context.Set <ClientGR>().Add(new ClientGR()
                    {
                        Clients = new List <Data.Entities.Clients.Client>()
                        {
                            client1
                        },
                        NameGr = client.GR_Contragent
                    });
                }
                else if (client.GR_Contragent != "")
                {
                    _context.Set <ClientGR>().FirstOrDefault(c => c.NameGr == client.GR_Contragent).Clients.Add(client1);
                }
                _context.SaveChanges();
                if (client.Manager_ID != null && client.Manager_ID != "")
                {
                    var managersGuidStr = client.Manager_ID.Split(',');
                    var managersGuid    = new List <Guid>();
                    foreach (var str in managersGuidStr)
                    {
                        try
                        {
                            managersGuid.Add(Guid.Parse(str));
                        }
                        catch
                        {
                        }
                    }
                    foreach (Guid guid in managersGuid)
                    {
                        var userInfo = userInfos.FirstOrDefault(x => x.OneCId == guid);
                        if (userInfo != null)
                        {
                            var workGroup = _context.Set <WorkGroup>()
                                            .FirstOrDefault(x => x.RegionalManagerId == userInfo.UserId ||
                                                            x.EscortManagerId == userInfo.UserId);
                            if (workGroup != null && workGroup.Clients.FirstOrDefault(c => c.ClientId == clientInfo.ClientId) == null)
                            {
                                workGroup.BindClient(new BindClient()
                                {
                                    ClientId    = client1.Id,
                                    WorkgroupId = workGroup.Id
                                });
                            }
                        }
                    }
                }
                _context.SaveChanges();
                if (client.Phones != null && client.Phones != "")
                {
                    var e            = client.Phones.Split(',');
                    var clientPhones = _context.Set <ClientPhone>().Where(c => c.ClientId == clientInfo.ClientId);
                    foreach (var phone in e)
                    {
                        string newPhone = Regex.Replace(phone, @"[^0-9]", "");
                        if (clientPhones == null || clientPhones.FirstOrDefault(c => c.Phone != null && (c.Phone == newPhone || c.Phone == newPhone.Substring(1) || c.Phone == newPhone.Substring(2))) == null)
                        {
                            ClientPhone clientPhone = new ClientPhone()
                            {
                                Client = client1,
                                Phone  = newPhone,
                            };
                            //if (newPhone.Length == 10)
                            //{
                            //}
                            //else if (newPhone.Length == 11)
                            //{
                            //    newPhone = newPhone.Substring(1);
                            //    clientPhone = new ClientPhone()
                            //    {
                            //        Client = client1,
                            //        Phone = newPhone,
                            //    };
                            //}
                            //else if (newPhone.Length == 12)
                            //{
                            //    newPhone = newPhone.Substring(2);
                            //    clientPhone = new ClientPhone()
                            //    {
                            //        Client = client1,
                            //        Phone = newPhone,
                            //    };
                            //}
                            _context.Set <ClientPhone>().Add(clientPhone);
                            _context.SaveChanges();
                        }
                    }
                }
            }
        }
Exemplo n.º 13
0
 public void CreateClientGroup(ClientGroup ClientGroup)
 {
     ClientGroupsRepository.Add(ClientGroup);
 }
        protected override void OnJoinRoomLocal(IOnlineConnection Sender, string RoomID, ClientGroup ActiveGroup)
        {
            foreach (IOnlineConnection ActivePlayer in ActiveGroup.Room.ListOnlinePlayer)
            {
                if (ActivePlayer == Sender)
                {
                    continue;
                }

                ActivePlayer.Send(new PlayerJoinedScriptServer(ActiveGroup.Room.GetPlayer(Sender)));
            }

            Sender.Send(new JoinRoomLocalScriptServer(RoomID, ActiveGroup.CurrentGame));
        }
Exemplo n.º 15
0
        public async Task PushNotifyApproveReport(string userId, NotificationDetail notificationDetail)
        {
            try
            {
                FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", userId);

                ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

                User currentUser = Feature.CurrentUser(httpContextAccessor, userRepository);

                foreach (string id in clientGroup.UserIds)
                {
                    NotificationDetail finalNotificationDetail = new NotificationDetail()
                    {
                        CreatorId            = notificationDetail.CreatorId,
                        ReceiverId           = userId,
                        NotificationObjectId = notificationDetail.NotificationObjectId
                    };
                    await notificationDetailRepository.AddAsync(finalNotificationDetail);

                    NotificationObject notificationObject =
                        await notificationObjectRepository.GetByIdAsync(
                            ObjectId.Parse(finalNotificationDetail.NotificationObjectId));

                    FilterDefinition <NotificationType> notificationTypeFilter =
                        Builders <NotificationType> .Filter.Eq("code", notificationObject.NotificationType);

                    NotificationType notificationType =
                        await notificationTypeRepository.FindAsync(notificationTypeFilter);

                    User creator = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotificationDetail.CreatorId));

                    PushedNotificationViewModel notificationToPush = new PushedNotificationViewModel()
                    {
                        AuthorName   = $"{creator.FirstName} {creator.LastName}",
                        AuthorAvatar = creator.AvatarHash,
                        AuthorId     = creator.OId,
                        Content      = $"{notificationType.ContentTemplate}.",
                        CreatedDate  = DateTime.Now,
                        IsRead       = false,
                        ModifiedDate = DateTime.Now,
                        ObjectId     = notificationObject.ObjectId,
                        OId          = notificationObject.OId,
                        OwnerId      = userId,
                        Status       = ItemStatus.Active
                    };
                    //Push notification
                    try
                    {
                        FilterDefinition <FcmInfo> userFilter = Builders <FcmInfo> .Filter.Eq("user_id", userId);

                        string token = (await fcmInfoRepository.FindAsync(userFilter)).DeviceToken;

                        FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                        {
                            Token = token,
                            Data  = new Dictionary <string, string>()
                            {
                                { "notification", JsonConvert.SerializeObject(notificationToPush) }
                            },
                            Notification = new Notification()
                            {
                                Title    = creator.LastName,
                                Body     = notificationToPush.Content,
                                ImageUrl = creator.AvatarHash
                            }
                        };
                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                    }
                    catch (Exception)
                    {
                        // do nothing
                    }
                }
            }
            catch (Exception)
            {
                //Do nothing
            }
        }
Exemplo n.º 16
0
        public async Task PushNotifyDetail(string clientGroupName, NotificationDetail notificationDetail)
        {
            FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

            ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

            User currentUser = Feature.CurrentUser(httpContextAccessor, userRepository);

            foreach (string receiverId in clientGroup.UserIds)
            {
                var existNotificationDetailBuilder = Builders <NotificationDetail> .Filter;
                var existNotificationDetailFilter  =
                    existNotificationDetailBuilder.Eq("creator_id", notificationDetail.CreatorId)
                    & existNotificationDetailBuilder.Eq("receiver_id", receiverId)
                    & existNotificationDetailBuilder.Eq("notification_object_id",
                                                        notificationDetail.NotificationObjectId);

                var existNotificationDetail =
                    await notificationDetailRepository.FindAsync(existNotificationDetailFilter);

                var finalNotificationDetail = new NotificationDetail();

                if (existNotificationDetail != null)
                {
                    finalNotificationDetail = existNotificationDetail;
                    finalNotificationDetail.ModifiedDate = DateTime.Now;
                    finalNotificationDetail.IsDeleted    = false;
                    await notificationDetailRepository.UpdateAsync(finalNotificationDetail, finalNotificationDetail.Id);
                }
                else
                {
                    finalNotificationDetail.CreatorId            = notificationDetail.CreatorId;
                    finalNotificationDetail.ReceiverId           = receiverId;
                    finalNotificationDetail.NotificationObjectId = notificationDetail.NotificationObjectId;
                    await notificationDetailRepository.AddAsync(finalNotificationDetail);
                }

                ;

                var notificationObject =
                    await notificationObjectRepository.GetByIdAsync(
                        ObjectId.Parse(finalNotificationDetail.NotificationObjectId));

                var owner = await userRepository.GetByIdAsync(ObjectId.Parse(notificationObject.OwnerId));

                var receiver = await userRepository.GetByIdAsync(ObjectId.Parse(receiverId));

                var creator = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotificationDetail.CreatorId));

                var notificationTypeFilter =
                    Builders <NotificationType> .Filter.Eq("code", notificationObject.NotificationType);

                var notificationType = await notificationTypeRepository.FindAsync(notificationTypeFilter);

                string notifyContent = string.Empty;

                if (owner.OId == creator.OId)
                {
                    if (receiver.OId == owner.OId)
                    {
                        notifyContent = $"Bạn {notificationType.ContentTemplate} chính mình";
                    }
                    else if (receiver.OId != owner.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} họ";
                    }
                }
                else if (owner.OId != creator.OId)
                {
                    if (receiver.OId != owner.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} {owner.LastName}";
                    }
                    else if (receiver.OId != creator.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} bạn";
                    }
                }


                var notificationToPush = new PushedNotificationViewModel()
                {
                    AuthorName   = $"{creator.FirstName} {creator.LastName}",
                    AuthorAvatar = creator.AvatarHash,
                    AuthorId     = creator.OId,
                    Content      = notifyContent,
                    CreatedDate  = DateTime.Now,
                    IsRead       = false,
                    ModifiedDate = DateTime.Now,
                    ObjectId     = notificationObject.ObjectId,
                    OId          = notificationObject.OId,
                    OwnerId      = owner.OId,
                    Status       = ItemStatus.Active
                };

                switch (notificationType.Code)
                {
                case "ADD_POST_NOTIFY":
                case "UPVOTE_POST_NOTIFY":
                case "DOWNVOTE_POST_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Post;
                    break;

                case "UPVOTE_COMMENT_NOTIFY":
                case "DOWNVOTE_COMMENT_NOTIFY":
                case "COMMENT_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Comment;
                    break;

                case "UPVOTE_REPLY_NOTIFY":
                case "DOWNVOTE_REPLY_NOTIFY":
                case "REPLY_COMMENT_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Reply;
                    break;

                case "FOLLOW_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.User;
                    break;

                default:
                    notificationToPush.NotificationType = PushedNotificationType.Other;
                    break;
                }

                try
                {
                    if (!(owner.OId == creator.OId && receiver.OId == owner.OId))
                    {
                        var userFilter = Builders <FcmInfo> .Filter.Eq("user_id", receiverId);

                        string token = (await fcmInfoRepository.FindAsync(userFilter)).DeviceToken;

                        FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                        {
                            Token = token,
                            Data  = new Dictionary <string, string>()
                            {
                                { "notification", JsonConvert.SerializeObject(notificationToPush) }
                            },
                            Notification = new Notification()
                            {
                                Title    = creator.LastName,
                                Body     = notifyContent,
                                ImageUrl = creator.AvatarHash
                            }
                        };
                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                    }
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
        }
Exemplo n.º 17
0
 public SendSquareScriptServer(ClientGroup ActiveGroup, PlayerWithID Owner)
     : base(ScriptName)
 {
     this.ActiveGroup = ActiveGroup;
     this.Owner       = Owner;
 }
Exemplo n.º 18
0
        protected override void OnJoinRoomLocal(IOnlineConnection Sender, string RoomID, ClientGroup ActiveGroup)
        {
            RoomInformations JoinedRoom            = (RoomInformations)ActiveGroup.Room;
            List <Player>    ListJoiningPlayerInfo = JoinedRoom.GetOnlinePlayer(Sender);

            foreach (IOnlineConnection ActivePlayer in ActiveGroup.Room.ListOnlinePlayer)
            {
                if (ActivePlayer == Sender)
                {
                    continue;
                }

                ActivePlayer.Send(new PlayerJoinedScriptServer(ListJoiningPlayerInfo));
            }

            Dictionary <string, OnlineScript> DicNewScript = new Dictionary <string, OnlineScript>();

            DicNewScript.Add(AskChangeCharacterScriptServer.ScriptName, new AskChangeCharacterScriptServer(JoinedRoom));
            DicNewScript.Add(AskChangePlayerTypeScriptServer.ScriptName, new AskChangePlayerTypeScriptServer(JoinedRoom));
            DicNewScript.Add(AskChangeTeamScriptServer.ScriptName, new AskChangeTeamScriptServer(JoinedRoom));
            DicNewScript.Add(AskChangeMapScriptServer.ScriptName, new AskChangeMapScriptServer(JoinedRoom, Owner));
            DicNewScript.Add(AskChangeRoomSubtypeScriptServer.ScriptName, new AskChangeRoomSubtypeScriptServer(JoinedRoom));
            DicNewScript.Add(LeaveRoomScriptServer.ScriptName, new LeaveRoomScriptServer(JoinedRoom, Owner));
            if (JoinedRoom.RoomType == RoomInformations.RoomTypeMission)
            {
                MissionRoomInformations MissionRoom = (MissionRoomInformations)JoinedRoom;

                DicNewScript.Add(AskStartGameMissionScriptServer.ScriptName, new AskStartGameMissionScriptServer(MissionRoom, (TripleThunderClientGroup)ActiveGroup, Owner));
                DicNewScript.Add(AskChangeRoomExtrasMissionScriptServer.ScriptName, new AskChangeRoomExtrasMissionScriptServer(MissionRoom));
            }
            else if (JoinedRoom.RoomType == RoomInformations.RoomTypeBattle)
            {
                BattleRoomInformations BattleRoom = (BattleRoomInformations)JoinedRoom;

                DicNewScript.Add(AskStartGameMissionScriptServer.ScriptName, new AskStartGameBattleScriptServer(BattleRoom, (TripleThunderClientGroup)ActiveGroup, Owner));
                DicNewScript.Add(AskChangeRoomExtrasBattleScriptServer.ScriptName, new AskChangeRoomExtrasBattleScriptServer(BattleRoom));
            }
            Sender.AddOrReplaceScripts(DicNewScript);

            if (ActiveGroup.CurrentGame != null)
            {
                FightingZone CurrentGame = (FightingZone)ActiveGroup.CurrentGame;

                foreach (Player ActivePlayer in ListJoiningPlayerInfo)
                {
                    CurrentGame.AddLocalCharacter(ActivePlayer);
                    ActivePlayer.OnlineClient = Sender;

                    int LayerIndex;
                    CurrentGame.AddPlayerFromSpawn(ActivePlayer, CurrentGame.NextID + (uint.MaxValue - 100), true, out LayerIndex);

                    //Add Game Specific scripts
                    DicNewScript = new Dictionary <string, OnlineScript>();
                    DicNewScript.Add(FinishedLoadingScriptServer.ScriptName, new FinishedLoadingScriptServer(ActiveGroup));
                    DicNewScript.Add(SendPlayerUpdateScriptServer.ScriptName, new SendPlayerUpdateScriptServer((TripleThunderClientGroup)ActiveGroup, ActivePlayer));
                    DicNewScript.Add(ShootBulletScriptServer.ScriptName, new ShootBulletScriptServer((TripleThunderClientGroup)ActiveGroup, ActivePlayer));
                    DicNewScript.Add(AskTripleThunderGameDataScriptServer.ScriptName, new AskTripleThunderGameDataScriptServer((TripleThunderClientGroup)ActiveGroup));
                    Sender.AddOrReplaceScripts(DicNewScript);

                    foreach (IOnlineConnection OtherPlayer in ActiveGroup.Room.ListOnlinePlayer)
                    {
                        if (OtherPlayer == Sender)
                        {
                            continue;
                        }

                        OtherPlayer.Send(new CreatePlayerScriptServer(ActivePlayer, LayerIndex, false));
                    }
                }
            }

            Sender.Send(new JoinRoomLocalScriptServer(RoomID, JoinedRoom.CurrentDifficulty, ListJoiningPlayerInfo, ActiveGroup));
        }
Exemplo n.º 19
0
 /// <summary>
 /// Check the reservation of a group of clients
 /// </summary>
 /// <param name="groupClient"></param>
 public void CheckReservation(ClientGroup groupClient)
 {
 }
        public CashflowBriefModel GetCashflow_Client()
        {
            Client      client      = edisRepo.GetClientSync(User.Identity.GetUserId(), DateTime.Now);
            ClientGroup clientGroup = edisRepo.GetClientGroupSync(client.ClientGroupId, DateTime.Now);

            if (clientGroup.MainClientId == client.Id)
            {
                List <GroupAccount>  groupAccounts  = edisRepo.GetAccountsForClientGroupSync(clientGroup.ClientGroupNumber, DateTime.Now);
                List <ClientAccount> clientAccounts = edisRepo.GetAccountsForClientSync(client.ClientNumber, DateTime.Now);


                double totalExpenseInAssets = 0;
                double totalIncomeInAssets  = 0;

                List <CashFlowBriefItem> items = new List <CashFlowBriefItem>();

                CashFlowBriefItem jan = new CashFlowBriefItem {
                    month = "Jan"
                };
                CashFlowBriefItem feb = new CashFlowBriefItem {
                    month = "Feb"
                };
                CashFlowBriefItem mar = new CashFlowBriefItem {
                    month = "Mar"
                };
                CashFlowBriefItem apr = new CashFlowBriefItem {
                    month = "Apr"
                };
                CashFlowBriefItem may = new CashFlowBriefItem {
                    month = "May"
                };
                CashFlowBriefItem jun = new CashFlowBriefItem {
                    month = "Jun"
                };
                CashFlowBriefItem jul = new CashFlowBriefItem {
                    month = "Jul"
                };
                CashFlowBriefItem aug = new CashFlowBriefItem {
                    month = "Aug"
                };
                CashFlowBriefItem sep = new CashFlowBriefItem {
                    month = "Sep"
                };
                CashFlowBriefItem oct = new CashFlowBriefItem {
                    month = "Oct"
                };
                CashFlowBriefItem nov = new CashFlowBriefItem {
                    month = "Nov"
                };
                CashFlowBriefItem dec = new CashFlowBriefItem {
                    month = "Dec"
                };


                foreach (var account in groupAccounts)
                {
                    List <Cashflow> cashFlows = account.GetLiabilitiesSync().OfType <Insurance>().Cast <LiabilityBase>().ToList().GetMonthlyCashflows();

                    foreach (var cashflow in cashFlows)
                    {
                        switch (cashflow.Month)
                        {
                        case "Jan": jan.date = DateTime.Now; jan.expense += cashflow.Expenses; jan.income += cashflow.Income; break;

                        case "Feb": feb.date = DateTime.Now; feb.expense += cashflow.Expenses; feb.income += cashflow.Income; break;

                        case "Mar": mar.date = DateTime.Now; mar.expense += cashflow.Expenses; mar.income += cashflow.Income; break;

                        case "Apr": apr.date = DateTime.Now; apr.expense += cashflow.Expenses; apr.income += cashflow.Income; break;

                        case "May": may.date = DateTime.Now; may.expense += cashflow.Expenses; may.income += cashflow.Income; break;

                        case "Jun": jun.date = DateTime.Now; jun.expense += cashflow.Expenses; jun.income += cashflow.Income; break;

                        case "Jul": jul.date = DateTime.Now; jul.expense += cashflow.Expenses; jul.income += cashflow.Income; break;

                        case "Aug": aug.date = DateTime.Now; aug.expense += cashflow.Expenses; aug.income += cashflow.Income; break;

                        case "Sep": sep.date = DateTime.Now; sep.expense += cashflow.Expenses; sep.income += cashflow.Income; break;

                        case "Oct": oct.date = DateTime.Now; oct.expense += cashflow.Expenses; oct.income += cashflow.Income; break;

                        case "Nov": nov.date = DateTime.Now; nov.expense += cashflow.Expenses; nov.income += cashflow.Income; break;

                        case "Dec": dec.date = DateTime.Now; dec.expense += cashflow.Expenses; dec.income += cashflow.Income; break;

                        default: break;
                        }
                        totalExpenseInAssets += cashflow.Expenses;
                        totalIncomeInAssets  += cashflow.Income;
                    }
                }
                foreach (var account in clientAccounts)
                {
                    List <Cashflow> cashFlows = account.GetLiabilitiesSync().OfType <Insurance>().Cast <LiabilityBase>().ToList().GetMonthlyCashflows();

                    foreach (var cashflow in cashFlows)
                    {
                        switch (cashflow.Month)
                        {
                        case "Jan": jan.date = DateTime.Now; jan.expense += cashflow.Expenses; jan.income += cashflow.Income; break;

                        case "Feb": feb.date = DateTime.Now; feb.expense += cashflow.Expenses; feb.income += cashflow.Income; break;

                        case "Mar": mar.date = DateTime.Now; mar.expense += cashflow.Expenses; mar.income += cashflow.Income; break;

                        case "Apr": apr.date = DateTime.Now; apr.expense += cashflow.Expenses; apr.income += cashflow.Income; break;

                        case "May": may.date = DateTime.Now; may.expense += cashflow.Expenses; may.income += cashflow.Income; break;

                        case "Jun": jun.date = DateTime.Now; jun.expense += cashflow.Expenses; jun.income += cashflow.Income; break;

                        case "Jul": jul.date = DateTime.Now; jul.expense += cashflow.Expenses; jul.income += cashflow.Income; break;

                        case "Aug": aug.date = DateTime.Now; aug.expense += cashflow.Expenses; aug.income += cashflow.Income; break;

                        case "Sep": sep.date = DateTime.Now; sep.expense += cashflow.Expenses; sep.income += cashflow.Income; break;

                        case "Oct": oct.date = DateTime.Now; oct.expense += cashflow.Expenses; oct.income += cashflow.Income; break;

                        case "Nov": nov.date = DateTime.Now; nov.expense += cashflow.Expenses; nov.income += cashflow.Income; break;

                        case "Dec": dec.date = DateTime.Now; dec.expense += cashflow.Expenses; dec.income += cashflow.Income; break;

                        default: break;
                        }
                        totalExpenseInAssets += cashflow.Expenses;
                        totalIncomeInAssets  += cashflow.Income;
                    }
                }


                items.Add(jan);
                items.Add(feb);
                items.Add(mar);
                items.Add(apr);
                items.Add(may);
                items.Add(jun);
                items.Add(jul);
                items.Add(aug);
                items.Add(sep);
                items.Add(oct);
                items.Add(nov);
                items.Add(dec);


                CashflowBriefModel model = new CashflowBriefModel
                {
                    totalExpense = totalExpenseInAssets,
                    totalIncome  = totalIncomeInAssets,
                    data         = items
                };
                return(model);
            }
            else
            {
                List <ClientAccount> accounts = edisRepo.GetAccountsForClientSync(client.ClientNumber, DateTime.Now);
                double totalExpenseInAssets   = 0;
                double totalIncomeInAssets    = 0;

                List <CashFlowBriefItem> items = new List <CashFlowBriefItem>();

                CashFlowBriefItem jan = new CashFlowBriefItem {
                    month = "Jan"
                };
                CashFlowBriefItem feb = new CashFlowBriefItem {
                    month = "Feb"
                };
                CashFlowBriefItem mar = new CashFlowBriefItem {
                    month = "Mar"
                };
                CashFlowBriefItem apr = new CashFlowBriefItem {
                    month = "Apr"
                };
                CashFlowBriefItem may = new CashFlowBriefItem {
                    month = "May"
                };
                CashFlowBriefItem jun = new CashFlowBriefItem {
                    month = "Jun"
                };
                CashFlowBriefItem jul = new CashFlowBriefItem {
                    month = "Jul"
                };
                CashFlowBriefItem aug = new CashFlowBriefItem {
                    month = "Aug"
                };
                CashFlowBriefItem sep = new CashFlowBriefItem {
                    month = "Sep"
                };
                CashFlowBriefItem oct = new CashFlowBriefItem {
                    month = "Oct"
                };
                CashFlowBriefItem nov = new CashFlowBriefItem {
                    month = "Nov"
                };
                CashFlowBriefItem dec = new CashFlowBriefItem {
                    month = "Dec"
                };

                foreach (var account in accounts)
                {
                    //List<Cashflow> cashFlows = account.GetAssetsSync().GetMonthlyCashflows();

                    List <Cashflow> cashFlows = account.GetLiabilitiesSync().OfType <Insurance>().Cast <LiabilityBase>().ToList().GetMonthlyCashflows();

                    foreach (var cashflow in cashFlows)
                    {
                        switch (cashflow.Month)
                        {
                        case "Jan": jan.date = DateTime.Now; jan.expense += cashflow.Expenses; jan.income += cashflow.Income; break;

                        case "Feb": feb.date = DateTime.Now; feb.expense += cashflow.Expenses; feb.income += cashflow.Income; break;

                        case "Mar": mar.date = DateTime.Now; mar.expense += cashflow.Expenses; mar.income += cashflow.Income; break;

                        case "Apr": apr.date = DateTime.Now; apr.expense += cashflow.Expenses; apr.income += cashflow.Income; break;

                        case "May": may.date = DateTime.Now; may.expense += cashflow.Expenses; may.income += cashflow.Income; break;

                        case "Jun": jun.date = DateTime.Now; jun.expense += cashflow.Expenses; jun.income += cashflow.Income; break;

                        case "Jul": jul.date = DateTime.Now; jul.expense += cashflow.Expenses; jul.income += cashflow.Income; break;

                        case "Aug": aug.date = DateTime.Now; aug.expense += cashflow.Expenses; aug.income += cashflow.Income; break;

                        case "Sep": sep.date = DateTime.Now; sep.expense += cashflow.Expenses; sep.income += cashflow.Income; break;

                        case "Oct": oct.date = DateTime.Now; oct.expense += cashflow.Expenses; oct.income += cashflow.Income; break;

                        case "Nov": nov.date = DateTime.Now; nov.expense += cashflow.Expenses; nov.income += cashflow.Income; break;

                        case "Dec": dec.date = DateTime.Now; dec.expense += cashflow.Expenses; dec.income += cashflow.Income; break;

                        default: break;
                        }
                        totalExpenseInAssets += cashflow.Expenses;
                        totalIncomeInAssets  += cashflow.Income;
                    }
                }

                items.Add(jan);
                items.Add(feb);
                items.Add(mar);
                items.Add(apr);
                items.Add(may);
                items.Add(jun);
                items.Add(jul);
                items.Add(aug);
                items.Add(sep);
                items.Add(oct);
                items.Add(nov);
                items.Add(dec);


                CashflowBriefModel model = new CashflowBriefModel
                {
                    totalExpense = totalExpenseInAssets,
                    totalIncome  = totalIncomeInAssets,
                    data         = items
                };
                return(model);
            }
        }
Exemplo n.º 21
0
        public async Task <ClientGroup> CreateClientGroupAsync(ClientGroup clientGroup)
        {
            var addedClientGroup = await _clientGroupRepository.AddAsync(clientGroup);

            return(addedClientGroup);
        }
        public List <InsuranceListItemModel> GetInsuranceList_Client()
        {
            Client      client      = edisRepo.GetClientSync(User.Identity.GetUserId(), DateTime.Now);
            ClientGroup clientGroup = edisRepo.GetClientGroupSync(client.ClientGroupId, DateTime.Now);

            if (clientGroup.MainClientId == client.Id)
            {
                List <GroupAccount>  groupAccounts  = edisRepo.GetAccountsForClientGroupSync(clientGroup.ClientGroupNumber, DateTime.Now);
                List <ClientAccount> clientAccounts = edisRepo.GetAccountsForClientSync(client.ClientNumber, DateTime.Now);


                List <InsuranceListItemDetailModel> assetInsurance         = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> persoanlInsurance      = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> liabilityInsurance     = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> miscellaneousInsurance = new List <InsuranceListItemDetailModel>();

                List <InsuranceListItemModel> model = new List <InsuranceListItemModel>();

                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.AssetInsurance.ToString(),
                    data = assetInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.LiabilityInsurance.ToString(),
                    data = liabilityInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.MiscellaneousInsurance.ToString(),
                    data = miscellaneousInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.PersoanlInsurance.ToString(),
                    data = persoanlInsurance,
                });

                List <LiabilityBase> liabilities = new List <LiabilityBase>();
                foreach (var account in groupAccounts)
                {
                    liabilities.AddRange(account.GetLiabilitiesSync());
                }
                foreach (var account in clientAccounts)
                {
                    liabilities.AddRange(account.GetLiabilitiesSync());
                }
                var insurancesGroups = liabilities.OfType <Insurance>().GroupBy(i => i.InsuranceType);
                foreach (var insuranceMetaGroup in insurancesGroups)
                {
                    var insurance = insuranceMetaGroup.FirstOrDefault();

                    switch (insuranceMetaGroup.Key)
                    {
                    case InsuranceType.None:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.None.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.AssetInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.MiscellaneousInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.MiscellaneousInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.PersoanlInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.PersoanlInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;
                    }
                }

                return(model);
            }
            else
            {
                List <ClientAccount> accounts = edisRepo.GetAccountsForClientSync(client.ClientNumber, DateTime.Now);

                List <InsuranceListItemDetailModel> assetInsurance         = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> persoanlInsurance      = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> liabilityInsurance     = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> miscellaneousInsurance = new List <InsuranceListItemDetailModel>();


                List <InsuranceListItemModel> model = new List <InsuranceListItemModel>();

                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.AssetInsurance.ToString(),
                    data = assetInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.LiabilityInsurance.ToString(),
                    data = liabilityInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.MiscellaneousInsurance.ToString(),
                    data = miscellaneousInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.PersoanlInsurance.ToString(),
                    data = persoanlInsurance,
                });

                List <LiabilityBase> liabilities = new List <LiabilityBase>();
                foreach (var account in accounts)
                {
                    liabilities.AddRange(account.GetLiabilitiesSync());
                }
                var insurancesGroups = liabilities.OfType <Insurance>().GroupBy(i => i.InsuranceType);
                foreach (var insuranceMetaGroup in insurancesGroups)
                {
                    var insurance = insuranceMetaGroup.FirstOrDefault();

                    switch (insuranceMetaGroup.Key)
                    {
                    case InsuranceType.None:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.None.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.AssetInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.MiscellaneousInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.MiscellaneousInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.PersoanlInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.PersoanlInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;
                    }
                }

                return(model);
            }
        }
Exemplo n.º 23
0
        public bool SpawnPlayer(coGameConnection client, string spawnpoint, bool nocontrol)
        {
            coPlayer player = client["player"];


            if (player.isObject())
            {
                console.error("Attempting to create a player for a client that already has one!");
                return(false);
            }

            if ((spawnpoint.Split(' ').GetUpperBound(0) == 0) && (spawnpoint.isObject()))
            {
                // Attempt to treat %spawnPoint as an object
                string spawnclass     = Game__DefaultPlayerClass;
                string spawndatablock = Game__DefaultPlayerDataBlock;

                coSimObject ospawnpoint = spawnpoint;


                // Overrides by the %spawnPoint
                if (ospawnpoint["spawnClass"] != "")
                {
                    spawnclass     = ospawnpoint["spawnClass"];
                    spawndatablock = ospawnpoint["spawnDataBlock"];
                }

                else if (ospawnpoint["spawnDatablock"] != "")
                {
                    // This may seem redundant given the above but it allows
                    // the SpawnSphere to override the datablock without
                    // overriding the default player class
                    spawndatablock = ospawnpoint["spawnDatablock"];
                }
                string spawnproperties = ospawnpoint["spawnProperties"];
                string spawnScript     = ospawnpoint["spawnScript"];

                // Spawn with the engine's Sim::spawnObject() function
                player = console.SpawnObject(spawnclass, spawndatablock, "", spawnproperties, spawnScript);
                // If we have an object do some initial setup
                if (console.isObject(player))
                {
                    // Pick a location within the spawn sphere.
                    player.setTransform(PointInSpawnSphere(player, ((coSpawnSphere)spawnpoint)));
                }
                else
                {
                    // If we weren't able to create the player object then warn the user
                    // When the player clicks OK in one of these message boxes, we will fall through
                    // to the "if (!isObject(%player))" check below.
                    if (console.GetVarString(spawndatablock).Trim() != "")
                    {
                        console.Call("MessageBoxOK", new[] { "Spawn Player Failed", "Unable to create a player with class " + spawnclass + " and datablock " + spawndatablock + ".\n\nStarting as an Observer instead.", "" });
                    }
                    else
                    {
                        console.Call("MessageBoxOK", new[] { "Spawn Player Failed", "Unable to create a player with class " + spawnclass + ".\n\nStarting as an Observer instead.", "" });
                    }
                }
            }
            else
            {
                // Create a default player
                player = console.SpawnObject(Game__DefaultPlayerClass, Game__DefaultPlayerDataBlock, "", "", "");

                if (player.isMemberOfClass("Player"))
                {
                    //if (SimObject.SimObject_isMemberOfClass(player, "Player"))
                    console.warn("Trying to spawn a class that does not derive from player!!!!!");
                }
                // Treat %spawnPoint as a transform
                player.setTransform(new TransformF(spawnpoint));
            }

            // Update the default camera to start with the player
            if (!console.isObject(player))
            {
                client["spawnCamera"] = spawnpoint;
                return(false);
            }

            ((coSimSet)"MissionCleanup").pushToBack(player);
            // Update the default camera to start with the player


            // Store the client object on the player object for
            // future reference
            player["client"] = client;

            // If the player's client has some owned turrets, make sure we let them
            // know that we're a friend too.

            if (client["ownedTurrets"].AsInt() >= 1)
            {
                coSimSet turrets = client["ownedTurrets"];
                for (uint i = 0; i < turrets.getCount(); i++)
                {
                    ((coTurretShape)turrets.getObject(i)).call("addToIgnoreList", player);
                }
            }

            player.setShapeName(client["playerName"]);

            player.setEnergyLevel(((coPlayerData)player.getDataBlock())["maxEnergy"].AsFloat());

            if (client["skin"] != "")
            {
                string availableSkins = ((coPlayerData)player.getDataBlock())["availableSkins"];
                foreach (coGameConnection other in ClientGroup.Where(other => other != client))
                {
                    availableSkins = availableSkins.Replace(console.GetVarString(other + ".skin"), " ");

                    availableSkins = availableSkins.Replace("  ", " ");
                }
                List <string> availskin = availableSkins.Split('\t').ToList();
                if (availskin.Count > 0)
                {
                    int r = new Random().Next(0, availskin.Count - 1);
                    client["skin"] = availskin[r];
                }
            }

            player.setSkinName(client["skin"]);
            client["player"] = player;

            coSimObject control = null;

            if (console.GetVarString("$startWorldEditor") == "1")
            {
                control = client["camera"];
                console.Call("EditorGui", "syncCameraGui");
            }
            else
            {
                control = player;
            }

            if (!nocontrol)
            {
                client.setControlObject(control);
            }

            int team = new Random().Next(1, 2);

            AddObjectTo_MobSearchGroup(player, team);

            MessageClient(client, "System", "Your on Team " + team);

            console.error(DateTime.Now + " --- PLAYER JOIN::Name '" + Util.StripMLControlChars(player.getShapeName()) + "'::ID '" + player + "'");
            return(true);
        }
Exemplo n.º 24
0
        public async Task PushNotify(string clientGroupName, Noftication noftication, Triple <string, string, ObjectNotificationType> notificationSetting)
        {
            try
            {
                FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

                ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

                foreach (string receiver in clientGroup.UserIds)
                {
                    var receiverUser = await userRepository.GetByIdAsync(ObjectId.Parse(receiver));

                    if (receiverUser.TurnOfNotification != null)
                    {
                        if (receiverUser.TurnOfNotification.Any(x => x == noftication.ObjectId))
                        {
                            return;
                        }
                    }

                    Noftication finalNotification = new Noftication()
                    {
                        AuthorId        = noftication.AuthorId,
                        OwnerId         = noftication.OwnerId,
                        ReceiverId      = receiver,
                        ObjectId        = noftication.ObjectId,
                        ObjectType      = notificationSetting.Item3,
                        ObjectThumbnail = noftication.ObjectThumbnail,
                    };

                    //Người tạo ra thông báo.
                    string creator     = noftication.AuthorId;
                    User   userCreator = await userRepository.GetByIdAsync(ObjectId.Parse(creator));

                    //Chủ sở hữu post
                    string owner     = noftication.OwnerId;
                    User   userOwner = await userRepository.GetByIdAsync(ObjectId.Parse(owner));


                    if (owner == creator)
                    {
                        if (receiver == owner)
                        {
                            finalNotification.Content = $"Bạn {notificationSetting.Item2} chính mình";
                        }
                        else if (receiver != owner)
                        {
                            finalNotification.Content = $"{userCreator.FirstName} {userCreator.LastName} {notificationSetting.Item2} họ. ";
                        }
                    }
                    else if (owner != creator)
                    {
                        //owner: Trung
                        //receiver: trung
                        //Creator: Thắng
                        if (receiver != owner)
                        {
                            finalNotification.Content = $"{userCreator.FirstName} {userCreator.LastName} {notificationSetting.Item2} {userOwner.FirstName} {userOwner.LastName}. ";
                        }
                        else if (receiver != creator)
                        {
                            finalNotification.Content = $"{userCreator.FirstName} {userCreator.LastName} {notificationSetting.Item2} bạn. ";
                        }
                    }

                    await nofticationRepository.AddAsync(finalNotification);

                    var notiViewModel = mapper.Map <NotificationViewModel>(finalNotification);
                    if (!(owner == creator && receiver == owner && creator == receiver))
                    {
                        try
                        {
                            FilterDefinition <FcmInfo> user = Builders <FcmInfo> .Filter.Eq("user_id", receiver);

                            string token  = (await fcmInfoRepository.FindAsync(user)).DeviceToken;
                            User   sender = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotification.AuthorId));

                            FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                            {
                                Token = token,

                                Data = new Dictionary <string, string>()
                                {
                                    { "notification", JsonConvert.SerializeObject(notiViewModel) }
                                },
                                Notification = new Notification()
                                {
                                    Title    = $"{sender.FirstName} {sender.LastName}",
                                    Body     = notiViewModel.Content,
                                    ImageUrl = sender.AvatarHash
                                }
                            };
                            string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
            catch (Exception)
            {
                //Do nothing
            }
        }
        public List <InsuranceListItemModel> GetInsuranceList_Adviser(string clientGroupId = null)
        {
            if (string.IsNullOrEmpty(clientGroupId))
            {
                List <GroupAccount>  groupAccounts  = edisRepo.getAllClientGroupAccountsForAdviser(User.Identity.GetUserId(), DateTime.Now);
                List <ClientAccount> clientAccounts = edisRepo.getAllClientAccountsForAdviser(User.Identity.GetUserId(), DateTime.Now);



                List <InsuranceListItemDetailModel> assetInsurance         = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> persoanlInsurance      = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> liabilityInsurance     = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> miscellaneousInsurance = new List <InsuranceListItemDetailModel>();

                List <InsuranceListItemModel> model = new List <InsuranceListItemModel>();

                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.AssetInsurance.ToString(),
                    data = assetInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.LiabilityInsurance.ToString(),
                    data = liabilityInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.MiscellaneousInsurance.ToString(),
                    data = miscellaneousInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.PersoanlInsurance.ToString(),
                    data = persoanlInsurance,
                });

                List <LiabilityBase> liabilities = new List <LiabilityBase>();
                foreach (var account in groupAccounts)
                {
                    liabilities.AddRange(account.GetLiabilitiesSync());
                }
                foreach (var account in clientAccounts)
                {
                    liabilities.AddRange(account.GetLiabilitiesSync());
                }
                var insurancesGroups = liabilities.OfType <Insurance>().GroupBy(i => i.InsuranceType);
                foreach (var insuranceMetaGroup in insurancesGroups)
                {
                    var insurance = insuranceMetaGroup.FirstOrDefault();

                    switch (insuranceMetaGroup.Key)
                    {
                    case InsuranceType.None:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.None.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.AssetInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.MiscellaneousInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.MiscellaneousInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.PersoanlInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.PersoanlInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;
                    }

                    //switch (insuranceMetaGroup.Key)
                    //{
                    //    case InsuranceType.None:
                    //        SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.None.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.None.ToString()), insurance);
                    //        break;
                    //    case InsuranceType.AssetInsurance:
                    //        switch (insurance.PolicyType)
                    //        {
                    //            case PolicyType.Boat:
                    //                SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.Boat.ToString()), insurance);
                    //                break;
                    //            case PolicyType.Building:
                    //                SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.Building.ToString()), insurance);
                    //                break;
                    //            case PolicyType.Car:
                    //                SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.Car.ToString()), insurance);
                    //                break;
                    //            case PolicyType.MotorBike:
                    //                SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.MotorBike.ToString()), insurance);
                    //                break;
                    //            case PolicyType.Content:
                    //                SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.Content.ToString()), insurance);
                    //                break;
                    //        }
                    //        break;
                    //    case InsuranceType.MiscellaneousInsurance:
                    //        switch (insurance.PolicyType)
                    //        {
                    //            case PolicyType.IncomeProtection:
                    //                SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.MiscellaneousInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.IncomeProtection.ToString()), insurance);
                    //                break;
                    //            case PolicyType.RentalIncome:
                    //                SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.MiscellaneousInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.RentalIncome.ToString()), insurance);
                    //                break;
                    //        }
                    //        break;
                    //    case InsuranceType.PersoanlInsurance:
                    //        SetModelDetailsFromInsurance(model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.PersoanlInsurance.ToString()).data.SingleOrDefault(d => d.typeOfPolicy == PolicyType.Accident.ToString()), insurance);
                    //        break;
                    //}
                }

                return(model);
                //return repo.Insurance_GetInsuranceList_Adviser(User.Identity.GetUserId());
            }
            else
            {
                ClientGroup          clientGroup    = edisRepo.getClientGroupByGroupId(clientGroupId);
                List <GroupAccount>  accounts       = edisRepo.GetAccountsForClientGroupSync(clientGroup.ClientGroupNumber, DateTime.Now);
                List <ClientAccount> clientAccounts = new List <ClientAccount>();
                clientGroup.GetClientsSync().ForEach(c => clientAccounts.AddRange(c.GetAccountsSync()));

                List <InsuranceListItemDetailModel> assetInsurance         = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> persoanlInsurance      = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> liabilityInsurance     = new List <InsuranceListItemDetailModel>();
                List <InsuranceListItemDetailModel> miscellaneousInsurance = new List <InsuranceListItemDetailModel>();

                List <InsuranceListItemModel> model = new List <InsuranceListItemModel>();

                //model.Add(new InsuranceListItemModel
                //{
                //    insuranceMetaType = InsuranceType.None.ToString(),
                //    data = noneInsurance,
                //});
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.AssetInsurance.ToString(),
                    data = assetInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.LiabilityInsurance.ToString(),
                    data = liabilityInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.MiscellaneousInsurance.ToString(),
                    data = miscellaneousInsurance,
                });
                model.Add(new InsuranceListItemModel
                {
                    insuranceMetaType = InsuranceType.PersoanlInsurance.ToString(),
                    data = persoanlInsurance,
                });

                List <LiabilityBase> liabilities = new List <LiabilityBase>();
                accounts.ForEach(a => liabilities.AddRange(a.GetLiabilitiesSync()));
                clientAccounts.ForEach(a => liabilities.AddRange(a.GetLiabilitiesSync()));

                var insurancesGroups = liabilities.OfType <Insurance>().GroupBy(i => i.InsuranceType);
                foreach (var insuranceMetaGroup in insurancesGroups)
                {
                    var insurance = insuranceMetaGroup.FirstOrDefault();

                    switch (insuranceMetaGroup.Key)
                    {
                    case InsuranceType.None:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.None.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.AssetInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.AssetInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.MiscellaneousInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.MiscellaneousInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;

                    case InsuranceType.PersoanlInsurance:
                        model.SingleOrDefault(i => i.insuranceMetaType == InsuranceType.PersoanlInsurance.ToString()).data.Add(SetModelDetailsFromInsurance(new InsuranceListItemDetailModel(), insurance));
                        break;
                    }
                }

                return(model);
                //return repo.Insurance_GetInsuranceList_Client(clientGroupId);
            }
        }
Exemplo n.º 26
0
        public void updateTree()
        {
            分组treeView.Nodes.Clear();
            rootNode.Nodes.Clear();


            //root tree
            //TreeNode rootNode = new TreeNode("所有分组",IconIndexes.tree, IconIndexes.tree);
            rootNode.Tag  = "所有分组";
            rootNode.Text = "所有分组";
            分组treeView.Nodes.Add(rootNode);

            TreeNode noNode = new TreeNode("未分组", IconIndexes.tree, IconIndexes.tree);

            noNode.Tag  = "未分组";
            noNode.Text = "未分组";
            分组treeView.Nodes.Add(noNode);

            //group tree
            using (SQLiteConnection conn = new SQLiteConnection("data source=nodisk.db"))
            {
                using (SQLiteCommand cmd = new SQLiteCommand())
                {
                    cmd.Connection = conn;
                    conn.Open();

                    SQLiteHelper sh = new SQLiteHelper(cmd);

                    DataTable dt  = sh.Select("select * from CLIENT_GROUP;");
                    DataTable dts = sh.Select("select * from CLIENT;");

                    ClientGroup tempClientGroup = new ClientGroup();

                    foreach (DataRow ro in dts.Rows)
                    {
                        if (ro["client_group_id"].ToString() == "未分组")
                        {
                            TreeNode clientNode = new TreeNode(ro["client_name"].ToString(), IconIndexes.computer, IconIndexes.computer);
                            clientNode.Tag  = ro["client_name"].ToString();
                            clientNode.Text = ro["client_name"].ToString();
                            noNode.Nodes.Add(clientNode);
                        }
                    }


                    foreach (DataRow row in dt.Rows)
                    {
                        tempClientGroup = new ClientGroup();
                        tempClientGroup.ClientGroupId   = row["client_group_id"].ToString();
                        tempClientGroup.ClientGroupName = row["client_group_name"].ToString();

                        TreeNode tempNode = new TreeNode(tempClientGroup.ClientGroupName, IconIndexes.computer, IconIndexes.computer);
                        tempNode.Tag  = tempClientGroup.ClientGroupName;
                        tempNode.Text = tempClientGroup.ClientGroupName;



                        //将工作站放入对应的组
                        foreach (DataRow rows in dts.Rows)
                        {
                            string tempGroupId = rows["client_group_id"].ToString();

                            if (tempGroupId == tempClientGroup.ClientGroupId)
                            {
                                TreeNode clientNode = new TreeNode(rows["client_name"].ToString(), IconIndexes.computer, IconIndexes.computer);
                                clientNode.Tag  = rows["client_name"].ToString();
                                clientNode.Text = rows["client_name"].ToString();
                                tempNode.Nodes.Add(clientNode);
                            }
                        }
                        //
                        rootNode.Nodes.Add(tempNode);
                        clientGroupList.Add(tempClientGroup);
                    }

                    conn.Close();
                }
            }

            分组treeView.ExpandAll();
        }
Exemplo n.º 27
0
        void InitServerByDatabase()
        {
            try
            {
                using (var dataReader = DataHelper.Instance.ExecuteProcedureReader("InitServer", DataHelper.CreateParam("@TYPE", System.Data.SqlDbType.Int, 1)))
                {
                    if (dataReader == null)
                    {
                        Environment.Exit(0);
                    }
                    //dataReader.Read();
                    dataReader.Read();
                    int count = dataReader.GetInt32(0);
                    _list    = new List <TagMetaData>(count);
                    _mapping = new Dictionary <string, ITag>(count);
                    dataReader.NextResult();
                    while (dataReader.Read())
                    {
                        _list.Add(new TagMetaData(dataReader.GetInt16(0), dataReader.GetInt16(1), dataReader.GetString(2), dataReader.GetString(3), (DataType)dataReader.GetByte(4),
                                                  (ushort)dataReader.GetInt16(5), dataReader.GetBoolean(6), dataReader.GetFloat(7), dataReader.GetFloat(8), dataReader.GetInt32(9)));
                        //_list[i].Description = dataReader.GetSqlString(6).Value;
                    }
                    _list.Sort();
                    if (reader != null && group == null)
                    {
                        group = reader.AddGroup("Group1", 1, 0, 0, true) as ClientGroup;
                        group.AddItems(_list);
                    }
                    dataReader.NextResult();
                    _conditions    = new List <ICondition>();
                    _conditionList = new ObservableCollection <ICondition>();
                    while (dataReader.Read())
                    {
                        int        id   = dataReader.GetInt32(0);
                        AlarmType  type = (AlarmType)dataReader.GetInt32(2);
                        ICondition cond;
                        string     source = dataReader.GetString(1);
                        if (_conditions.Count > 0)
                        {
                            cond = _conditions[_conditions.Count - 1];
                            if (cond.ID == id)
                            {
                                cond.AddSubCondition(new SubCondition((SubAlarmType)dataReader.GetInt32(9), dataReader.GetFloat(10),
                                                                      (Severity)dataReader.GetByte(11), dataReader.GetString(12), dataReader.GetBoolean(13)));
                                continue;
                            }
                        }
                        switch (type)
                        {
                        case AlarmType.Complex:
                            cond = new ComplexCondition(id, source, dataReader.GetString(6), dataReader.GetFloat(7), dataReader.GetInt32(8));
                            break;

                        case AlarmType.Level:
                            cond = new LevelAlarm(id, source, dataReader.GetString(6), dataReader.GetFloat(7), dataReader.GetInt32(8));
                            break;

                        case AlarmType.Dev:
                            cond = new DevAlarm(id, (ConditionType)dataReader.GetByte(4), source, dataReader.GetString(6),
                                                dataReader.GetFloat(5), dataReader.GetFloat(7), dataReader.GetInt32(8));
                            break;

                        case AlarmType.ROC:
                            cond = new ROCAlarm(id, source, dataReader.GetString(6), dataReader.GetFloat(7), dataReader.GetInt32(8));
                            break;

                        case AlarmType.Quality:
                            cond = new QualitiesAlarm(id, source, dataReader.GetString(6));
                            break;

                        default:
                            cond = new DigitAlarm(id, source, dataReader.GetString(6), dataReader.GetInt32(8));
                            break;
                        }
                        cond.AddSubCondition(new SubCondition((SubAlarmType)dataReader.GetInt32(9), dataReader.GetFloat(10),
                                                              (Severity)dataReader.GetByte(11), dataReader.GetString(12), dataReader.GetBoolean(13)));

                        cond.IsEnabled = dataReader.GetBoolean(3);
                        var simpcond = cond as SimpleCondition;
                        if (simpcond != null)
                        {
                            simpcond.Tag = this[source];
                        }
                        else
                        {
                            var complexcond = cond as ComplexCondition;
                            if (complexcond != null)
                            {
                                var action = complexcond.SetFunction(reval.Eval(source));
                                if (action != null)
                                {
                                    ValueChangedEventHandler handle = (s1, e1) => { action(); };
                                    foreach (ITag tag in reval.TagList)
                                    {
                                        tag.ValueChanged += handle;// tag.Refresh();
                                    }
                                }
                            }
                        }
                        cond.AlarmActive += new AlarmEventHandler(cond_SendAlarm);
                        cond.AlarmAck    += new EventHandler(cond_AckAlarm);
                        //_conditions.Add(cond);// UpdateCondition(cond);
                        _conditions.Add(cond);
                    }
                    dataReader.NextResult();
                    while (dataReader.Read())
                    {
                        _scales.Add(new Scaling(dataReader.GetInt16(0), (ScaleType)dataReader.GetByte(1),
                                                dataReader.GetFloat(2), dataReader.GetFloat(3), dataReader.GetFloat(4), dataReader.GetFloat(5)));
                    }
                }
                reval.Clear();
                _scales.Sort();
                _compare = new CompareCondBySource();
                _conditions.Sort(_compare);
            }
            catch (Exception e)
            {
                App.AddErrorLog(e);
                Environment.Exit(0);
            }
        }
Exemplo n.º 28
0
 public CreateRoomTripleThunderScriptServer(Server Owner, ClientGroup ClientGroupTemplate)
     : base(Owner, ClientGroupTemplate)
 {
     this.Owner = Owner;
     this.ClientGroupTemplate = ClientGroupTemplate;
 }
Exemplo n.º 29
0
 public AskStartGameScriptServer(ClientGroup CreatedGroup)
     : base(ScriptName)
 {
     this.CreatedGroup = CreatedGroup;
 }
        public InvestmentPortfolioModel GetAssetAllocationSummary_Adviser(string clientGroupId = null)
        {
            if (string.IsNullOrEmpty(clientGroupId))
            {
                List <GroupAccount>  groupAccounts  = edisRepo.getAllClientGroupAccountsForAdviser(User.Identity.GetUserId(), DateTime.Now);
                List <ClientAccount> clientAccounts = edisRepo.getAllClientAccountsForAdviser(User.Identity.GetUserId(), DateTime.Now);

                double totalMarketValueAE = 0;
                double totalMarketValueIE = 0;
                double totalMarketValueMI = 0;
                double totalMarketValueDP = 0;
                double totalMarketValueFI = 0;
                double totalMarketValueCD = 0;

                foreach (var account in groupAccounts)
                {
                    totalMarketValueAE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <AustralianEquity>();
                    totalMarketValueIE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <InternationalEquity>();
                    totalMarketValueMI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <ManagedInvestment>();
                    totalMarketValueDP += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <DirectProperty>();
                    totalMarketValueFI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <FixedIncome>();
                    totalMarketValueCD += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <Cash>();
                }
                foreach (var account in clientAccounts)
                {
                    totalMarketValueAE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <AustralianEquity>();
                    totalMarketValueIE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <InternationalEquity>();
                    totalMarketValueMI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <ManagedInvestment>();
                    totalMarketValueDP += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <DirectProperty>();
                    totalMarketValueFI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <FixedIncome>();
                    totalMarketValueCD += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <Cash>();
                }

                InvestmentPortfolioModel model = new InvestmentPortfolioModel
                {
                    data = new List <DataNameAmountPair> {
                        new DataNameAmountPair {
                            name = "Australian Equity", amount = totalMarketValueAE
                        },
                        new DataNameAmountPair {
                            name = "International Equity", amount = totalMarketValueIE
                        },
                        new DataNameAmountPair {
                            name = "Managed Investments", amount = totalMarketValueMI
                        },
                        new DataNameAmountPair {
                            name = "Direct & Listed Property", amount = totalMarketValueDP
                        },
                        new DataNameAmountPair {
                            name = "Miscellaneous Investments", amount = totalMarketValueAE
                        },
                        new DataNameAmountPair {
                            name = "Fixed Income Investments", amount = totalMarketValueFI
                        },
                        new DataNameAmountPair {
                            name = "Cash & Term Deposit", amount = totalMarketValueCD
                        },
                    },
                };

                return(model);
            }
            else
            {
                ClientGroup          clientGroup    = edisRepo.getClientGroupByGroupId(clientGroupId);
                List <GroupAccount>  accounts       = edisRepo.GetAccountsForClientGroupSync(clientGroup.ClientGroupNumber, DateTime.Now);
                List <ClientAccount> clientAccounts = new List <ClientAccount>();
                clientGroup.GetClientsSync().ForEach(c => clientAccounts.AddRange(c.GetAccountsSync()));


                double totalMarketValueAE = 0;
                double totalMarketValueIE = 0;
                double totalMarketValueMI = 0;
                double totalMarketValueDP = 0;
                double totalMarketValueFI = 0;
                double totalMarketValueCD = 0;

                foreach (var account in accounts)
                {
                    totalMarketValueAE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <AustralianEquity>();
                    totalMarketValueIE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <InternationalEquity>();
                    totalMarketValueMI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <ManagedInvestment>();
                    totalMarketValueDP += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <DirectProperty>();
                    totalMarketValueFI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <FixedIncome>();
                    totalMarketValueCD += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <Cash>();
                }
                foreach (var account in clientAccounts)
                {
                    totalMarketValueAE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <AustralianEquity>();
                    totalMarketValueIE += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <InternationalEquity>();
                    totalMarketValueMI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <ManagedInvestment>();
                    totalMarketValueDP += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <DirectProperty>();
                    totalMarketValueFI += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <FixedIncome>();
                    totalMarketValueCD += account.GetAssetsSync().GetTotalMarketValue_ByAssetType <Cash>();
                }

                InvestmentPortfolioModel model = new InvestmentPortfolioModel
                {
                    data = new List <DataNameAmountPair> {
                        new DataNameAmountPair {
                            name = "Australian Equity", amount = totalMarketValueAE
                        },
                        new DataNameAmountPair {
                            name = "International Equity", amount = totalMarketValueIE
                        },
                        new DataNameAmountPair {
                            name = "Managed Investments", amount = totalMarketValueMI
                        },
                        new DataNameAmountPair {
                            name = "Direct & Listed Property", amount = totalMarketValueDP
                        },
                        new DataNameAmountPair {
                            name = "Miscellaneous Investments", amount = totalMarketValueAE
                        },
                        new DataNameAmountPair {
                            name = "Fixed Income Investments", amount = totalMarketValueFI
                        },
                        new DataNameAmountPair {
                            name = "Cash & Term Deposit", amount = totalMarketValueCD
                        },
                    },
                };

                return(model);
            }

            //return repo.ManagedInvestment_GetAssetAllocation_Adviser(User.Identity.GetUserId());
        }