Beispiel #1
0
        public static BusinessResults GetBusinessResults(MainModel mainModel, bool isForMonth = false)
        {
            BusinessResults model = new BusinessResults();
            model.StartDate = mainModel.StartDate;
            model.EndDate = mainModel.EndDate;

            using (base3Entities db = new base3Entities())
            {
                Start = mainModel.StartTranz;
                End = mainModel.EndTranz;
                StartOriginal = mainModel.StartTranzOriginal;
                EndOriginal = mainModel.EndTranzOriginal;

                if (isForMonth)
                {
                    Start.AddRange(mainModel.EndTranz.Where(_ => _.period < mainModel.StartDate).ToList());
                    End = mainModel.EndTranz.Where(_ => _.period >= mainModel.StartDate && _.period < mainModel.EndDate).ToList();

                    //StartOriginal.AddRange(mainModel.EndTranzOriginal.Where(_ => _.period < mainModel.StartDate).ToList());
                    //EndOriginal = mainModel.EndTranzOriginal.Where(_ => _.period >= mainModel.StartDate && _.period < mainModel.EndDate).ToList();
                }

                ourScr = new List<int>(); // Вытащим ID интересующих нас счетов нас счетов

                decimal _outStart = 0;
                decimal _outEnd = 0;

                #region Оборотные активы

                #region Денежные средства в кассе

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.CashInCashBox1,
                    (int)ScoresForBusinessResults.CashInCashBox2);
                model.CashInCashBoxStart = _outStart;
                model.CashInCashBoxEnd = _outEnd;

                #endregion

                #region Денежные средства на рассчетном счете

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.MoneyInTheBankAccounts1,
                    (int)ScoresForBusinessResults.MoneyInTheBankAccounts2);
                model.MoneyInTheBankAccountsStart = _outStart;
                model.MoneyInTheBankAccountsEnd = _outEnd;

                #endregion
                
                #region Депозиты

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.Deposits);
                model.DepositsStart = _outStart;
                model.DepositsEnd = _outEnd;

                #endregion

                #region Долги клиентов и переплаты

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.DebtsOfCustomersAndOverpayments);
                model.DebtsOfCustomersAndOverpaymentsStart = _outStart;
                model.DebtsOfCustomersAndOverpaymentsEnd = _outEnd;

                #endregion

                #region Сырье и материалы

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.RawAndMaterials);
                model.RawAndMaterialsStart = _outStart;
                model.RawAndMaterialsEnd = _outEnd;

                #endregion

                #region Товары

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.Goods1,
                    (int)ScoresForBusinessResults.Goods2);
                model.GoodsStart = _outStart;
                model.GoodsEnd = _outEnd;

                #endregion

                #region Незавершенное производство

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.UnfinishedProduction);
                model.UnfinishedProductionStart = _outStart;
                model.UnfinishedProductionEnd = _outEnd;

                #endregion

                #region Прочие оборотные активы

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.OtherCurrentAssets1,
                    (int)ScoresForBusinessResults.OtherCurrentAssets2,
                    (int)ScoresForBusinessResults.OtherCurrentAssets3,
                    (int)ScoresForBusinessResults.OtherCurrentAssets4,
                    (int)ScoresForBusinessResults.OtherCurrentAssets5,
                    (int)ScoresForBusinessResults.OtherCurrentAssets6,
                    (int)ScoresForBusinessResults.OtherCurrentAssets7,
                    (int)ScoresForBusinessResults.OtherCurrentAssets8,
                    (int)ScoresForBusinessResults.OtherCurrentAssets9,
                    (int)ScoresForBusinessResults.OtherCurrentAssets10,
                    (int)ScoresForBusinessResults.OtherCurrentAssets11,
                    (int)ScoresForBusinessResults.OtherCurrentAssets12);
                model.OtherCurrentAssetsStart = _outStart;
                model.OtherCurrentAssetsEnd = _outEnd;

                #endregion

                #region Налоговые переплаты / авансы

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.TaxOverpaymentsAndAdvances);
                model.TaxOverpaymentsAndAdvancesStart = _outStart;
                model.TaxOverpaymentsAndAdvancesEnd = _outEnd;

                #endregion

            #endregion
                #region Долгосрочные активы

                    #region Долгосрочная дебиторская задолженность контрагентов

                    Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.CustomerDebts);
                model.CustomerDebtsStart = _outStart;
                model.CustomerDebtsEnd = _outEnd;

                #endregion

                #region Прочие долги клиентов/переплаты

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment1,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment2,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment3,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment4,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment5,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment6,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment7,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment8,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment9,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment10,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment11,
                    (int)ScoresForBusinessResults.OtherDebtsOfClientsAndOverpayment12);
                model.OtherDebtsOfClientsAndOverpaymentStart = _outStart;
                model.OtherDebtsOfClientsAndOverpaymentEnd = _outEnd;

                #endregion

                #region Инвестиции

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.Investments1,
                    (int)ScoresForBusinessResults.Investments2,
                    (int)ScoresForBusinessResults.Investments3);
                model.InvestmentsStart = _outStart;
                model.InvestmentsEnd = _outEnd;

                #endregion

                #region Основные средства

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.FixedAssets);
                model.FixedAssetsStart = _outStart;
                model.FixedAssetsEnd = _outEnd;

                #endregion

                #region Нематериальные активы

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.IntangibleAssets);
                model.IntangibleAssetsStart = _outStart;
                model.IntangibleAssetsEnd = _outEnd;

                #endregion

                #region Отложенные налоговые переплаты/авансы

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.TheDeferredTaxOverpaymentsAndAdvances);
                model.TheDeferredTaxOverpaymentsAndAdvancesStart = _outStart;
                model.TheDeferredTaxOverpaymentsAndAdvancesEnd = _outEnd;

                #endregion

                #endregion

                #region Текущая задолженность

                #region Кредиты сроком до одного года

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.CreditsForOneYear1,
                    (int)ScoresForBusinessResults.CreditsForOneYear2);
                model.CreditsForOneYearStart = _outStart * minusOne;
                model.CreditsForOneYearEnd = _outEnd * minusOne;

                #endregion

                #region Задолженность по КПН/ИПН

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.DebtCitIit);
                model.DebtCitIitStart = _outStart * minusOne;
                model.DebtCitIitEnd = _outEnd * minusOne;

                #endregion

                #region Задолженность по НДС

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.DebtVat);
                model.DebtVatStart = _outStart * minusOne;
                model.DebtVatEnd = _outEnd * minusOne;

                #endregion

                #region Прочая задолженность по налогам

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.OtherTaxesPayable1,
                    (int)ScoresForBusinessResults.OtherTaxesPayable2,
                    (int)ScoresForBusinessResults.OtherTaxesPayable3,
                    (int)ScoresForBusinessResults.OtherTaxesPayable4,
                    (int)ScoresForBusinessResults.OtherTaxesPayable5,
                    (int)ScoresForBusinessResults.OtherTaxesPayable6,
                    (int)ScoresForBusinessResults.OtherTaxesPayable7);
                model.OtherTaxesPayableStart = _outStart * minusOne;
                model.OtherTaxesPayableEnd = _outEnd * minusOne;

                #endregion

                #region Задолжность перед поставщиками

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.PayablesToSuppliersShortTermDebts);
                model.PayablesToSuppliersShortTermDebtsStart = _outStart * minusOne;
                model.PayablesToSuppliersShortTermDebtsEnd = _outEnd * minusOne;

                #endregion

                #region Задолженность перед сотрудниками

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.PayablesToEmployees);
                model.PayablesToEmployeesStart = _outStart * minusOne;
                model.PayablesToEmployeesEnd = _outEnd * minusOne;

                #endregion

                #region Прочая задолженность

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts1,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts2,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts3,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts4,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts5,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts6,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts7,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts8,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts9,
                    (int)ScoresForBusinessResults.OtherDebtsShortTermDebts10);
                model.OtherDebtsShortTermDebtsStart = _outStart * minusOne;
                model.OtherDebtsShortTermDebtsEnd = _outEnd * minusOne;

                #endregion

                #endregion

                #region Долгосрочные долги

                #region Долгосрочные банковские займы

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.CreditsForLongerThanOneYear1,
                    (int)ScoresForBusinessResults.CreditsForLongerThanOneYear2);
                model.CreditsForLongerThanOneYearStart = _outStart * minusOne;
                model.CreditsForLongerThanOneYearEnd = _outEnd * minusOne;

                #endregion

                #region Задолженность перед контрагентами

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.PayablesToSuppliersLongTermDebts);
                model.PayablesToSuppliersLongTermDebtsStart = _outStart * minusOne;
                model.PayablesToSuppliersLongTermDebtsEnd = _outEnd * minusOne;

                #endregion

                #region Отложеннные налоговая задолженность

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.DefferedTaxDebts);
                model.DefferedTaxDebtsStart = _outStart * minusOne;
                model.DefferedTaxDebtsEnd = _outEnd * minusOne;

                #endregion

                #region Прочая задолженность

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.OtherDebtsLongTermDebts1,
                    (int)ScoresForBusinessResults.OtherDebtsLongTermDebts2,
                    (int)ScoresForBusinessResults.OtherDebtsLongTermDebts3,
                    (int)ScoresForBusinessResults.OtherDebtsLongTermDebts4);
                model.OtherDebtsLongTermDebtsStart = _outStart * minusOne;
                model.OtherDebtsLongTermDebtsEnd = _outEnd * minusOne;

                #endregion

                #endregion

                #region Собственный капитал

                #region Уставной капитал

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.AuthorizedCapital1,
                    (int)ScoresForBusinessResults.AuthorizedCapital2);
                model.AuthorizedCapitalStart = _outStart * minusOne;
                model.AuthorizedCapitalEnd = _outEnd * minusOne;

                #endregion

                #region Прочий капитал

                Calculate(out _outStart, out _outEnd,
                    (int)ScoresForBusinessResults.OtherCapital);
                model.OtherCapitalStart = _outStart * minusOne;
                model.OtherCapitalEnd = _outEnd * minusOne;

                #endregion

                #endregion

                #region Итого

                // Сначала считаем пассивые, потом активы

                #region Текущая задолженность

                model.CalculateCurrentDebt();

                #endregion

                #region Долгосрочная задолженность

                model.CalculateLongTermDebt();

                #endregion

                #region Собственный капитал

                model.CalculateOwnCapital();

                #endregion

                #region Оборотные активы

                model.CalculateCirculatingAssets();

                #endregion

                #region Долгосрочные активы

                model.CalculateLongTermAssets();

                #endregion

                #region Итого активов

                model.CalculateTotalAssets();

                #endregion

                #region Итого пассивов

                model.CalculateTotalLiabilities();

                #endregion

                #region Накопленная прибыль/убыток

                model.CalculateAccumulatedProfitAndLoss();
                    //Calculate(out _outStart, out _outEnd,
                    //    (int)ScoresForBusinessResults.AccumulatedProfitAndLoss);
                    //model.AccumulatedProfitAndLossStart = _outStart;
                    //model.AccumulatedProfitAndLossEnd = _outEnd;

                #endregion


                #endregion
                //model.StartDate = mainModel.StartDate.AddYears(mainModel.TimeSpan * -1);
                //model.EndDate = mainModel.EndDate.AddYears(mainModel.TimeSpan * -1);
                return model;
            }
        }
        public static WorkingСapitalBusinessAnalysis GetWorkingСapitalBA(MainModel MainModel)
        {
            var model = new WorkingСapitalBusinessAnalysis();

            model.myMoney = MainModel.BusinessResults.CirculatingAssetsEnd - MainModel.BusinessResults.CurrentDebtEnd;
            model.myCosts = MainModel.BusinessResults.CurrentDebtEnd;

            model.difmyMoney = model.myMoney - MainModel.GeneralBA.PastBisRes.CirculatingAssetsEnd - MainModel.GeneralBA.PastBisRes.CurrentDebtEnd;
            model.difmyMoneyByPercent = (MainModel.GeneralBA.PastBisRes.CirculatingAssetsEnd - MainModel.GeneralBA.PastBisRes.CurrentDebtEnd) != 0 ? 
                model.difmyMoney / (MainModel.GeneralBA.PastBisRes.CirculatingAssetsEnd - MainModel.GeneralBA.PastBisRes.CurrentDebtEnd) * 100 : 0;

            model.difmyCosts = model.myCosts - MainModel.GeneralBA.PastBisRes.CurrentDebtEnd;
            model.difmyCostsByPercent = MainModel.GeneralBA.PastBisRes.CurrentDebtEnd != 0 ? model.difmyCosts / MainModel.GeneralBA.PastBisRes.CurrentDebtEnd * 100 : 0;

            model.stSokDiagram = new Dictionary<string, decimal>();
            var st = ((Month)MainModel.StartDate.Month).ToString() + "," + MainModel.StartDate.AddYears(MainModel.TimeSpan * -1).Year.ToString();
            var en = ((Month)MainModel.EndDate.Month).ToString() + "," + MainModel.EndDate.AddYears(MainModel.TimeSpan * -1).Year.ToString();
            model.stSokDiagram.Add(st , MainModel.BusinessResults.CirculatingAssetsStart - MainModel.BusinessResults.CurrentDebtStart);
            model.stSokDiagram.Add(st + "-" + en, 0);
            model.stSokDiagram.Add(en, model.myMoney);

            model.profit = new Dictionary<string, decimal>();
            model.profit.Add(st, 0);
            model.profit.Add(st + "-" + en, MainModel.GeneralBA.NetProfit);
            model.profit.Add(en, 0);

            model.stDebtsDiagram = new Dictionary<string, decimal>();
            model.stDebtsDiagram.Add(st, MainModel.BusinessResults.CurrentDebtStart);
            model.stDebtsDiagram.Add(st + "-" + en, 0);
            model.stDebtsDiagram.Add(en, MainModel.BusinessResults.CurrentDebtEnd);

            model.turnoverDiagram = new Dictionary<string, decimal>();
            var tr = (from sa in MainModel.Sales.SelectMany(_ => _.Sales)
                      group sa by sa.GroupCode into g
                      select new
                      {
                          code = g.FirstOrDefault().GroupCode,
                          name = g.FirstOrDefault().GroupName,
                          val = (g.FirstOrDefault().CountGoodsSt + g.FirstOrDefault().CountGoodsEnd == 0 
                          ? 1 : g.Sum(_ => _.CostPrise) / (((g.Count() != 0 ? g.FirstOrDefault().CountGoodsSt  + g.FirstOrDefault().CountGoodsEnd : 0)) / 2)) * (MainModel.EndDate - MainModel.StartDate).Days
                      }).OrderByDescending(_ => _.val).ToList();

            var ttC = 3;
            if (tr.Count < 3) ttC = tr.Count;
            for (var i = 0; i < ttC; i++)
                model.turnoverDiagram.Add(tr[i].name, tr[i].val);

            model.turnoverDiagram.Add("Прочее", tr.Sum(_ => _.val) - model.turnoverDiagram.Sum(_ => _.Value));
            DateTime sty = MainModel.StartDate;
            DateTime eny = MainModel.EndDate;
            BusinessResults tmpBR = new BusinessResults();

            model.aveDZDiagram = new Dictionary<string, decimal>();
            model.aveGoodsDiagram = new Dictionary<string, decimal>();
            model.aveMoneyDiagram = new Dictionary<string, decimal>();
            model.aveSalesDiagram = new Dictionary<string, decimal>();
            model.DZ_dzVsKzDiagram = new Dictionary<string, decimal>();
            model.KZ_dzVsKzDiagram = new Dictionary<string, decimal>();
            var isMoreYear = (MainModel.EndDate - MainModel.StartDate).Days > 365;
            foreach (var item in MainModel.Sales)
            {
                MainModel.StartDate = item.Date;
                MainModel.EndDate = item.Date.AddMonths(1);
                // можно оптимизировать это, изначально это считается сразу за весь период, можно в первоначальной загрузке разбить по месяцам,
                // но это только если эта штука нужна будет еще где-то, если только тут, выгоды особой не будет, еще вариант вытаскивать не суммы, 
                // а массивы данных по счетам в массивы данных с датой и на клиенте ворочать, но я думаю это тоже трешак их может быть овер 100 000 по каждому
                tmpBR = GetBusinessResults(MainModel, true);

                var mm =
                 MainModel.IsItQuarter || isMoreYear ? string.Format("{0}, {1}", (Month)item.Date.Month, item.Date.Year) : ((Month)item.Date.Month).ToString();
               
                model.aveDZDiagram.Add(mm, (tmpBR.DebtsOfCustomersAndOverpaymentsStart + tmpBR.DebtsOfCustomersAndOverpaymentsEnd) / 2);
                model.aveGoodsDiagram.Add(mm, (tmpBR.RawAndMaterialsStart + tmpBR.RawAndMaterialsEnd) / 2);
                model.aveMoneyDiagram.Add(mm, (tmpBR.CashInCashBoxStart + tmpBR.MoneyInTheBankAccountsStart + tmpBR.CashInCashBoxEnd + tmpBR.MoneyInTheBankAccountsEnd) / 2);
                model.aveSalesDiagram.Add(mm, item.Sales.Sum(_ => _.SalesWithoutNDS));

                model.KZ_dzVsKzDiagram.Add(mm, (tmpBR.DebtsOfCustomersAndOverpaymentsStart + tmpBR.DebtsOfCustomersAndOverpaymentsEnd) / 2);
                model.DZ_dzVsKzDiagram.Add(mm, (tmpBR.PayablesToSuppliersShortTermDebtsStart + tmpBR.PayablesToSuppliersShortTermDebtsEnd) / 2);
            }

            MainModel.StartDate = sty;
            MainModel.EndDate = eny;


            return model;
        }