Inheritance: IdentifiedEntity
Ejemplo n.º 1
0
 public void ClientRequestUpdated(ClientRequest clientRequest)
 {
     if (OnClientRequestUpdated != null)
     {
         logger.Debug("Запуск обработчика для события [OnClientRequestUpdated] с кол-вом слушателей [{0}]",
             OnClientRequestUpdated.GetInvocationList().Length);
         OnClientRequestUpdated(this, new QueueInstanceEventArgs()
         {
             ClientRequest = Mapper.Map<ClientRequest, DTO.ClientRequest>(clientRequest)
         });
     }
 }
Ejemplo n.º 2
0
 public void AddClientRequest()
 {
     ClientRequest req = new ClientRequest();
     plan.AddClientRequest(req);
 }
Ejemplo n.º 3
0
        private Workplace[] GetCouponWorkplaces(ClientRequest clientRequest)
        {
            QueuePlan queuePlan;

            if (clientRequest.RequestDate == DateTime.Today)
            {
                queuePlan = QueueInstance.TodayQueuePlan;
            }
            else
            {
                queuePlan = new QueuePlan();
                queuePlan.Load(clientRequest.RequestDate);
                queuePlan.Build();
            }

            using (var locker = queuePlan.ReadLock())
            {
                ServiceRenderingMode serviceRenderingMode = clientRequest.Type == ClientRequestType.Early
                                                            ? ServiceRenderingMode.EarlyRequests
                                                            : ServiceRenderingMode.LiveRequests;

                Schedule serviceSchedule = queuePlan.GetServiceSchedule(clientRequest.Service);

                return queuePlan.GetServiceRenderings(serviceSchedule, clientRequest.ServiceStep, serviceRenderingMode)
                      .Where(r => r.Operator.Workplace != null)
                      .Select(r => r.Operator.Workplace)
                      .ToArray();
            }
        }
 public NotDistributedClientRequest(ClientRequest clientRequest, string reason)
 {
     ClientRequest = clientRequest;
     Reason = reason;
 }
Ejemplo n.º 5
0
        public async Task<DTO.ClientRequest> AddLiveClientRequest(Guid clientId, Guid serviceId, bool isPriority, Dictionary<Guid, object> parameters, int subjects)
        {
            return await Task.Run(() =>
            {
                CheckPermission(UserRole.Administrator, AdministratorPermissions.ClientsRequests);

                using (var session = SessionProvider.OpenSession())
                using (var transaction = session.BeginTransaction())
                {
                    Client client = null;

                    if (clientId != Guid.Empty)
                    {
                        client = session.Get<Client>(clientId);
                        if (client == null)
                        {
                            throw new FaultException<ObjectNotFoundFault>(new ObjectNotFoundFault(clientId),
                                string.Format("Клиент [{0}] не найден", clientId));
                        }
                    }

                    var service = session.Get<Service>(serviceId);
                    if (service == null)
                    {
                        throw new FaultException<ObjectNotFoundFault>(new ObjectNotFoundFault(serviceId),
                            string.Format("Услуга [{0}] не найдена", serviceId));
                    }

                    if (!service.IsActive)
                    {
                        throw new FaultException("Выбранная услуга не активна");
                    }

                    if (service.ClientRequire && client == null)
                    {
                        throw new FaultException("Выбранная услуга требует наличие клиента");
                    }

                    var clientRequest = new ClientRequest()
                    {
                        Client = client,
                        Service = service,
                        ServiceStep = service.GetFirstStep(session),
                        Subjects = subjects,
                        IsPriority = client != null && client.VIP
                    };

                    var currentTime = DateTime.Now.TimeOfDay;

                    var todayQueuePlan = QueueInstance.TodayQueuePlan;

                    using (var locker = todayQueuePlan.ReadLock())
                    {
                        var schedule = todayQueuePlan.GetServiceSchedule(service);

                        int count = session.CreateCriteria<ClientRequest>()
                            .Add(Restrictions.Eq("RequestDate", DateTime.Today))
                            .Add(Restrictions.Eq("Client", client))
                            .Add(Restrictions.Eq("Service", service))
                            .SetProjection(Projections.RowCount())
                            .UniqueResult<int>();

                        if (count >= schedule.MaxClientRequests)
                        {
                            throw new FaultException("Достигнуто максимальное кол-во запрос на текущий день");
                        }

#if !DEBUG
                        if (currentTime < schedule.StartTime)
                        {
                            throw new FaultException(string.Format("Время начала оказания услуги наступит в {0}", schedule.StartTime));
                        }
#endif

                        try
                        {
                            var freeTime = todayQueuePlan.GetServiceFreeTime(service, clientRequest.ServiceStep,
                                ClientRequestType.Live, service.IsPlanSubjects ? subjects : 1);
                            var timeIntervals = freeTime.TimeIntervals;
                            if (timeIntervals.Length == 0)
                            {
                                throw new FaultException("Нет свободного времени для оказания услуги");
                            }
                        }
                        catch (Exception exception)
                        {
                            throw new FaultException(exception.Message);
                        }
                    }

                    logger.Info("Добавление нового запроса в план очереди");

                    using (var locker = todayQueuePlan.WriteLock())
                    {
                        clientRequest.Number = ++todayQueuePlan.LastNumber;
                    }

                    clientRequest.RequestDate = DateTime.Today;

                    clientRequest.RequestTime = currentTime.Add(service.ClientCallDelay);
                    clientRequest.IsPriority = isPriority;
                    clientRequest.Type = ClientRequestType.Live;

                    var error = clientRequest.Validate().FirstOrDefault();
                    if (error != null)
                    {
                        throw new FaultException(error.Message);
                    }

                    session.Save(clientRequest);

                    var queueEvent = new ClientRequestEvent()
                    {
                        ClientRequest = clientRequest,
                        Message = string.Format("[{0}] добавил новый запрос клиента в живую очередь [{1}]", currentUser, clientRequest)
                    };

                    session.Save(queueEvent);

                    var defaultConfig = session.Get<DefaultConfig>(ConfigType.Default);
                    if (defaultConfig.IsDebug)
                    {
                        session.Save(new QueuePlanReport()
                        {
                            ClientRequest = clientRequest,
                            Report = string.Join(Environment.NewLine, todayQueuePlan.Report)
                        });
                    }

                    using (var locker = todayQueuePlan.WriteLock())
                    {
                        transaction.Commit();

                        todayQueuePlan.AddClientRequest(clientRequest);
                        todayQueuePlan.Build(currentTime);
                    }

                    QueueInstance.Event(queueEvent);

                    logger.Info("Запрос добавлен в план очереди");

                    return Mapper.Map<ClientRequest, DTO.ClientRequest>(clientRequest);
                }
            });
        }
Ejemplo n.º 6
0
        public async Task<DTO.ClientRequest> AddEarlyClientRequest(Guid clientId, Guid serviceId, DateTime requestDate, TimeSpan requestTime, Dictionary<Guid, object> parameters, int subjects)
        {
            return await Task.Run(() =>
            {
                CheckPermission(UserRole.Administrator, AdministratorPermissions.ClientsRequests);

                using (var session = SessionProvider.OpenSession())
                using (var transaction = session.BeginTransaction())
                {
                    Client client = null;

                    if (clientId != Guid.Empty)
                    {
                        client = session.Get<Client>(clientId);
                        if (client == null)
                        {
                            throw new FaultException<ObjectNotFoundFault>(new ObjectNotFoundFault(clientId),
                                string.Format("Клиент [{0}] не найден", clientId));
                        }
                    }

                    var service = session.Get<Service>(serviceId);
                    if (service == null)
                    {
                        throw new FaultException<ObjectNotFoundFault>(new ObjectNotFoundFault(serviceId),
                            string.Format("Услуга [{0}] не найдена", serviceId));
                    }

                    if (!service.IsActive)
                    {
                        throw new FaultException("Выбранная услуга не активна");
                    }

                    if (service.ClientRequire && client == null)
                    {
                        throw new FaultException("Выбранная услуга требует наличие клиента");
                    }

                    requestDate = requestDate.Date;
                    var isRequestDateToday = requestDate == DateTime.Today;

                    QueuePlan queuePlan;

                    if (isRequestDateToday)
                    {
                        queuePlan = QueueInstance.TodayQueuePlan;
                    }
                    else
                    {
                        if (requestDate - DateTime.Today > TimeSpan.FromDays(service.MaxEarlyDays))
                        {
                            throw new FaultException(string.Format("По указанной услуге запись возможна не более чем за {0} дней", service.MaxEarlyDays));
                        }

                        queuePlan = new QueuePlan();
                        queuePlan.Load(requestDate);
                        queuePlan.Build();
                    }

                    var clientRequest = new ClientRequest()
                    {
                        Client = client,
                        Service = service,
                        ServiceStep = service.GetFirstStep(session),
                        Subjects = subjects
                    };

                    using (var locker = queuePlan.ReadLock())
                    {
                        var schedule = queuePlan.GetServiceSchedule(service);

                        int count = session.CreateCriteria<ClientRequest>()
                            .Add(Restrictions.Eq("RequestDate", requestDate))
                            .Add(Restrictions.Eq("Client", client))
                            .Add(Restrictions.Eq("Service", service))
                            .SetProjection(Projections.RowCount())
                            .UniqueResult<int>();

                        if (count >= schedule.MaxClientRequests)
                        {
                            throw new FaultException("Достигнуто максимальное кол-во запрос на текущий день");
                        }

                        try
                        {
                            var freeTime = queuePlan.GetServiceFreeTime(service, clientRequest.ServiceStep,
                                ClientRequestType.Early, subjects);
                            var timeIntervals = freeTime.TimeIntervals;
                            if (timeIntervals.Length == 0)
                            {
                                throw new FaultException("Нет свободного времени для оказания услуги");
                            }

                            if (!timeIntervals.Contains(requestTime))
                            {
                                throw new FaultException("Выбрано недопустимое время");
                            }
                        }
                        catch (Exception exception)
                        {
                            throw new FaultException(exception.Message);
                        }

                        if (subjects < 1)
                        {
                            throw new FaultException("Количество объектов должно быть больше 0");
                        }
                    }

                    logger.Info("Добавление нового запроса в план очереди");

                    using (var locker = queuePlan.WriteLock())
                    {
                        clientRequest.Number = ++queuePlan.LastNumber;
                    }

                    clientRequest.RequestDate = requestDate;
                    clientRequest.RequestTime = requestTime;
                    clientRequest.Type = ClientRequestType.Early;

                    var error = clientRequest.Validate().FirstOrDefault();
                    if (error != null)
                    {
                        throw new FaultException(error.Message);
                    }

                    session.Save(clientRequest);

                    var queueEvent = new ClientRequestEvent()
                    {
                        ClientRequest = clientRequest,
                        Message = string.Format("[{0}] добавил новый запрос клиента по предварительной записи на дату [{1}] и время [{2}] [{3}]", currentUser, requestDate.ToShortDateString(), requestTime, clientRequest)
                    };

                    session.Save(queueEvent);

                    var defaultConfig = session.Get<DefaultConfig>(ConfigType.Default);
                    if (defaultConfig.IsDebug)
                    {
                        session.Save(new QueuePlanReport()
                        {
                            ClientRequest = clientRequest,
                            Report = string.Join(Environment.NewLine, queuePlan.Report)
                        });
                    }

                    if (isRequestDateToday)
                    {
                        using (var locker = queuePlan.WriteLock())
                        {
                            transaction.Commit();

                            queuePlan.AddClientRequest(clientRequest);
                            queuePlan.Build(DateTime.Now.TimeOfDay);
                        }
                    }
                    else
                    {
                        transaction.Commit();
                    }

                    QueueInstance.Event(queueEvent);

                    logger.Info("Запрос добавлен в план очереди");

                    return Mapper.Map<ClientRequest, DTO.ClientRequest>(clientRequest);
                }
            });
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Запланировать новый запрос клиента
 /// </summary>
 /// <param name="clientRequest"></param>
 /// <returns></returns>
 public void AddClientRequest(ClientRequest clientRequest)
 {
     clientRequests.Add(storage.Put(clientRequest));
 }
Ejemplo n.º 8
0
 public ClientRequestPlan(ClientRequest clientRequest, TimeSpan startTime, TimeSpan finishTime)
 {
     ClientRequest = clientRequest;
     StartTime = startTime;
     FinishTime = finishTime;
 }
Ejemplo n.º 9
0
        public void AddClientRequest(ClientRequest clientRequest, Schedule schedule)
        {
            if (!clientRequest.IsClosed)
            {
                TimeSpan startTime, finishTime;

                var clientInterval = clientRequest.Type == ClientRequestType.Live
                    ? schedule.LiveClientInterval : schedule.EarlyClientInterval;
                clientInterval = TimeSpan.FromTicks(clientInterval.Ticks * clientRequest.Subjects);

                switch (clientRequest.State)
                {
                    case ClientRequestState.Waiting:
                    case ClientRequestState.Redirected:
                    case ClientRequestState.Postponed:
                        startTime = clientRequest.RequestTime;
                        if (startTime < schedule.StartTime)
                        {
                            startTime = schedule.StartTime;
                        }
                        if (startTime < PlanTime)
                        {
                            startTime = PlanTime;
                        }
                        startTime = GetNearTimeInterval(startTime, schedule, clientRequest.Type);
                        finishTime = startTime.Add(clientInterval);
                        break;

                    case ClientRequestState.Calling:
                        startTime = clientRequest.CallingStartTime;
                        finishTime = PlanTime.Add(clientInterval);
                        break;

                    case ClientRequestState.Rendering:
                        startTime = clientRequest.RenderStartTime;
                        finishTime = startTime.Add(clientInterval);
                        if (finishTime < PlanTime)
                        {
                            finishTime = PlanTime;
                        }
                        break;

                    default:
                        throw new Exception(string.Format("Недопустимое состояние для запроса [{0}]", clientRequest));
                }

                ClientRequestPlans.Add(new ClientRequestPlan(clientRequest, startTime, finishTime));
            }
            else if (clientRequest.State == ClientRequestState.Rendered)
            {
                Metrics.DailyWorkload = Metrics.DailyWorkload.Add(clientRequest.RenderFinishTime - clientRequest.RenderStartTime);
            }
        }