private void BetCancel(bet_cancel e, dbEntities db, string routeKey)
        {
            var sectionName = string.Empty;

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    sectionName = "bet_cancel";
                    foreach (var market in e.market)
                    {
                        var specifier = market.specifiers?.Split('=').LastOrDefault().Trim();
                        var spParams  = "EXECUTE PROCEDURE BET_EVENTBETCANCEL_I(";
                        spParams += SourceId + ",";
                        spParams += e.event_id.Split(':').Last() + ",";
                        spParams += e.product + ",";
                        spParams += e.start_time + ",";
                        spParams += e.end_time + ",";
                        spParams += market.id + ",";
                        spParams += "'" + specifier + "',";
                        spParams += market.void_reason + ",";
                        spParams += e.GeneratedAt + ")";
                        db.Database.ExecuteSqlCommand(spParams.Trim());
                    }
                    dbContextTransaction.Commit();
                    SerilogHelper.Information(string.Format("{0} {1}", routeKey, UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception(string.Format("Unknown exception in {0} {1} {2}", routeKey, sectionName, e.event_id), ex);
                }
            }
        }
        private void BetStop(bet_stop e, dbEntities cnn, string routeKey)
        {
            using (var dbContextTransaction = cnn.Database.BeginTransaction())
            {
                var sectionName = string.Empty;
                var spParams    = string.Empty;
                try
                {
                    sectionName = "bet_stop";
                    spParams    = "EXECUTE PROCEDURE BET_EVENTBETSTOP_I(";
                    spParams   += SourceId + ",";
                    spParams   += e.event_id.Split(':').Last() + ",";
                    spParams   += e.product + ",";
                    spParams   += "'" + e.groups?.Trim() + "',";
                    spParams   += e.market_status + ",";
                    spParams   += e.GeneratedAt + ")";
                    cnn.Database.ExecuteSqlCommand(spParams.Trim());

                    dbContextTransaction.Commit();

                    SerilogHelper.Information($"{routeKey} {UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"}");
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception($"Unknown exception in {routeKey} SectionName:{sectionName} SQL:{spParams.Trim()}", ex);
                }
            }
        }
        private void FixtureChange(fixture_change e, dbEntities db, string routeKey)
        {
            var sectionName = string.Empty;

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    sectionName = "fixture_change";
                    var spParams = "EXECUTE PROCEDURE BET_EVENTFIXTURECHANGE_I(";
                    spParams += SourceId + ",";
                    spParams += e.event_id.Split(':').Last() + ",";
                    spParams += e.product + ",";
                    spParams += e.change_type + ",";
                    spParams += e.GeneratedAt + ")";
                    db.Database.ExecuteSqlCommand(spParams.Trim());

                    dbContextTransaction.Commit();
                    SerilogHelper.Information(string.Format("{0} {1}", routeKey, UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception(string.Format("Unknown exception in {0} {1} {2}", routeKey, sectionName, e.event_id), ex);
                }
            }
        }
        private void BetSettlement(bet_settlement e, dbEntities db, string routeKey)
        {
            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                var sectionName = string.Empty;
                var spParams    = string.Empty;
                try
                {
                    var marketIdList  = string.Empty;
                    var specifierList = string.Empty;
                    var outcomeIdList = string.Empty;
                    var resultList    = string.Empty;
                    var certaintyList = string.Empty;
                    var productList   = string.Empty;

                    foreach (var market in e.outcomes)
                    {
                        var marketId  = market.id;
                        var specifier = market.specifiers?.Split('=').LastOrDefault()?.Trim();

                        foreach (var outcome in market.Items)
                        {
                            marketIdList  += marketId + ",";
                            specifierList += specifier + ",";
                            outcomeIdList += outcome.id.Split(':').LastOrDefault() + ",";
                            resultList    += outcome.result + ",";
                            certaintyList += e.certainty + ",";
                            productList   += e.product + ",";

                            marketId = 0;
                            if (!string.IsNullOrEmpty(specifier))
                            {
                                specifier = "*";
                            }
                        }
                    }

                    sectionName = "bet_settlement";
                    spParams    = "EXECUTE PROCEDURE BET_EVENTRESULTS_I_MULTI(";
                    spParams   += SourceId + ",";
                    spParams   += e.event_id.Split(':').Last() + ",";
                    spParams   += "'" + marketIdList.Substring(0).Trim() + "',";
                    spParams   += "'" + specifierList.Substring(0).Trim() + "',";
                    spParams   += "'" + outcomeIdList.Substring(0).Trim() + "',";
                    spParams   += "'" + resultList.Substring(0).Trim() + "',";
                    spParams   += "'" + certaintyList.Substring(0).Trim() + "',";
                    spParams   += "'" + productList.Substring(0).Trim() + "',";
                    spParams   += e.GeneratedAt + ")";
                    db.Database.ExecuteSqlCommand(spParams.Trim());

                    dbContextTransaction.Commit();
                    SerilogHelper.Information($"{routeKey} {UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"}");
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception($"Unknown exception in {routeKey} SectionName:{sectionName} SQL:{spParams.Trim()}", ex);
                }
            }
        }
        public static void ReceiveMeta()
        {
            var rbService = new RabbitMQService();
            var conn      = rbService.GetRabbitMQConnection();
            var meta      = conn.CreateModel();

            meta.ExchangeDeclare("Metas", durable: true, type: ExchangeType.Fanout);
            var queueName = meta.QueueDeclare().QueueName;

            meta.QueueBind(queue: queueName, exchange: "Metas", routingKey: "UOFMetas");
            meta.BasicQos(prefetchSize: 0, prefetchCount: 1, false);
            var metaConsumer = new EventingBasicConsumer(meta);

            meta.BasicConsume(queueName, false, metaConsumer);
            SerilogHelper.Information($"Connected Metas {queueName}");

            metaConsumer.Received += (model, ea) =>
            {
                var body  = ea.Body;
                var data  = Encoding.UTF8.GetString(body);
                var _data = UtcHelper.Deserialize <Meta>(data);
                Program.metaMainQueue.Enqueue(_data);
                meta.BasicAck(ea.DeliveryTag, multiple: false);
            };
        }
        private void RouteTheKey(string typeName, ReceiveFeedv2 feed, dbEntities db)
        {
            switch (typeName)
            {
            case "odds_change":
                OddsChange(UtcHelper.Deserialize <odds_change>(feed.Data), db, feed.RouteKey);
                break;

            case "bet_stop":
                BetStop(UtcHelper.Deserialize <bet_stop>(feed.Data), db, feed.RouteKey);
                break;

            case "bet_settlement":
                BetSettlement(UtcHelper.Deserialize <bet_settlement>(feed.Data), db, feed.RouteKey);
                break;

            case "cancelbet":
                BetCancel(UtcHelper.Deserialize <bet_cancel>(feed.Data), db, feed.RouteKey);
                break;

            case "producer_down":
                ProducerUpDown(UtcHelper.Deserialize <ProducerModel>(feed.Data), db, feed.RouteKey);
                break;

            case "producer_up":
                ProducerUpDown(UtcHelper.Deserialize <ProducerModel>(feed.Data), db, feed.RouteKey);
                break;

            case "rollback_betsettlement":
                SerilogHelper.Error($"{feed.RouteKey}");
                break;

            case "rollback_cancelbet":
                SerilogHelper.Error($"{feed.RouteKey}");
                break;

            case "fixture_change":
                FixtureChange(UtcHelper.Deserialize <fixture_change>(feed.Data), db, feed.RouteKey);
                break;

            default:
                SerilogHelper.Error($"{feed.RouteKey}");
                break;
            }
        }
        private void OddsChange(odds_change e, dbEntities cnn, string routeKey)
        {
            using (var dbContextTransaction = cnn.Database.BeginTransaction())
            {
                var spParams    = string.Empty;
                var sectionName = string.Empty;
                try
                {
                    var eventId      = e.event_id.Split(':').Last();
                    var product      = e.product;
                    var generatedAt  = e.timestamp;
                    var clockStopped = 0;

                    if (e.odds?.market != null)
                    {
                        sectionName = "odds_change";
                        var marketIdList      = string.Empty;
                        var specifierList     = string.Empty;
                        var statusList        = string.Empty;
                        var favoriteList      = string.Empty;
                        var outcomeIdList     = string.Empty;
                        var outcomeStatusList = string.Empty;
                        var outcomeOddList    = string.Empty;

                        foreach (var market in e.odds.market)
                        {
                            var marketId     = market.id;
                            var specifier    = market.specifiers?.Split('=').LastOrDefault()?.Trim();
                            var marketStatus = market.status;


                            if (market.outcome != null)
                            {
                                foreach (var outcome in market.outcome)
                                {
                                    sectionName        = "odds_change.market.outcome";
                                    marketIdList      += marketId + ",";
                                    specifierList     += specifier + ",";
                                    statusList        += marketStatus + ",";
                                    favoriteList      += market.favourite + ",";
                                    outcomeIdList     += outcome.id.Split(':').LastOrDefault() + ",";
                                    outcomeStatusList += outcome.active + ",";
                                    outcomeOddList    += outcome.odds.ToString(_nfi) + ",";
                                    marketId           = 0;
                                    if (!string.IsNullOrEmpty(specifier))
                                    {
                                        specifier = "*";
                                    }
                                }
                            }
                            else
                            {
                                marketIdList      += market.id + ",";
                                specifierList     += specifier + ",";
                                statusList        += market.status + ",";
                                favoriteList      += market.favourite + ",";
                                outcomeIdList     += string.Empty + ",";
                                outcomeStatusList += string.Empty + ",";
                                outcomeOddList    += string.Empty + ",";
                            }
                        }

                        sectionName = "execute BETDATA_ODDSCHANGE";
                        spParams    = "EXECUTE PROCEDURE BETDATA_ODDSCHANGE_MULTI(";
                        spParams   += SourceId + ",";
                        spParams   += eventId + ",";
                        spParams   += "'" + marketIdList.Substring(0).Trim() + "',";
                        spParams   += "'" + specifierList.Substring(0).Trim() + "',";
                        spParams   += "'" + statusList.Substring(0).Trim() + "',";
                        spParams   += "'" + favoriteList.Substring(0).Trim() + "',";
                        spParams   += "'" + outcomeIdList.Substring(0).Trim() + "',";
                        spParams   += "'" + outcomeStatusList.Substring(0).Trim() + "',";
                        spParams   += "'" + outcomeOddList.Substring(0).Trim() + "',";
                        spParams   += generatedAt + ")";
                        cnn.Database.ExecuteSqlCommand(spParams.Trim());
                    }


                    if (e.sport_event_status != null)
                    {
                        sectionName = "odds_change.sport_event_status";
                        var periodNumberList          = string.Empty;
                        var periodHomeScoreList       = string.Empty;
                        var periodAwayScoreList       = string.Empty;
                        var periodMatchStatusCodeList = string.Empty;
                        if (e.sport_event_status?.period_scores != null)
                        {
                            if (e.sport_event_status.period_scores.Length > 0)
                            {
                                sectionName = "odds_change.sport_event_status.period_scores";

                                periodNumberList = e.sport_event_status.period_scores
                                                   .Aggregate(string.Empty, (current, s) => current + "," + s.number).Substring(1)
                                                   .Trim();
                                periodHomeScoreList = e.sport_event_status.period_scores
                                                      .Aggregate(string.Empty, (current, s) => current + "," + s.home_score).Substring(1)
                                                      .Trim();
                                periodAwayScoreList = e.sport_event_status.period_scores
                                                      .Aggregate(string.Empty, (current, s) => current + "," + s.away_score).Substring(1)
                                                      .Trim();
                                periodMatchStatusCodeList = e.sport_event_status.period_scores
                                                            .Aggregate(string.Empty, (current, s) => current + "," + s.match_status_code)
                                                            .Substring(1).Trim();

                                periodNumberList          += ",";
                                periodHomeScoreList       += ",";
                                periodAwayScoreList       += ",";
                                periodMatchStatusCodeList += ",";
                            }
                        }

                        if (e.sport_event_status?.clock?.stopped != null)
                        {
                            clockStopped = e.sport_event_status.clock.stopped ? 1 : 0;
                        }


                        sectionName = "execute BET_EVENTDETAILS_UI";
                        spParams    = "EXECUTE PROCEDURE BET_EVENTDETAILS_UI(";
                        spParams   += SourceId + ",";
                        spParams   += eventId + ",";
                        spParams   += product + ",";
                        spParams   += "'" + e.sport_event_status?.clock?.match_time + "',";
                        spParams   += "'" + e.sport_event_status?.clock?.stoppage_time + "',";
                        spParams   += "'" + e.sport_event_status?.clock?.stoppage_time_announced + "',";
                        spParams   += "'" + e.sport_event_status?.clock?.remaining_time + "',";
                        spParams   += "'" + e.sport_event_status?.clock?.remaining_time_in_period + "',";
                        spParams   += clockStopped + ",";
                        spParams   += (e.sport_event_status?.statistics?.corners.home ?? 0) + ",";
                        spParams   += (e.sport_event_status?.statistics?.corners.away ?? 0) + ",";
                        spParams   += (e.sport_event_status?.statistics?.red_cards.home ?? 0) + ",";
                        spParams   += (e.sport_event_status?.statistics?.red_cards.away ?? 0) + ",";
                        spParams   += (e.sport_event_status?.statistics?.yellow_cards.home ?? 0) + ",";
                        spParams   += (e.sport_event_status?.statistics?.yellow_cards.away ?? 0) + ",";
                        spParams   += (e.sport_event_status?.statistics?.yellow_red_cards.home ?? 0) + ",";
                        spParams   += (e.sport_event_status?.statistics?.yellow_red_cards.away ?? 0) + ",";
                        spParams   += e.sport_event_status?.status + ",";
                        spParams   += e.sport_event_status?.home_score.ToString(_nfi) + ",";
                        spParams   += e.sport_event_status?.away_score.ToString(_nfi) + ",";
                        spParams   += e.sport_event_status?.match_status + ",";
                        spParams   += (e.odds?.betstop_reason ?? 0) + ",";
                        spParams   += (e.odds?.betting_status ?? 0) + ",";
                        spParams   += "'" + periodNumberList.Substring(0).Trim() + "',";
                        spParams   += "'" + periodHomeScoreList.Substring(0).Trim() + "',";
                        spParams   += "'" + periodAwayScoreList.Substring(0).Trim() + "',";
                        spParams   += "'" + periodMatchStatusCodeList.Substring(0).Trim() + "',";
                        spParams   += generatedAt + ")";
                        cnn.Database.ExecuteSqlCommand(spParams.Trim());
                    }

                    dbContextTransaction.Commit();
                    SerilogHelper.Information($"{routeKey} {UtcHelper.GetDifferenceFromTimestamp(e.timestamp) + "ms"}");
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();
                    SerilogHelper.Exception(
                        $"Unknown exception in {routeKey} SectionName:{sectionName} SQL:{spParams.Trim()}", ex);
                }
            }
        }
        public void LoadAllMetasOnStartUp()
        {
            if (!SampleClient.Properties.Settings.Default.LoadMetaOnStartUp)
            {
                return;
            }

            var         cnn      = new dbEntities();
            var         uri      = new Uri(MetaUrlSport);
            ApiResponse response = new ApiResponse();

            response = UtcHelper.GetDispatchMeta(uri, null).Result;
            if (response.Success)
            {
                List <Sport> sports = JsonConvert.DeserializeObject <List <Sport> >(response.Message);

                foreach (var sport in sports)
                {
                    using (var dbContextTransaction = cnn.Database.BeginTransaction())
                    {
                        var spParams = "EXECUTE PROCEDURE BET_SPORTS_I(";
                        spParams += sport.SourceId + ",";
                        spParams += sport.SportId + ",";
                        spParams += 1 + ",";
                        spParams += 0 + ")";
                        cnn.Database.ExecuteSqlCommand(spParams.Trim());
                        SerilogHelper.Debug(string.Format("META sport [{0}]", sport.SportId));

                        foreach (var sporttext in sport.Names)
                        {
                            spParams = "EXECUTE PROCEDURE BET_TRANSLATIONSIMPORT({0},{1},{2},{3},{4})";
                            var lang    = sporttext.Lang;
                            var mid     = sport.SportId;
                            var mtype   = 1;
                            var text    = sporttext.Name;
                            var superid = 0;
                            cnn.Database.ExecuteSqlCommand(spParams.Trim(), lang, mid, mtype, text, superid);
                            SerilogHelper.Debug(string.Format("TRANSLATION sport [{0}][{1}][{2}]", sport.SportId, sporttext.Lang, sporttext.Name));
                        }
                        dbContextTransaction.Commit();
                    }
                }
            }

            uri      = new Uri(MetaUrlCategory);
            response = UtcHelper.GetDispatchMeta(uri, null).Result;
            List <Category> categories = null;

            if (response.Success)
            {
                categories = JsonConvert.DeserializeObject <List <Category> >(response.Message);

                foreach (var category in categories)
                {
                    using (var dbContextTransaction = cnn.Database.BeginTransaction())
                    {
                        var spParams = "EXECUTE PROCEDURE BET_TOURNAMENTS_I(";
                        spParams += category.SourceId + ",";
                        spParams += category.SportId + ",";
                        spParams += category.CategoryId + ",";
                        spParams += category.CategoryId + ",";
                        spParams += 1 + ",";
                        spParams += 0 + ")";
                        cnn.Database.ExecuteSqlCommand(spParams.Trim());
                        SerilogHelper.Debug("META category");


                        foreach (var categorytext in category.Names)
                        {
                            spParams = "EXECUTE PROCEDURE BET_TRANSLATIONSIMPORT({0},{1},{2},{3},{4})";
                            var lang    = categorytext.Lang;
                            var mid     = category.CategoryId;
                            var mtype   = 4;
                            var text    = categorytext.Name;
                            var superid = 0;
                            cnn.Database.ExecuteSqlCommand(spParams.Trim(), lang, mid, mtype, text, superid);
                            SerilogHelper.Debug(string.Format("TRANSLATION category [{0}][{1}][{2}]", category.SportId, categorytext.Lang, categorytext.Name));
                        }

                        dbContextTransaction.Commit();
                    }
                }
            }

            uri      = new Uri(MetaUrlTournament);
            response = UtcHelper.GetDispatchMeta(uri, null).Result;
            if (response.Success)
            {
                List <Tournament> tournaments = JsonConvert.DeserializeObject <List <Tournament> >(response.Message);

                foreach (var tournament in tournaments)
                {
                    using (var dbContextTransaction = cnn.Database.BeginTransaction())
                    {
                        var sportid = categories.Where(g => g.CategoryId == tournament.CategoryId).FirstOrDefault()?.SportId ?? 0;
                        if (sportid == 0)
                        {
                            continue;
                        }
                        var spParams = "EXECUTE PROCEDURE BET_TOURNAMENTS_I(";
                        spParams += tournament.SourceId + ",";
                        spParams += sportid + ",";
                        spParams += tournament.TournamentId + ",";
                        spParams += tournament.CategoryId + ",";
                        spParams += 1 + ",";
                        spParams += 0 + ")";
                        cnn.Database.ExecuteSqlCommand(spParams.Trim());
                        SerilogHelper.Debug("META tournament");

                        foreach (var tournamenttext in tournament.Names)
                        {
                            spParams = "EXECUTE PROCEDURE BET_TRANSLATIONSIMPORT({0},{1},{2},{3},{4})";
                            var lang    = tournamenttext.Lang;
                            var mid     = tournament.TournamentId;
                            var mtype   = 5;
                            var text    = tournamenttext.Name;
                            var superid = tournament.CategoryId;
                            cnn.Database.ExecuteSqlCommand(spParams.Trim(), lang, mid, mtype, text, superid);
                            SerilogHelper.Debug(string.Format("TRANSLATION tournaments [{0}][{1}][{2}]", sportid, tournamenttext.Lang, tournamenttext.Name));
                        }

                        dbContextTransaction.Commit();
                    }
                }
            }


            uri      = new Uri(MetaUrlMarket);
            response = UtcHelper.GetDispatchMeta(uri, null).Result;
            List <Market> markets = null;

            if (response.Success)
            {
                var HomeTeam = string.Empty;
                var DrawGame = string.Empty;
                var AwayTeam = string.Empty;
                var Over     = string.Empty;
                var Under    = string.Empty;
                var nextGoal = string.Empty;

                markets = JsonConvert.DeserializeObject <List <Market> >(response.Message);

                foreach (var market in markets)
                {
                    using (var dbContextTransaction = cnn.Database.BeginTransaction())
                    {
                        foreach (var marketitem in market.Names)
                        {
                            switch (marketitem.Lang)
                            {
                            case "tr":
                                HomeTeam = "Evsahibi";
                                AwayTeam = "Deplasman";
                                nextGoal = "Sıradaki";
                                break;

                            case "de":
                                HomeTeam = "Heimteam";
                                AwayTeam = "Gastteam";
                                nextGoal = "Nächstes";
                                break;

                            default:
                                HomeTeam = "Hometeam";
                                AwayTeam = "Awayteam";
                                nextGoal = "Next";
                                break;
                            }
                            var spParams = "EXECUTE PROCEDURE BET_TRANSLATIONSIMPORT({0},{1},{2},{3},{4})";
                            var lang     = marketitem.Lang;
                            var mid      = market.MarketId;
                            var mtype    = 2;
                            var text     = marketitem.Name.Replace("{$competitor1}", HomeTeam)
                                           .Replace("{$competitor2}", AwayTeam).Replace("{!goalnr}", nextGoal).Replace("{hcp}", "");
                            var superid = 0;
                            cnn.Database.ExecuteSqlCommand(spParams.Trim(), lang, mid, mtype, text, superid);
                            SerilogHelper.Debug(string.Format("TRANSLATION markets [{0}][{1}][{2}]", market.MarketId, marketitem.Lang, marketitem.Name));
                        }

                        dbContextTransaction.Commit();
                    }
                }
            }

            uri      = new Uri(MetaUrlOutcome);
            response = UtcHelper.GetDispatchMeta(uri, null).Result;
            if (response.Success)
            {
                var HomeTeam = "1";
                var DrawGame = "X";
                var AwayTeam = "2";
                var Over     = "+";
                var Under    = "-";

                List <Outcome> outcomes = JsonConvert.DeserializeObject <List <Outcome> >(response.Message);


                foreach (var outcome in outcomes)
                {
                    using (var dbContextTransaction = cnn.Database.BeginTransaction())
                    {
                        //var markettext = markets.Where(g => g.MarketId == outcome.MarketId).FirstOrDefault().Names.Where(g => g.Lang == "en").FirstOrDefault().Name;
                        foreach (var outcometext in outcome.Names)
                        {
                            //outcome translate for special bet list
                            var spParams = "EXECUTE PROCEDURE BET_TRANSLATIONSIMPORT({0},{1},{2},{3},{4})";
                            var lang     = outcometext.Lang;
                            var mid      = outcome.OutcomeId;
                            var mtype    = 9;
                            var text     = outcometext.Name.Replace("{$competitor1}", HomeTeam).Replace("{$competitor2}", AwayTeam).
                                           Replace("{total}", "").Replace("({hcp})", "").Replace("({-hcp})", "");
                            var superid = outcome.MarketId;
                            cnn.Database.ExecuteSqlCommand(spParams.Trim(), lang, mid, mtype, text, superid);
                            SerilogHelper.Debug(string.Format("TRANSLATION outcomes [{0}][{1}][{2}]", outcome.OutcomeId, outcometext.Lang, outcometext.Name));

                            //outcome translate for bet basket text

                            /*spParams = "EXECUTE PROCEDURE BET_TRANSLATIONSIMPORT({0},{1},{2},{3},{4})";
                             * lang = outcometext.Lang;
                             * mid = outcome.OutcomeId;
                             * mtype = 3;
                             * //text = outcometext.Name.Replace("{$competitor1}", HomeTeam).Replace("{$competitor2}", AwayTeam).Replace("{total}","").Replace("({+hcp})","");
                             * text = outcometext.Name;
                             * superid = outcome.MarketId;
                             * cnn.Database.ExecuteSqlCommand(spParams.Trim(), lang, mid, mtype, text, superid);
                             */
                        }
                        dbContextTransaction.Commit();
                    }
                }
            }
        }
示例#9
0
 public UtcHelperTests()
 {
     utcHelper = new UtcHelper();
 }
示例#10
0
        public PurchaseOrderBillPageViewModel(INavigationService navigationService,
                                              IProductService productService,
                                              IUserService userService,
                                              ITerminalService terminalService,
                                              IWareHousesService wareHousesService,
                                              IAccountingService accountingService,
                                              IPurchaseBillService purchaseBillService,
                                              IManufacturerService manufacturerService,
                                              IMicrophoneService microphoneService,
                                              IDialogService dialogService
                                              ) : base(navigationService, productService, terminalService, userService, wareHousesService, accountingService, dialogService)
        {
            Title = "采购单";

            _purchaseBillService = purchaseBillService;
            _manufacturerService = manufacturerService;

            _microphoneService = microphoneService;


            InitBill();


            //验证
            var valid_IsReversed     = this.ValidationRule(x => x.Bill.ReversedStatus, _isBool, "已红冲单据不能操作");
            var valid_IsAudited      = this.ValidationRule(x => x.Bill.AuditedStatus, _isBool, "已审核单据不能操作");
            var valid_ManufacturerId = this.ValidationRule(x => x.Bill.ManufacturerId, _isZero, "供应商未指定");
            var valid_WareHouseId    = this.ValidationRule(x => x.Bill.WareHouseId, _isZero, "仓库未指定");
            var valid_ProductCount   = this.ValidationRule(x => x.Bill.Items.Count, _isZero, "请添加商品项目");
            var valid_SelectesCount  = this.ValidationRule(x => x.PaymentMethods.Selectes.Count, _isZero, "请选择支付方式");


            //初始化
            this.Load = ReactiveCommand.CreateFromTask(() => Task.Run(async() =>
            {
                var whs = await _wareHousesService.GetWareHousesAsync(this.BillType, force: true);
                if (whs != null && whs.FirstOrDefault() != null)
                {
                    var wh = whs.FirstOrDefault();
                    if (Bill.WareHouseId == 0)
                    {
                        WareHouse        = wh;
                        Bill.WareHouseId = wh.Id;
                    }

                    if (string.IsNullOrEmpty(Bill.WareHouseName))
                    {
                        Bill.WareHouseName = wh.Name;
                    }
                }

                var result = await _purchaseBillService.GetInitDataAsync(calToken: new System.Threading.CancellationToken());
                if (result != null)
                {
                    var defaultAccs = result.PurchaseBillAccountings.Select(s => new AccountingModel()
                    {
                        Default              = true,
                        AccountingOptionId   = s.AccountingOptionId,
                        AccountingOptionName = s.AccountingOptionName,
                        AccountCodeTypeId    = s.AccountCodeTypeId,
                        Name = s.Name
                    }).ToList();

                    PaymentMethods.Selectes = new ObservableCollection <AccountingModel>(defaultAccs);
                }
            }));

            //提交单据
            this.SubmitDataCommand = ReactiveCommand.CreateFromTask <object, Unit>(async _ =>
            {
                //await this.Access(AccessGranularityEnum.PurchaseBillsSave);

                return(await this.Access(AccessGranularityEnum.PurchaseBillsSave, async() =>
                {
                    if (this.Bill.ReversedStatus)
                    {
                        _dialogService.ShortAlert("已红冲单据不能操作");
                        return Unit.Default;
                    }

                    if (this.Bill.AuditedStatus)
                    {
                        _dialogService.ShortAlert("已审核单据不能操作");
                        return Unit.Default;
                    }

                    var dateTime = UtcHelper.ConvertDateTimeInt(DateTime.Now.ToUniversalTime());

                    if (Bill.BusinessUserId == 0)
                    {
                        Bill.BusinessUserId = Settings.UserId;
                    }

                    var postMData = new PurchaseItemUpdateModel()
                    {
                        BillNumber = this.Bill.BillNumber,
                        //供应商
                        ManufacturerId = Bill.ManufacturerId,
                        //业务员
                        BusinessUserId = Bill.BusinessUserId,
                        //仓库
                        WareHouseId = Bill.WareHouseId,
                        //交易日期
                        //TransactionDate = DateTime.Now,
                        TransactionDate = dateTime,
                        //按最小单位采购
                        IsMinUnitPurchase = true,
                        //备注
                        Remark = Bill.Remark,
                        //优惠金额
                        PreferentialAmount = Bill.PreferentialAmount,
                        //优惠后金额
                        PreferentialEndAmount = Bill.SumAmount - Bill.PreferentialAmount,
                        //欠款金额
                        OweCash = Bill.OweCash,
                        //商品项目(保存量大于零的商品)
                        Items = Bill.Items?.Where(i => i.Quantity > 0).ToList(),
                        //收款账户
                        Accounting = PaymentMethods.Selectes.Select(a =>
                        {
                            return new AccountMaping()
                            {
                                AccountingOptionId = a.AccountingOptionId,
                                CollectionAmount = a.CollectionAmount,
                                Name = a.Name,
                                BillId = 0,
                            };
                        }).ToList()
                    };

                    return await SubmitAsync(postMData, Bill.Id, _purchaseBillService.CreateOrUpdateAsync, (result) =>
                    {
                        Bill = new PurchaseBillModel();
                    }, token: new System.Threading.CancellationToken());
                }));
            },
                                                                                   this.IsValid());

            //存储记录
            this.SaveCommand = ReactiveCommand.Create <object>(async e =>
            {
                var c1 = this.Bill.ManufacturerId != 0 && this.Bill.ManufacturerId != (Settings.PurchaseBill?.ManufacturerId ?? 0);
                var c3 = this.Bill.WareHouseId != 0 && this.Bill.WareHouseId != (Settings.PurchaseBill?.WareHouseId ?? 0);
                var c4 = this.Bill.Items?.Count != (Settings.PurchaseBill?.Items?.Count ?? 0);
                if (!this.Bill.AuditedStatus && (c1 || c3 || c4))
                {
                    if (!this.Bill.AuditedStatus && !this.Bill.IsSubmitBill)
                    {
                        var ok = await _dialogService.ShowConfirmAsync("你是否要保存单据?", "提示", "确定", "取消");
                        if (ok)
                        {
                            Settings.PurchaseBill = this.Bill;
                        }
                        else
                        {
                            await _navigationService.GoBackAsync();
                        }
                    }
                }
                else
                {
                    await _navigationService.GoBackAsync();
                }
            });

            //商品编辑
            this.ItemSelectedCommand = ReactiveCommand.Create <CollectionView>(async e =>
            {
                if (this.Bill.ReversedStatus)
                {
                    _dialogService.ShortAlert("已红冲单据不能操作");
                    return;
                }

                if (this.Bill.AuditedStatus)
                {
                    _dialogService.ShortAlert("已审核单据不能操作");
                    return;
                }

                if (this.Bill.IsSubmitBill)
                {
                    _dialogService.ShortAlert("已提交的单据不能编辑");
                    return;
                }

                if (e.SelectedItem != null)
                {
                    var item = Selecter;
                    if (item != null)
                    {
                        var product = ProductSeries.Select(p => p).Where(p => p.Id == item.ProductId).FirstOrDefault();
                        if (product != null)
                        {
                            product.UnitId   = item.UnitId;
                            product.Quantity = item.Quantity;
                            product.Price    = item.Price;
                            product.Amount   = item.Amount;
                            product.Remark   = item.Remark;
                            product.Subtotal = item.Subtotal;
                            product.UnitName = item.UnitName;
                            product.GUID     = item.GUID;
                            if (item.BigUnitId > 0)
                            {
                                product.bigOption.Name        = item.UnitName;
                                product.BigPriceUnit.Quantity = item.Quantity;
                                product.BigPriceUnit.UnitId   = item.BigUnitId ?? 0;
                                product.BigPriceUnit.Amount   = item.Amount;
                                product.BigPriceUnit.Remark   = item.Remark;
                            }

                            if (item.SmallUnitId > 0)
                            {
                                product.bigOption.Name          = item.UnitName;
                                product.SmallPriceUnit.Quantity = item.Quantity;
                                product.SmallPriceUnit.UnitId   = item.SmallUnitId ?? 0;
                                product.SmallPriceUnit.Amount   = item.Amount;
                                product.SmallPriceUnit.Remark   = item.Remark;
                            }

                            await this.NavigateAsync("EditProductPage", ("Product", product), ("Reference", PageName), ("Item", item), ("WareHouse", WareHouse));
                        }
                    }
                }
            });

            //添加商品
            this.AddProductCommand = ReactiveCommand.Create <object>(async e =>
            {
                if (!valid_IsAudited.IsValid)
                {
                    _dialogService.ShortAlert("已审核单据不能操作!");
                    return;
                }

                if (!valid_ManufacturerId.IsValid)
                {
                    _dialogService.ShortAlert("请选择供应商!");
                    ((ICommand)ManufacturerSelected)?.Execute(null);
                    return;
                }

                if (!valid_WareHouseId.IsValid || WareHouse == null)
                {
                    _dialogService.ShortAlert("请选择仓库!");
                    ((ICommand)StockSelected)?.Execute(null);
                    return;
                }

                await this.NavigateAsync("SelectProductPage", ("Reference", this.PageName),
                                         ("WareHouse", WareHouse),
                                         ("ManufacturerId", Bill.ManufacturerId),
                                         ("SerchKey", Filter.SerchKey));
            });

            //审核
            this.AuditingDataCommand = ReactiveCommand.CreateFromTask <object>(async _ =>
            {
                //是否具有审核权限
                await this.Access(AccessGranularityEnum.PurchaseBillsApproved);
                await SubmitAsync(Bill.Id, _purchaseBillService.AuditingAsync, async(result) =>
                {
                    //红冲审核水印
                    this.Bill.AuditedStatus = true;

                    var _conn = App.Resolve <ILiteDbService <MessageInfo> >();
                    var ms    = await _conn.Table.FindByIdAsync(SelecterMessage.Id);
                    if (ms != null)
                    {
                        ms.IsRead = true;
                        await _conn.UpsertAsync(ms);
                    }
                });
            }, this.WhenAny(x => x.Bill.Id, (x) => x.GetValue() > 0));

            //启用麦克风
            this.WhenAnyValue(x => x.EnableMicrophone)
            .Subscribe(async x =>
            {
                var micAccessGranted = await _microphoneService.GetPermissionsAsync();
                if (!micAccessGranted)
                {
                    this.Alert("请打开麦克风");
                }
            }).DisposeWith(DeactivateWith);
            //匹配声音
            this.RecognitionCommand = ReactiveCommand.Create(() =>
            {
                if (!valid_ManufacturerId.IsValid)
                {
                    _dialogService.ShortAlert("请选择供应商!");
                    return;
                }

                if (!valid_WareHouseId.IsValid)
                {
                    _dialogService.ShortAlert("请选择仓库!");
                    return;
                }

                RecognitionSpeech((key) =>
                {
                    Filter.SerchKey = key;
                    ((ICommand)this.AddProductCommand)?.Execute(null);
                });
            });

            //切换语音助手
            this.SpeechCommand = ReactiveCommand.Create(() =>
            {
                if (IsFooterVisible)
                {
                    IsVisible       = true;
                    IsExpanded      = true;
                    IsFooterVisible = false;
                }
                else
                {
                    IsVisible       = false;
                    IsExpanded      = false;
                    IsFooterVisible = true;
                }
            });

            //工具栏打印
            this.PrintCommand = ReactiveCommand.Create(async() =>
            {
                if (Bill.Items.Count == 0)
                {
                    Alert("请添加商品项目");
                    return;
                }
                Bill.BillType = BillTypeEnum.PurchaseBill;
                await SelectPrint(Bill);
            });

            //绑定页面菜单
            _popupMenu = new PopupMenu(this, new Dictionary <MenuEnum, Action <SubMenu, ViewModelBase> >
            {
                //支付方式
                { MenuEnum.PAY, (m, vm) => {
                      if (Bill.SumAmount == 0)
                      {
                          this.Alert("请添加商品项目!"); return;
                      }
                      PaymentMethodBaseModel payments = this.PaymentMethods;
                      SelectPaymentMethods(("PaymentMethods", payments),
                                           ("TBalance", this.TBalance),
                                           ("BillType", this.BillType),
                                           ("Reference", PageName));
                  } },