public bool IsCurrentUserAllowedToExecuteCommandInCurrentState(ServiceIdentity identity, WorkflowState state, Guid instanceId)
        {
            if (state == null)
            {
                return ValidateInitiator(identity, instanceId);
            }

            if (state.Type != WorkflowType.DemandAdjustmentWorkflow)
                return false;

            if (state == WorkflowState.DemandAdjustmentDraft)
                return ValidateInitiator(identity, instanceId);

            if (state == WorkflowState.DemandAdjustmentSourceDemandLimitManagerSighting)
                return ValidateSourceDemandLimitManager(identity, instanceId);

            if (state == WorkflowState.DemandAdjustmentSourceDemandLimitExecutorSighting)
                return ValidateSourceDemandLimitExecutor(identity, instanceId);

            if (state == WorkflowState.DemandAdjustmentTargetDemandLimitExecutorSighting)
                return ValidateTargetDemandLimitExecutor(identity, instanceId);

            if (state == WorkflowState.DemandAdjustmentTargetDemandLimitManagerSighting)
                return ValidateTargetDemandLimitManager(identity, instanceId);

            if (state == WorkflowState.DemandAdjustmentUPKZCuratorSighting)
                return AuthorizationService.IsInRole(identity.Id, BudgetRole.Curator);

            if (state == WorkflowState.DemandAdjustmentUPKZHeadSighting)
                return AuthorizationService.IsInRole(identity.Id, BudgetRole.UPKZHead);

            return false;
        }
        public bool IsCommandSupportsInState(WorkflowState state, WorkflowCommandType commandType, Guid instanceId)
        {
            if (state == null)
            {
                if (commandType == WorkflowCommandType.StartProcessing)
                    return true;
                return false;
            }

            if (state.Type != WorkflowType.DemandAdjustmentWorkflow)
                return false;

            if (commandType == WorkflowCommandType.PostingAccounting || commandType == WorkflowCommandType.DenialByTechnicalCauses)
                return false;

            if ((state == WorkflowState.DemandAdjustmentAgreed) || (state == WorkflowState.DemandAdjustmentArchived))
                return false;

            if (commandType == WorkflowCommandType.StartProcessing && state == WorkflowState.DemandAdjustmentDraft)
                return true;

            if ((commandType == WorkflowCommandType.Sighting || commandType == WorkflowCommandType.Denial) && state != WorkflowState.DemandAdjustmentDraft)
                return true;

            return false;
        }
        public void CreateDemandPreHistory(Guid demandUid, WorkflowState state)
        {
            using (var scope = ReadUncommittedSupressedScope)
            {
                using (var context = this.CreateContext())
                {
                    var existingNotUsedItems =
                        context.DemandTransitionHistories.Where(
                            dth =>
                            dth.DemandId == demandUid && !dth.TransitionTime.HasValue &&
                            dth.InitialState.Order >= state.Order).ToList();

                    context.DemandTransitionHistories.DeleteAllOnSubmit(existingNotUsedItems);

                    var demand = GetDemand(context, demandUid);


                    if (CheckInitiatorIsExecutorStructDivision(demandUid, context))
                    {
                        WritePreHistory(demandUid, context, WorkflowState.DemandDraft,
                                        WorkflowState.DemandOPHeadSighting, demand.AuthorId,
                                        WorkflowCommand.StartProcessing, state);
                    }
                    else
                    {
                        WritePreHistory(demandUid, context, WorkflowState.DemandDraft,
                                        WorkflowState.DemandOPExpertSighting, demand.AuthorId,
                                        WorkflowCommand.StartProcessing, state);
                        WritePreHistory(demandUid, context, WorkflowState.DemandOPExpertSighting,
                                        WorkflowState.DemandInitiatorHeadSighting, null, state);
                        WritePreHistory(demandUid, context, WorkflowState.DemandInitiatorHeadSighting,
                                        WorkflowState.DemandOPHeadSighting, null, state);
                    }

                    if (CheckSendToAgreementStructDivision(demandUid, context))
                    {
                        WritePreHistory(demandUid, context, WorkflowState.DemandOPHeadSighting,
                                        WorkflowState.DemandAgreementOPExpertSighting, null, state);
                        WritePreHistory(demandUid, context, WorkflowState.DemandAgreementOPExpertSighting,
                                        WorkflowState.DemandUPKZCuratorSighting, null, state);
                    }
                    else
                    {
                        WritePreHistory(demandUid, context, WorkflowState.DemandOPHeadSighting,
                                        WorkflowState.DemandUPKZCuratorSighting, null, state);
                    }



                    WritePreHistory(demandUid, context, WorkflowState.DemandUPKZCuratorSighting,
                                    WorkflowState.DemandUPKZHeadSighting, null, state);
                    WritePreHistory(demandUid, context, WorkflowState.DemandUPKZHeadSighting, WorkflowState.DemandAgreed,
                                    null, state);

                    context.SubmitChanges();
                }

                scope.Complete();
            }
        }
 public UpdateBillDemandStateParams(WorkflowState initialState, WorkflowState destinationState, WorkflowCommand command, Guid billDemandUid, Guid initiatorId, Guid? impesonatedIdentityId, string comment)
 {
     _initialState = initialState;
     _destinationState = destinationState;
     _command = command;
     _billDemandUid = billDemandUid;
     _initiatorId = initiatorId;
     _impesonatedIdentityId = impesonatedIdentityId;
     _comment = comment;
 }
        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);
        }
        public bool IsCommandSupportsInState(WorkflowState state, WorkflowCommandType commandType, Guid instanceId)
        {
            if (state == null)
            {
                if (commandType == WorkflowCommandType.StartProcessing)
                    return true;
                return false;
            }

            if (state.Type != WorkflowType.DemandWorkflow)
                return false;

            
            if ((commandType == WorkflowCommandType.Sighting) &&
                ((state == WorkflowState.DemandInitiatorHeadSighting) ||
                 (state == WorkflowState.DemandOPExpertSighting) ||
                 (state == WorkflowState.DemandOPHeadSighting) ||
                 (state == WorkflowState.DemandUPKZCuratorSighting) ||
                 (state == WorkflowState.DemandUPKZHeadSighting) ||
                 //(state == WorkflowState.DemandAgreementInitiatorHeadSighting) ||
                 //(state == WorkflowState.DemandAgreementOPHeadSighting) ||
                 (state == WorkflowState.DemandAgreementOPExpertSighting) || (state == WorkflowState.DemandRollbackRequested) 
                )
                )
                return true;

            if ((commandType == WorkflowCommandType.Denial) &&
               ((state == WorkflowState.DemandInitiatorHeadSighting) ||
                (state == WorkflowState.DemandOPExpertSighting) ||
                (state == WorkflowState.DemandOPHeadSighting) ||
                (state == WorkflowState.DemandUPKZCuratorSighting) ||
                (state == WorkflowState.DemandUPKZHeadSighting) ||
                //(state == WorkflowState.DemandAgreementInitiatorHeadSighting) ||
                // (state == WorkflowState.DemandAgreementOPHeadSighting) ||
                 (state == WorkflowState.DemandAgreementOPExpertSighting) || (state == WorkflowState.DemandRollbackRequested) 
               )
               )
                return true;
            if ((commandType == WorkflowCommandType.StartProcessing) && (state == WorkflowState.DemandDraft))
                return true;

            return false;
        }
        public List<WorkflowCommandType> AddAdditionalCommand(ServiceIdentity getCurrentIdentity, IEnumerable<ServiceIdentity> identities, WorkflowState currentState, Guid instanceUid, List<WorkflowCommandType> allowedOperations)
        {
            if (currentState == WorkflowState.DemandDraft || currentState == WorkflowState.DemandAgreed || currentState == WorkflowState.DemandRollbackRequested || currentState == null)
                return allowedOperations;

            if (ValidateInitiatorForRollback(getCurrentIdentity, instanceUid))
                allowedOperations.Add(WorkflowCommandType.Rollback);
            else if (!getCurrentIdentity.IsImpersonated)
            {
                var identity = identities.FirstOrDefault(i => ValidateInitiatorForRollback(i, instanceUid));
                    if (identity != null)
                    {
                        getCurrentIdentity.TryImpersonate(identity.Id);
                        allowedOperations.Add(WorkflowCommandType.Rollback);
                    }

            }

            return allowedOperations;
        }
 private void SendNotifications(WorkflowState state)
 {
     try
     {
         if (state == null)
             return;
         else
             Budget2WorkflowRuntime.BillDemandNotificationService.SendNotificationsForState(WorkflowInstanceId, state);
     }
     catch (Exception ex)
     {
         Logger.Log.ErrorFormat("Произошла ошибка при отправке уведомления по РД. Message = {0}. BilDemandId = {1}", ex.Message, WorkflowInstanceId);
     }
 }
        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);
            }
        }
        public bool IsCommandSupportsInState(WorkflowState state, WorkflowCommandType commandType, Guid instanceId)
        {
            if (state == null)
            {
                if (commandType == WorkflowCommandType.StartProcessing)
                    return true;
                return false;
            }

            if (state.Type != WorkflowType.BillDemandWorkfow)
                return false;

            if ((commandType == WorkflowCommandType.Sighting) &&
                ((state == WorkflowState.BillDemandUPKZCuratorSighting) ||
                 (state == WorkflowState.BillLimitManagerSighting) ||
                 (state == WorkflowState.BillDemandUPKZCntrollerSighting) ||
                 (state == WorkflowState.BillDemandLimitExecutorSighting) ||
                 (state == WorkflowState.BillDemandUPKZHeadSighting) ||
                 (state == WorkflowState.BillDemandHeadInitiatorSighting)
                )
                )
                return true;

            if (((commandType == WorkflowCommandType.Denial) ||
                 (commandType == WorkflowCommandType.DenialByTechnicalCauses)) &&
                (
                    (state == WorkflowState.BillDemandUPKZCuratorSighting) ||
                    (state == WorkflowState.BillLimitManagerSighting) ||
                    (state == WorkflowState.BillDemandLimitExecutorSighting) ||
                     (state == WorkflowState.BillDemandUPKZHeadSighting) ||
                     (state == WorkflowState.BillDemandHeadInitiatorSighting))
                )
                return true;

            if ((commandType == WorkflowCommandType.Denial) &&
                ((state == WorkflowState.BillDemandPostingAccounting) ||
                 (state == WorkflowState.BillDemandUPKZCntrollerSighting) ||
                 (state == WorkflowState.BillDemandDraftForTechnicalDenial)))
                return true;

            if ((commandType == WorkflowCommandType.PostingAccounting) &&
                (state == WorkflowState.BillDemandPostingAccounting))
                return true;

            if ((commandType == WorkflowCommandType.Export) && (state == WorkflowState.BillDemandInAccountingWithExport) && BillDemandBuinessService.IsBillDemandFilialSupportsExport(instanceId))
                return true;

            if ((commandType == WorkflowCommandType.SetPaidStatus || commandType == WorkflowCommandType.SetDenialStatus) && (state == WorkflowState.BillDemandInAccountingWithExport))
                return true;

            if ((commandType == WorkflowCommandType.SetPaidStatus || commandType == WorkflowCommandType.Denial) && state == WorkflowState.BillDemandInitiatorConfirmation)
                return true;

            if ((commandType == WorkflowCommandType.StartProcessing) && (state == WorkflowState.BillDemandDraft || state == WorkflowState.BillDemandDraftForTechnicalDenial))
                return true;

            if (commandType == WorkflowCommandType.CheckStatus && state == WorkflowState.BillDemandOnPayment)
                return true;

            return false;
        }
        private bool AuthorizeAccessAndImpersonateIfNecessary (IEnumerable<ServiceIdentity> identities, IAuthorizationValidator validator, WorkflowState currentState, Guid instanceId)
        {
            var identity = AuthenticationService.GetCurrentIdentity();

            if (validator.IsCurrentUserAllowedToExecuteCommandInCurrentState(identity, currentState, instanceId))
                return true;

            //var deputyId = GetSuitableDeputyId(validator, identity.Id, currentState, instanceId);

            //if (!deputyId.HasValue)
            //    return false;

            //return identity.TryImpersonate(deputyId.Value);

            foreach (var impersonated in identities)
            {
                if (validator.IsCurrentUserAllowedToExecuteCommandInCurrentState(impersonated, currentState, instanceId))
                    return identity.TryImpersonate(impersonated.Id);
            }

            return false;
        }
 public void SendNotificationsForState(Guid billDemandUid, WorkflowState state)
 {
     var billDemand = BillDemandBuinessService.GetBillDemand(billDemandUid);
     Action<BillDemand> action;
     if (_senders.TryGetValue(state, out action))
         action.Invoke(billDemand);
 }
 public void SendNotification(Guid billDemandUid, WorkflowState state)
 {
 }
        private void SendMailsToEmployee(IEnumerable<Employee> employees, BillDemand billDemand, WorkflowState state)
        {
            bool hasErrors = false;
            var errors = new StringBuilder();
            var distinctemployees = employees;//.Distinct();
            foreach (var employee in distinctemployees)
            {
                try
                {
                    SendEmailToEmployee(billDemand, employee, state);
                }
                catch (Exception ex)
                {
                    errors.AppendLine(ex.Message);
                    hasErrors = true;
                }
            }

            if (hasErrors)
                throw new InvalidOperationException(errors.ToString());
        }
        public void UpdateBillDemandState(WorkflowState state, Guid billDemandUid)
        {
            if (!state.DbStateId.HasValue)
                throw new ArgumentException(
                    "Не определено соттветствие состояния Workflow отображаемому состоянию BillDemand", "state");

            using (var scope = ReadUncommittedSupressedScope)
            {
                using (var context = CreateContext())
                {
                    var billDemand = context.BillDemands.SingleOrDefault(p => p.Id == billDemandUid);
                    if (billDemand == null)
                        return;
                    var billDemandState = context.BillDemandStates.SingleOrDefault(p => p.Id == state.DbStateId);
                    if (billDemandState == null)
                        return;
                    billDemand.BillDemandStateId = state.DbStateId.Value;
                    context.SubmitChanges();
                }
                scope.Complete();
            }
        }
        private void WritePreHistory(Guid billDemandUid, Budget2DataContext context, WorkflowState initialState,
                                    WorkflowState destinationState, Guid? expectedInitiatorId, WorkflowState startState)
        {
            WritePreHistory(billDemandUid, context, initialState, destinationState, expectedInitiatorId, WorkflowCommand.Sighting, startState);

        }
        public void UpdateDemandState(WorkflowState state, Guid demandId)
        {
            if (!state.DbStateId.HasValue)
                throw new ArgumentException(
                    "Не определено соттветствие состояния Workflow отображаемому состоянию Demand", "state");

            using (var scope = ReadUncommittedSupressedScope)
            {
                using (var context = CreateContext())
                {
                    Demand demand = GetDemand(context, demandId);
                    if (demand == null)
                        return;
                    var demandState = context.DemandStatusInternals.SingleOrDefault(p => p.Id == state.DbStateId);
                    if (demandState == null)
                        return;
                    demand.InternalStatusId = state.DbStateId.Value;
                    context.SubmitChanges();
                }
                scope.Complete();
            }
        }
        public void UpdateDemandState(WorkflowState initialState, WorkflowState destinationState, WorkflowCommand command, Guid demandId,
                                         Guid initiatorId, string comment)
        {
            if (!initialState.DbStateId.HasValue)
                throw new ArgumentException(
                    "Не определено соттветствие состояния Workflow отображаемому состоянию Demand", "initialState");
            if (!destinationState.DbStateId.HasValue)
                throw new ArgumentException(
                    "Не определено соттветствие состояния Workflow отображаемому состоянию Demand",
                    "destinationState");
            using (var scope = ReadUncommittedSupressedScope)
            {
                using (var context = CreateContext())
                {
                    var demandHistoryItem =
                     context.DemandTransitionHistories.Where(
                         p =>
                         p.DemandId == demandId && p.InitialStateId == initialState.DbStateId.Value && p.DestinationStateId == destinationState.DbStateId.Value
                         && (p.CommandId == command.Id || command.SkipCheckCommandId) && !p.TransitionInitiatorId.HasValue).ToList().FirstOrDefault();

                    if (demandHistoryItem == null)
                    {
                        demandHistoryItem = new DemandTransitionHistory()
                                                {
                                                    Id = Guid.NewGuid(),
                                                    DemandId = demandId,
                                                    DestinationStateId = destinationState.DbStateId.Value,
                                                    InitialStateId = initialState.DbStateId.Value,
                                                    CommandId =
                                                        (command.Id == WorkflowCommand.Unknown.Id
                                                             ? (Guid?) null
                                                             : command.Id),
                                                };
                        context.DemandTransitionHistories.InsertOnSubmit(demandHistoryItem);
                    }
                    demandHistoryItem.TransitionInitiatorId = initiatorId;
                    demandHistoryItem.TransitionTime = DateTime.Now;
                    demandHistoryItem.Comment = comment;
                    var info = WorkflowStateService.GetWorkflowStateInfo(destinationState);
                    demandHistoryItem.Description = WorkflowCommand.GetCommandDescription(command,
                                                                                             info == null
                                                                                                 ? string.Empty
                                                                                                 : info.StateVisibleName);



                    
                    context.SubmitChanges();
                }

                scope.Complete();
            }
        }
        public void CreateBillDemandPreHistory(Guid billDemandUid, WorkflowState state)
        {
            using (var scope = ReadUncommittedSupressedScope)
            {
                using (var context = CreateContext())
                {
                  
                    //удаляем последующие этапы
                    var existingNotUsedItems =
                        context.BillDemandTransitionHistories.Where(
                            bdth => bdth.BillDemandId == billDemandUid && !bdth.TransitionInitiatorId.HasValue).ToList();
                    
                    context.BillDemandTransitionHistories.DeleteAllOnSubmit(existingNotUsedItems.Where(bdth=> bdth.InitialState.Order >= state.Order));

                    foreach (var historyitem in existingNotUsedItems.Where(bdth => bdth.InitialState.Order < state.Order && !bdth.TransitionTime.HasValue))
                        historyitem.TransitionTime = DateTime.Now;

                    Guid? expectedInitiatorId = GetInitiatorId(billDemandUid, context);

                    WritePreHistory(billDemandUid, context, WorkflowState.BillDemandDraft,
                                    WorkflowState.BillDemandUPKZCntrollerSighting, expectedInitiatorId, WorkflowCommand.StartProcessing, state);

                      var billDemand = GetBillDemandWithFilialAndContract(billDemandUid);
                      var isBillDemandFilialSupportExport = this.IsBillDemandSupportExport(billDemand);
                      var isSkipInAccountingState = this.IsBillDemandSkipInAccountingState(billDemand);

                      if (billDemand.BudgetPartId > 0)
                      {
                          if (this.CheckInitiatorHeadMustSign(billDemandUid))
                          {
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandUPKZCntrollerSighting,
                                              WorkflowState.BillDemandHeadInitiatorSighting, null, state);
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandHeadInitiatorSighting,
                                              WorkflowState.BillLimitManagerSighting, null, state);
                          }
                          else
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandUPKZCntrollerSighting,
                                              WorkflowState.BillLimitManagerSighting, null, state);

                          var limitManagerSighters = GetLimitManagerSightersOperative(context, billDemand);

                          if (limitManagerSighters.Count > 0)
                          {
                              foreach (var sighter in limitManagerSighters)
                              {
                                  //Определить руководителя, прописать руководителя
                                  WritePreHistory(billDemandUid, context, WorkflowState.BillLimitManagerSighting,
                                                 isSkipInAccountingState
                                                  ? WorkflowState.BillDemandInitiatorConfirmation
                                                  : WorkflowState.BillDemandPostingAccounting, null, state);
                              }
                          }
                          else
                          {
                              WritePreHistory(billDemandUid, context, WorkflowState.BillLimitManagerSighting,
                                              isSkipInAccountingState
                                                  ? WorkflowState.BillDemandInitiatorConfirmation
                                                  : WorkflowState.BillDemandPostingAccounting, null, state);
                          }



                          WriteInAccountingPreHistory(billDemandUid, state, expectedInitiatorId, context, isSkipInAccountingState, isBillDemandFilialSupportExport);
                      }
                      else
                      {
                          if (this.CheckInitiatorHeadMustSign(billDemandUid))
                          {
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandUPKZCntrollerSighting,
                                              WorkflowState.BillDemandHeadInitiatorSighting, null, state);
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandHeadInitiatorSighting,
                                              WorkflowState.BillDemandLimitExecutorSighting, null, state);
                          }
                          else
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandUPKZCntrollerSighting,
                                              WorkflowState.BillDemandLimitExecutorSighting, null, state);

                          var executors = GetLimitsExecutors(context, billDemandUid);

                          if (executors.Count > 0)
                          {
                              foreach (var executorId in executors)
                              {
                                  WritePreHistory(billDemandUid, context, WorkflowState.BillDemandLimitExecutorSighting,
                                                  WorkflowState.BillLimitManagerSighting, executorId, state);
                              }
                          }
                          else
                          {
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandLimitExecutorSighting,
                                              WorkflowState.BillLimitManagerSighting, null, state);
                          }

                          var managers = GetLimitManagers(context, billDemandUid);

                          if (managers.Count > 0)
                          {
                              foreach (var managerId in managers)
                              {
                                  WritePreHistory(billDemandUid, context, WorkflowState.BillLimitManagerSighting,
                                                  WorkflowState.BillDemandUPKZCuratorSighting, managerId, state);
                              }
                          }
                          else
                          {
                              WritePreHistory(billDemandUid, context, WorkflowState.BillLimitManagerSighting,
                                              WorkflowState.BillDemandUPKZCuratorSighting, null, state);
                          }

                          bool UPKZHeadMustSight = CheckUPKZHeadMustSight(billDemandUid);
                          
                          if (UPKZHeadMustSight)
                          {
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandUPKZCuratorSighting,
                                              WorkflowState.BillDemandUPKZHeadSighting, null, state);

                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandUPKZHeadSighting,
                                              isSkipInAccountingState
                                                  ? WorkflowState.BillDemandInitiatorConfirmation
                                                  : WorkflowState.BillDemandPostingAccounting, null, state);
                          }
                          else
                          {
                              WritePreHistory(billDemandUid, context, WorkflowState.BillDemandUPKZCuratorSighting,
                                              isSkipInAccountingState
                                                  ? WorkflowState.BillDemandInitiatorConfirmation
                                                  : WorkflowState.BillDemandPostingAccounting, null, state);
                          }

                          WriteInAccountingPreHistory(billDemandUid, state, expectedInitiatorId, context, isSkipInAccountingState, isBillDemandFilialSupportExport);

                      }
                    context.SubmitChanges();
                }
                scope.Complete();
            }
        }
 public UpdateBillDemandStateParams(WorkflowState initialState, WorkflowState destinationState, WorkflowCommand command, Guid billDemandUid, Guid initiatorId, Guid? impesonatedIdentityId, string comment, DateTime sightingTime) :
     this(initialState,destinationState,command,billDemandUid,initiatorId,impesonatedIdentityId,comment)
 {
    _sightingTime = sightingTime;
 }
        public void RewriteWorkflow(Guid instanceId, WorkflowState state)
        {

            if (state.Type.Id == WorkflowType.BillDemandWorkfow.Id)
            {
                BillDemandBuinessService.CreateBillDemandPreHistory(instanceId, state);
            }
            else if (state.Type.Id == WorkflowType.DemandWorkflow.Id)
            {
                DemandBusinessService.CreateDemandPreHistory(instanceId, state);
            }
            else if (state.Type.Id == WorkflowType.DemandAdjustmentWorkflow.Id)
            {
                DemandAdjustmentBusinessService.CreateDemandAdjustmentPreHistory(instanceId, state);
            }
        }
 private void WriteTransitionToHistory(WorkflowState current, Guid initiatorId, Guid? impersonatedIdentityId)
 {
     WriteTransitionToHistory(current, initiatorId, impersonatedIdentityId, null);
 }
 private void SendEmailToEmployee(BillDemand bd, Employee employee, WorkflowState state)
 {
     var parameters = GetDefaultParameters(bd);
     parameters.Add("$BILLDEMANDLINK$", string.Format("{0}/BillDemand/?tid={1}", PublicPagesUrl, WorkflowTicketService.CreateTicket(employee.IdentityId, bd.Id, state.WorkflowStateName)));
     EmailService.SendEmail("BILL_DEMAND_NOTIFICATION", parameters, employee.Email);
 }
        private void WriteTransitionToHistory(WorkflowState current, Guid initiatorId, Guid? impersonatedIdentityId, DateTime? sightingTime)
        {
            if (DontWriteToWorkflowHistory)
                return;
            if (PreviousWorkflowState == null || PreviousWorkflowState.WorkflowStateName == WorkflowState.BillDemandDraft.WorkflowStateName)
            {
                Budget2WorkflowRuntime.BillDemandBuinessService.CreateBillDemandPreHistory(WorkflowInstanceId, WorkflowState.BillDemandDraft);
            }
            //Отказ не в черновик - расписываем маршрут
            else if (LastCommand.Id == WorkflowCommand.Denial.Id && current.WorkflowStateName != WorkflowState.BillDemandDraft.WorkflowStateName)
            {
                Budget2WorkflowRuntime.BillDemandBuinessService.CreateBillDemandPreHistory(WorkflowInstanceId, current);
            }

            if (PreviousWorkflowState == null)
            {
                Budget2WorkflowRuntime.BillDemandBuinessService.UpdateBillDemandState(current, WorkflowInstanceId);
                return;
            }

            if (sightingTime.HasValue)
                Budget2WorkflowRuntime.BillDemandBuinessService.UpdateBillDemandState(new UpdateBillDemandStateParams(PreviousWorkflowState, current, LastCommand,
                                                                                 WorkflowInstanceId,
                                                                                 initiatorId, impersonatedIdentityId, Comment, sightingTime.Value));
            else
                Budget2WorkflowRuntime.BillDemandBuinessService.UpdateBillDemandState(
                    new UpdateBillDemandStateParams(PreviousWorkflowState, current, LastCommand,
                                                    WorkflowInstanceId,
                                                    initiatorId, impersonatedIdentityId, Comment));
            Comment = string.Empty;
        }
        public void CheckAndSendMailForState(Guid billDemandUid, WorkflowState state)
        {
            var dataLoadOptions = new DataLoadOptions();
            dataLoadOptions.LoadWith<BillDemand>(d=>d.Author);
            if (state == WorkflowState.BillDemandInAccountingWithExport)
                dataLoadOptions.LoadWith<BillDemand>(d=>d.Filial);

            var billDemand = BillDemandBuinessService.GetBillDemand(billDemandUid,dataLoadOptions);
            Action<BillDemand> action;
            if (_checkings.TryGetValue(state, out action))
                action.Invoke(billDemand);
        }
 private void WriteTransitionToHistory(WorkflowState current)
 {
     WriteTransitionToHistory(current, null);
 }
 public List<WorkflowCommandType> AddAdditionalCommand(ServiceIdentity getCurrentIdentity, IEnumerable<ServiceIdentity> identities, WorkflowState currentState, Guid instanceUid, List<WorkflowCommandType> allowedOperations)
 {
     return allowedOperations;
 }
 private void WriteTransitionToHistory(WorkflowState current, DateTime? sightingTime)
 {
     if (DontWriteToWorkflowHistory)
         return;
     SetStateIfParcelExists();
     WriteTransitionToHistory(current, TransitionInitiator, ImpersonatedIdentityId, sightingTime);
 }
        public bool IsCurrentUserAllowedToExecuteCommandInCurrentState(ServiceIdentity identity, WorkflowState state,
                                                                    Guid instanceId)
        {
            if (state == null)
            {
                return ValidateInitiator(identity, instanceId);
            }

            if (state.Type != WorkflowType.BillDemandWorkfow)
                return false;

            if (state == WorkflowState.BillDemandOnPayment)
                return true;

            if ((state == WorkflowState.BillDemandDraft) || (state == WorkflowState.BillDemandPostingAccounting) || state == WorkflowState.BillDemandDraftForTechnicalDenial || state == WorkflowState.BillDemandInitiatorConfirmation)
                return ValidateInitiator(identity, instanceId);

            if (state == WorkflowState.BillDemandUPKZCntrollerSighting)
                return AuthorizationService.IsInRole(identity.Id, BudgetRole.Controller);

            if (state == WorkflowState.BillDemandUPKZCuratorSighting)
                return AuthorizationService.IsInRole(identity.Id, BudgetRole.Curator);

            if (state == WorkflowState.BillDemandUPKZHeadSighting)
                return AuthorizationService.IsInRole(identity.Id, BudgetRole.UPKZHead);

            if (state == WorkflowState.BillLimitManagerSighting)
                return ValidateLimitManager(identity, instanceId);

            if (state == WorkflowState.BillDemandInAccountingWithExport)
                return  AuthorizationService.IsInRole(identity.Id, BudgetRole.Accountant);

            if (state == WorkflowState.BillDemandLimitExecutorSighting)
                return ValidateLimitExecutor(identity, instanceId);

            if (state == WorkflowState.BillDemandHeadInitiatorSighting)
                return ValidateInitiatorHead(identity, instanceId);

            return false;
        }
 private void CheckBillDemand(WorkflowState state)
 {
     try
     {
         if (state == null)
             Budget2WorkflowRuntime.BillDemandNotificationService.CheckAndSendMail(WorkflowInstanceId);
         else
             Budget2WorkflowRuntime.BillDemandNotificationService.CheckAndSendMailForState(WorkflowInstanceId, state);
     }
     catch (Exception ex)
     {
         Logger.Log.ErrorFormat("Произошла ошибка при проверке РД. Message = {0}. BilDemandId = {1}", ex.Message, WorkflowInstanceId);
     }
 }