public Budget2DataContext CreateContext ()
 {
     var context = new Budget2DataContext(ConfigurationManager.ConnectionStrings["default"].ConnectionString);
     context.CommandTimeout = 600;
     context.DeferredLoadingEnabled = true;
     return context;
 }
        protected override void Send(TrackingRecord record)
        {
            var activityTrackingRecord = record as ActivityTrackingRecord;

            if (activityTrackingRecord == null)
                return;

            var type = GetWorkflowType(_parameters.WorkflowType);
            if (type.StatesToIgnoreInTracking.Count(s => s.Equals(activityTrackingRecord.QualifiedName,StringComparison.InvariantCultureIgnoreCase)) > 0)
                return;

            using (var context = new Budget2DataContext(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
            {
                WorkflowTrackingHistory item = new WorkflowTrackingHistory()
                                                   {
                                                       Id = Guid.NewGuid(),
                                                       TransitionTime = DateTime.Now,
                                                       StateName = activityTrackingRecord.QualifiedName,
                                                       WorkflowId = _parameters.InstanceId,
                                                       WorkflowTypeId = type.Id

                                                   };
                context.WorkflowTrackingHistories.InsertOnSubmit(item);

                context.SubmitChanges();
            }
        }
        private void WritePreHistory(Guid demandId, Budget2DataContext context, WorkflowState initialState,
                                    WorkflowState destinationState, Guid? expectedInitiatorId, WorkflowCommand command, WorkflowState startState)
        {

            if (initialState.Order < startState.Order)
                return;
            var billDemndHistoryItem = new DemandTransitionHistory
            {
                Id = Guid.NewGuid(),
                DemandId = demandId,
                DestinationStateId = destinationState.DbStateId.Value,
                InitialStateId = initialState.DbStateId.Value,
                TransitionExpectedInitiatorId = expectedInitiatorId,
                CommandId = command.Id,
                Comment = string.Empty,
                Description = string.Empty
            };
            context.DemandTransitionHistories.InsertOnSubmit(billDemndHistoryItem);
        }
 private DemandAdjustment GetDemandAdjustment(Budget2DataContext context, Guid demandAdjustmentUid)
 {
     return context.DemandAdjustments.First(p => p.Id == demandAdjustmentUid);
 }
 private List<WorkflowSighting> GetSightings (Guid instanceId, Guid initiatorId,  SightingType type, Budget2DataContext context)
 {
     return
         context.WorkflowSightings.Where(
             p => p.SighterId == initiatorId && p.EntityId == instanceId && p.SightingType ==
                  type.Id).ToList();
     
 }
        private void SavePaymentPlan(Budget2DataContext context, Guid budgetVersionId, IEnumerable<PaymentPlanItem> paymentPlanItems, Guid contractId)
        {
            foreach (var paymentPlanItem in paymentPlanItems)
            {

                var currPaymentPlanItem = new ContractMoney()
                                              {
                                                  Id = Guid.NewGuid(),
                                                  Number = paymentPlanItem.Prefix,
                                                  NumberId = paymentPlanItem.Number,
                                                  ContractId = contractId,
                                                  ExternalId = paymentPlanItem.Id
                                              };

                context.ContractMoneys.InsertOnSubmit(currPaymentPlanItem);



                if (paymentPlanItem.Date == DateTime.MinValue)
                    throw new Exception(string.Format("Значение поля PaymentPlanItem.Date ({0}) некорректно.", paymentPlanItem.Date));

                currPaymentPlanItem.Date = paymentPlanItem.Date;
                currPaymentPlanItem.MonthId = (byte)paymentPlanItem.Date.Month;
                currPaymentPlanItem.Year = paymentPlanItem.Date.Year;
                currPaymentPlanItem.DateFrom = paymentPlanItem.DateFrom;
                currPaymentPlanItem.DateTo = paymentPlanItem.DateTo;
                currPaymentPlanItem.Comment = paymentPlanItem.Comment;
                currPaymentPlanItem.ConditionPayment = paymentPlanItem.PaymentTerms;
                currPaymentPlanItem.Sum = paymentPlanItem.Amount;
                currPaymentPlanItem.ExternalFromEmployeeId = paymentPlanItem.FromEmployee;
                currPaymentPlanItem.ExternaToEmployeeId = paymentPlanItem.ToEmployee;
                currPaymentPlanItem.PaidState = paymentPlanItem.FactPay;

                currPaymentPlanItem.FromCounteragentId =
                        (from c in context.Counteragents
                         where c.Number == paymentPlanItem.FromEmployee && c.BudgetVersionId == budgetVersionId && !c.IsDeleted && !c.IsPotential
                         select new Nullable<Guid>(c.Id)).FirstOrDefault();

                currPaymentPlanItem.ToCounteragentId =
                       (from c in context.Counteragents
                        where c.Number == paymentPlanItem.ToEmployee && c.BudgetVersionId == budgetVersionId && !c.IsDeleted && !c.IsPotential
                        select new Nullable<Guid>(c.Id)).FirstOrDefault();

                Logger.Log.DebugFormat("План платежей {0} обновлен (Id={1}).", currPaymentPlanItem.NumberId, currPaymentPlanItem.Id);
            }
        }
        private void UploadPaymentPlan(Budget2DataContext context, Guid budgetVersionId, API.Interface.DataContracts.Contract contract, Guid parentContractId, IEnumerable<PaymentPlanItem> paymentPlan)
        {
            var contractMoneyList =
                context.ContractMoneys.Where(p => p.ContractId == parentContractId).ToList();

            context.ContractMoneys.DeleteAllOnSubmit(contractMoneyList);

            if (paymentPlan != null)
                SavePaymentPlan(context, budgetVersionId, paymentPlan, parentContractId);
        }
 private List<Guid> GetLimitManagers(Budget2DataContext context, Guid billDemandUid)
 {
     return context.BillDemands.Single(p => p.Id == billDemandUid).BillDemandDistributions.Where(
         p =>
         p.DemandId.HasValue && p.Demand.LimitId.HasValue &&
         p.Demand.Limit.ManagerId.HasValue).Select(
             p => p.Demand.Limit.ManagerId.Value).Distinct().ToList();
 }
 private List<LimitSighter> GetLimitManagerSightersOperative (Budget2DataContext context, BillDemand billDemand)
 {
     return  billDemand.BillDemandDistributions.Where(
           p =>
           p.DemandId.HasValue && p.Demand.ExecutorStructId.HasValue).Select(
               p =>
               new LimitSighter { LimitId = p.Demand.ExecutorStructId.Value, SighterId = null }).
           Distinct().ToList();
 }
 private Demand GetDemand(Budget2DataContext context, Guid demandId)
 {
     var demand = context.Demands.SingleOrDefault(p => p.Id == demandId);
     return demand;
 }
 private bool CheckSendToAgreementStructDivision(Guid demandUid, Budget2DataContext context)
 {
    return context.Demands.Count(
         d =>
         d.Id == demandUid &&
         ((d.CostArticle != null && d.CostArticle.AlwaysConfirmInGO && d.Filial.Code != SettingsService.HeadFilialCode) ||
          (d.AuthorCFO != null && d.AuthorCFO.Filial != null &&
           d.AuthorCFO.Filial.Code == SettingsService.HeadFilialCode && d.Filial.Code != SettingsService.HeadFilialCode))) > 0;
 }
 private bool CheckInitiatorIsAgreementStructDivision(Guid demandUid, Budget2DataContext context)
 {
     return
                 context.Demands.Count(
                     p =>
                     p.Id == demandUid && p.AuthorId.HasValue &&
                     p.Author.Employees.First(e => e.BudgetId == p.BudgetVersion.BudgetId).StructDivisionId == p.AgreementCfo) > 0;
 }
 private Guid? GetIdentityDivisionId(Budget2DataContext context, ServiceIdentity identity, Guid budgetId)
 {
     var employee =
         context.Employees.FirstOrDefault(p => p.SecurityTrusteeId == identity.Id && p.BudgetId == budgetId);
     return employee == null ? null : employee.StructDivisionId;
 }
 private List<LimitSighting> GetCurrentSighters(Budget2DataContext context, Guid billDemandUid, SightingType sightingType)
 {
     return context.WorkflowSightings.Where(
         p =>
         p.EntityId == billDemandUid &&
         p.SightingType == sightingType.Id).Select(
             p => new LimitSighting { LimitId = p.ItemId, SighterId = p.SighterId, InitiatorId = p.InitiatorId, SightingTime = p.SightingTime })
         .Distinct().ToList();
 }
        private static void CreateNewCurrencyRate(Budget2DataContext context, API.Interface.DataContracts.CurrencyRate currencyRate, Currency currency)
        {
            var newCurrRate = new CurrencyRate
                                           {
                                               CurrencyId = currency.Id,
                                               RateDate = currencyRate.RevaluationDate
                                           };

            newCurrRate.Rate = currencyRate.Measure == 0 ? (decimal)0 : currencyRate.Rate / currencyRate.Measure;
            newCurrRate.RevRate = newCurrRate.Rate == 0 ? 0 : 1/newCurrRate.Rate;
            
            context.CurrencyRates.InsertOnSubmit(newCurrRate);
        }
 private List<LimitSighter> GetLimitExecutorSighters(Budget2DataContext context, Guid billDemandUid)
 {
     return context.BillDemands.Single(p => p.Id == billDemandUid).BillDemandDistributions.Where(
       p =>
       p.DemandId.HasValue && p.Demand.LimitId.HasValue &&
       p.Demand.Limit.ExecutorId.HasValue).Select(
           p => new LimitSighter { LimitId = p.Demand.LimitId.Value, SighterId = p.Demand.Limit.ExecutorId.Value }).Distinct().ToList();
 }
        private static void CreateCurrency(Budget2DataContext context, ICollection<Currency> ccList, string currencyName, string currencyISOCode, bool isBase)
        {
            var currency = ccList.FirstOrDefault(curr => curr.Code == currencyISOCode);
            if (currency == null)
            {   
                if (isBase)
                {
                    int count = ccList.Where(curr => curr.IsBase).Count();
                    if (count > 0)
                    {
                        Logger.Log.ErrorFormat("Валюта {0} - {1} не может быть создана в качестве базовой.", currencyISOCode, currencyName);
                        return;
                    }
                }

                var newCurrency = new Currency
                                   {
                                       Id = Guid.NewGuid(),
                                       Name =
                                           !string.IsNullOrEmpty(currencyName)
                                               ? currencyName
                                               : currencyISOCode,
                                       Code = currencyISOCode,
                                       IsBase = isBase,
                                       IsDeleted = false
                                   };

                ccList.Add(newCurrency);
                context.Currencies.InsertOnSubmit(newCurrency);

                Logger.Log.DebugFormat("{3} {0} - {1} добавлена. ID={2}.",
                    newCurrency.Code, newCurrency.Name, newCurrency.Id,
                    newCurrency.IsBase ? "Базовая валюта" : "Валюта");
            }
            else if (currency.Name != currencyName || currency.IsBase != isBase || currency.IsDeleted)
            {
                UpdateCurrency(context, ccList, currency, currencyISOCode, currencyName, isBase);
            }
        }
        private List<LimitSighter> GetLimitManagerSighters(Budget2DataContext context, Guid billDemandUid)
        {
            return context.BillDemands.Single(p => p.Id == billDemandUid).BillDemandDistributions.Where(
                    p =>
                    p.DemandId.HasValue && p.Demand.LimitId.HasValue &&
                    p.Demand.Limit.ManagerId.HasValue).Select(
                        p =>
                        new LimitSighter { LimitId = p.Demand.LimitId.Value, SighterId = p.Demand.Limit.ManagerId.Value }).
                    Distinct().ToList();
            //var bd = context.BillDemands.Single(p => p.Id == billDemandUid);
            //if (bd.BudgetPartId < 1)
            //    return bd.BillDemandDistributions.Where(
            //        p =>
            //        p.DemandId.HasValue && p.Demand.LimitId.HasValue &&
            //        p.Demand.Limit.ManagerId.HasValue).Select(
            //            p =>
            //            new LimitSighter { LimitId = p.Demand.LimitId.Value, SighterId = p.Demand.Limit.ManagerId.Value }).
            //        Distinct().ToList();

            //return bd.BillDemandDistributions.Where(
            //       p =>
            //       p.DemandId.HasValue && p.Demand.ExecutorStructId.HasValue).Select(
            //           p =>
            //           new LimitSighter { LimitId = p.Demand.ExecutorStructId.Value, SighterId = null }).
            //       Distinct().ToList();   
        }
        private static bool UpdateCurrency(Budget2DataContext context, ICollection<Currency> ccList, Currency currency, string currencyISOCode, string currencyName, bool isBase)
        {
            if (isBase && !currency.IsBase)
            {
                int count = ccList.Where(curr => curr.IsBase).Count();
                if (count > 0)
                {
                    Logger.Log.ErrorFormat("Валюта {0} - {1} не может быть указана в качестве базовой.", currencyISOCode, currencyName);
                    return false;
                }
            }

            var upCurrency = (from c in context.Currencies where c.Code == currencyISOCode select c);
            foreach (var cur in upCurrency)
            {
                cur.Name = currencyName;
                cur.IsDeleted = false;
                cur.IsBase = isBase;

                ccList.Remove(currency);
                ccList.Add(cur);

                Logger.Log.DebugFormat("{0} {1} - {2} обновлена. ID={3}",
                isBase ? "Базовая валюта" : "Валюта", currencyISOCode, currencyName, cur.Id);
            }

            return true;
        }
 private BillDemand GetBillDemand(Budget2DataContext context, Guid billDemandUid)
 {
     return context.BillDemands.First(p => p.Id == billDemandUid);
 }
 private static void CreateCurrencyRate(Budget2DataContext context, API.Interface.DataContracts.CurrencyRate currencyRate, Currency currency)
 {
     var crs = context.CurrencyRates.Where(currR => currR.RateDate.Date == currencyRate.RevaluationDate.Date
                                                    && currR.CurrencyId == currency.Id);
     if (crs.Count() > 0)
         UpdateExistingCurrencyRate(currencyRate, crs);
     else
         CreateNewCurrencyRate(context, currencyRate, currency);
 }
 public Guid? GetIdentityStructDivisionId(Guid trusteeId, Guid budgetId, Budget2DataContext context)
 {
       return
             context.Employees.Where(p => p.SecurityTrusteeId == trusteeId && p.BudgetId == budgetId && !p.IsDeleted).Select(p => p.StructDivisionId).FirstOrDefault();
 }
        private void WriteInAccountingPreHistory(Guid billDemandUid, WorkflowState state, Guid? expectedInitiatorId,
                                                 Budget2DataContext context, bool isSkipInAccountingState,
                                                 bool isBillDemandFilialSupportExport)
        {
            if (!isSkipInAccountingState)
            {
                if (isBillDemandFilialSupportExport)
                {
                    WritePreHistory(billDemandUid, context, WorkflowState.BillDemandPostingAccounting,
                                    WorkflowState.BillDemandInAccountingWithExport, expectedInitiatorId,
                                    state);

                    WritePreHistory(billDemandUid, context, WorkflowState.BillDemandInAccountingWithExport,
                                    WorkflowState.BillDemandOnPayment, null, WorkflowCommand.Export, state);
                }
                else
                {
                    WritePreHistory(billDemandUid, context, WorkflowState.BillDemandPostingAccounting,
                                    WorkflowState.BillDemandInAccountingWithExport, expectedInitiatorId,
                                    state);
                }
            }
            else
            {
                WritePreHistory(billDemandUid, context, WorkflowState.BillDemandInitiatorConfirmation,
                                WorkflowState.BillDemandPaid, expectedInitiatorId, state);
            }
        }
 private void UploadSubcontracts(Budget2DataContext context, Guid budgetVersionId, API.Interface.DataContracts.Contract contract, List<Contract> caList, List<Currency> currencyList, Guid parentContractId)
 {
     foreach (var subcontract in contract.Subcontracts)
     {
         Logger.Log.DebugFormat("Обновляем допсоглашение №{0} {1} (Id={2}).", subcontract.Prefix,
                                subcontract.Number, subcontract.Id);
         var parentContractId1 = CreateContract(context, budgetVersionId, subcontract, caList, currencyList,
                                                parentContractId);
         if (!parentContractId1.HasValue)
             continue;
         UploadPaymentPlan(context, budgetVersionId, subcontract, parentContractId1.Value, contract.PaymentPlan.Where(ppi => ppi.DogId == subcontract.Id));
     }
 }
 private Guid? GetInitiatorId(Guid billDemandUid, Budget2DataContext context)
 {
     return context.BillDemands.First(p => p.Id == billDemandUid).AuthorId;
 }
        private Guid? CreateContract(Budget2DataContext context, Guid budgetVersionId, API.Interface.DataContracts.Contract contract, List<Contract> caList, List<Currency> currencyList, Guid? parentContractUid)
        {
            var currContract =
                (from curr in caList where curr.ExternalId == contract.Id && (!parentContractUid.HasValue || curr.ParentId == parentContractUid.Value) select curr).FirstOrDefault();

            if (currContract != null && currContract.IsProtected)
                return null;

            if (currContract == null)
            {
                #region Если контрагент не найден, то создаём его в системе

                currContract = new Contract
                                   {
                                       Id = Guid.NewGuid(),
                                       Number = contract.Prefix,
                                       NumberId = contract.Number,
                                       IsDeleted = false,
                                       BudgetVersionId = budgetVersionId,
                                       FilialId = DefaultFilialKey,
                                       AuthorId = Guid.Empty,
                                       CreateDate = DateTime.Now
                                       
                                   };
                context.Contracts.InsertOnSubmit(currContract);

                #endregion

                Logger.Log.DebugFormat("Контракт {0} {1} добавлен. ID={2}.", currContract.Number, currContract.NumberId, currContract.Id);
            }
            currContract.ChangedByID = Guid.Empty;
            currContract.ChangeDate = DateTime.Now;
            currContract.Number = contract.Prefix;
            currContract.NumberId = contract.Number;
            currContract.Date = contract.Date;
            currContract.DateFrom = contract.DateFrom;
            currContract.DateTo = contract.DateTo;
            currContract.DistributionDate = contract.CompletionDate;
            currContract.Subject = contract.Comment;
            currContract.CurrencySum = contract.Amount;
            currContract.ConditionPayment = contract.PaymentTerms;
            currContract.CurrencyRateCBPercents = (double?)(contract.RateCBRPercents.HasValue ? contract.RateCBRPercents.Value / 100 : (decimal?)null);
            currContract.CurrencyRate = (double?)contract.Rate;
            currContract.StatusId = (byte)0;
            currContract.ExternalId = contract.Id;
            currContract.ExternalCustomerId = contract.CustomerId;
            currContract.ExternalExecutorId = contract.ExecutorId;
            currContract.ExternalCustomerDetails = contract.CustomerDetails;
            currContract.ExternalExecutorDetails = contract.ExecutorDetails;
            currContract.ExternalManager = contract.Manager;
            if (parentContractUid.HasValue)
                currContract.ParentId = parentContractUid.Value;

            currContract.ExecutorCounteragentId =
                (from c in context.Counteragents
                 where c.Number == contract.ExecutorId && c.BudgetVersionId == budgetVersionId && !c.IsDeleted && !c.IsPotential
                 select new Nullable<Guid>(c.Id)).FirstOrDefault();

            currContract.CustomerCounteragentId =
                (from c in context.Counteragents
                 where c.Number == contract.CustomerId && c.BudgetVersionId == budgetVersionId && !c.IsDeleted && !c.IsPotential
                 select new Nullable<Guid>(c.Id)).FirstOrDefault();

            currContract.CurrencyId =
                (from c in currencyList
                 where c.Code == contract.Currency && !c.IsDeleted
                 select new Nullable<Guid>(c.Id)).FirstOrDefault();

            Logger.Log.DebugFormat("Контракт {0} обновлен (Id={1}).", currContract.Name, currContract.Id);

            return currContract.Id;
        }
        private void WritePreHistory(Guid billDemandUid, Budget2DataContext context, WorkflowState initialState,
                                    WorkflowState destinationState, Guid? expectedInitiatorId, WorkflowState startState)
        {
            WritePreHistory(billDemandUid, context, initialState, destinationState, expectedInitiatorId, WorkflowCommand.Sighting, startState);

        }
 private List<BillDemandDistribution> GetBillDemandDistributions (Guid instanceId, Guid initiatorId,  SightingType type, Budget2DataContext context)
 {
     if (type == SightingType.BillDemandLimitManagerSighting)
         return
             context.BillDemandDistributions.Where(
                 p => p.DemandId.HasValue &&
                 p.BillDemandId == instanceId && p.Demand.LimitId.HasValue && p.Demand.Limit.ManagerId.HasValue &&
                 p.Demand.Limit.ManagerId.Value == initiatorId).ToList();
     else if (type == SightingType.BillDemandLimitExecutorSighting)
         return
            context.BillDemandDistributions.Where(
                p => p.DemandId.HasValue &&
                p.BillDemandId == instanceId && p.Demand.LimitId.HasValue && p.Demand.Limit.ExecutorId.HasValue &&
                p.Demand.Limit.ExecutorId.Value == initiatorId).ToList();
     else
     {
         throw new ArgumentException("Неизвестный тип параллельного согласования");
     }
 }
 private DemandAdjustment GetDemandAdjustmentWithAllLimits(Budget2DataContext context, Guid demandAdjustmentUid)
 {
     DataLoadOptions dlo = new DataLoadOptions();
     dlo.LoadWith<DemandAdjustment>(p=>p.SourceDemand);
     dlo.LoadWith<DemandAdjustment>(p => p.TargetDemand);
     dlo.LoadWith<Demand>(p=>p.Limit);
     context.LoadOptions = dlo;
     return GetDemandAdjustment(context, demandAdjustmentUid);
 }