Пример #1
0
        public virtual void CallServiceMethod(DataEventArgs de)
        {
            if (ApplicationContext._taskId < int.MaxValue)
            {
                ApplicationContext._taskId++;
            }
            else
            {
                ApplicationContext._taskId = 0;
            }
            de.TaskId = ApplicationContext._taskId;

            try
            {
                if (RunTime == null)
                {
                    RunTime = new ConcurrentDictionary <int, TaskTicks>();
                }
                ClientTask.Enqueue(de);
                RunTime.TryAdd(de.TaskId, new TaskTicks()
                {
                    InitTime = DateTime.Now.Ticks, IntoQueTime = 0, OutQueTime = 0
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public async Task <IActionResult> PutClientTask([FromRoute] int id, [FromBody] ClientTask clientTask)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != clientTask.Id)
            {
                return(BadRequest());
            }

            _context.Entry(clientTask).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ClientTaskExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #3
0
        public async Task <ClientTask> UpdateDone([FromBody] ClientTask task)
        {
            var update = Builders <ClientTask> .Update.Set(u => u.Done, task.Done);

            var client = await GetClient();

            if (client == null)
            {
                throw new Exception("Client not found");
            }

            await DbContext.ClientTasks.UpdateOneAsync(
                t => t.ClientId == client.ClientId && t.TaskId == task.TaskId,
                update);

            return(await DbContext
                   .ClientTasks
                   .Aggregate()
                   .Match(t => t.TaskId == task.TaskId)
                   .Lookup <Aspect, ClientTaskTempResult>("Aspects", "AspectId", "AspectId", "Aspect")
                   .Lookup <AspectType, ClientTaskTempResult>("AspectTypes", "Aspect.AspectTypeId", "AspectTypeId", "AspectType")
                   .Unwind("Aspect")
                   .Unwind("AspectType")
                   .As <ClientTaskResult>()
                   .FirstAsync());
        }
Пример #4
0
 public bool DeleteRelation(string empCode, string devCode)
 {
     try
     {
         using (BemEntities db = new BemEntities())
         {
             int count = 0;
             count = db.Database.ExecuteSqlCommand(string.Format("update DeviceEmployeeRelation set operate={0} where EmpCode='{1}' and DevCode='{2}';", (int)OPERATETYPE.DEBIND, empCode, devCode));
             if (count > 0)
             {
                 ClientTask task = new ClientTask();
                 task.ClientID = devCode;
                 task.TaskID   = Guid.NewGuid().ToString();
                 TaskManager.TaskEnqueue(task);
                 return(true);
             }
         }
         return(false);
     }
     catch (Exception ex)
     {
         LogHelper.Error("删除绑定关系失败", ex);
         return(false);
     }
 }
Пример #5
0
 /// <summary>
 /// 通知某个员工的所有设备,有员工信息更新
 /// </summary>
 /// <param name="empCode"></param>
 public void HasEmpUpdate(string empCode)
 {
     try
     {
         using (BemEntities db = new BemEntities())
         {
             var devList = db.deviceemployeerelation.Where(m => m.EmpCode == empCode);
             if (devList.Count() == 0)
             {
                 return;
             }
             foreach (var dev in devList)
             {
                 ClientTask task = new ClientTask();
                 task.ClientID = dev.DevCode;
                 task.TaskID   = Guid.NewGuid().ToString();
                 TaskManager.TaskEnqueue(task);
             }
         }
     }
     catch (Exception ex)
     {
         LogHelper.Error("更新下发失败", ex);
     }
 }
Пример #6
0
        public bool DeleteRelationByDev(string devCode, List <string> excepts)
        {
            StringBuilder condition = new StringBuilder();

            try
            {
                bool hasCondition = false;


                if (excepts != null && excepts.Count > 0)
                {
                    hasCondition = true;
                    condition.Append("not in (");
                    int index = 0;
                    foreach (var itm in excepts)
                    {
                        if (index == 0)
                        {
                            condition.Append(string.Format("'{0}'", itm));
                        }
                        else
                        {
                            condition.Append(string.Format(",'{0}'", itm));
                        }
                        index++;
                    }
                    condition.Append(")");
                }
                using (BemEntities db = new BemEntities())
                {
                    int count = 0;
                    if (hasCondition == false)
                    {
                        count = db.Database.ExecuteSqlCommand(string.Format("update DeviceEmployeeRelation set operate={0} where DevCode='{1}';", (int)OPERATETYPE.DEBIND, devCode));
                    }
                    else
                    {
                        count = db.Database.ExecuteSqlCommand(string.Format("update DeviceEmployeeRelation set operate={0} where DevCode='{1}' and EmpCode {2};", (int)OPERATETYPE.DEBIND, devCode, condition.ToString()));
                    }

                    if (count > 0)
                    {
                        ClientTask task = new ClientTask();
                        task.ClientID = devCode;
                        task.TaskID   = Guid.NewGuid().ToString();
                        TaskManager.TaskEnqueue(task);
                        return(true);
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                LogHelper.Error("删除绑定关系失败", ex);
                return(false);
            }
        }
Пример #7
0
 private void SendToClient(List <string> devs)
 {
     foreach (string devCode in devs)
     {
         ClientTask task = new ClientTask();
         task.ClientID = devCode;
         task.TaskID   = Guid.NewGuid().ToString();
         TaskManager.TaskEnqueue(task);
     }
 }
        public async Task <IActionResult> PostClientTask([FromBody] ClientTask clientTask)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.ClientTasks.Add(clientTask);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetClientTask", new { id = clientTask.Id }, clientTask));
        }
Пример #9
0
        /// <summary>
        /// функция обновления данных клиента.
        /// </summary>
        /// <param name="clientTask">Задача с данными клиента</param>
        private static void UpdateClientFunction(ClientTask clientTask)
        {
            using (IDBSource dbSource = new MKKContext()) {
                if (clientTask.ClientDB.BirthDate < new DateTime(1920, 1, 1))
                {
                    LogAndThrowException <Exception, EFService1C>(_Logger,
                                                                  "",
                                                                  "Проверьте год рождения клиента {clientLastName} {clientFirstName} {clientSecondName}" +
                                                                  " (код клиента {clientID1C}). Год рождения: {clientBirthDate}./* Метод {methodName}.*/",
                                                                  clientTask.ClientDB.LastName, clientTask.ClientDB.FirstName,
                                                                  clientTask.ClientDB.SecondName, clientTask.ClientDB.Code1C, clientTask.ClientDB.BirthDate,
                                                                  "UpdateClientsInfo");
                }

                ClientDB presentClient = clientTask.Task.ResultAndThrowException();
                ICollection <GuarantorDB> guarantorDB = clientTask.ClientDB.GuarantorDBs;
                clientTask.ClientDB.GuarantorDBs = default;

                if (presentClient == default)
                {
                    dbSource.Clients.Add(clientTask.ClientDB);
                    presentClient = clientTask.ClientDB;
                }
                else
                {
                    dbSource.Entry(presentClient).State = EntityState.Modified;
                }

                presentClient.BirthDate  = clientTask.ClientDB.BirthDate;
                presentClient.FIO        = clientTask.ClientDB.FIO;
                presentClient.FirstName  = clientTask.ClientDB.FirstName;
                presentClient.LastName   = clientTask.ClientDB.LastName;
                presentClient.SecondName = clientTask.ClientDB.SecondName;

                try { dbSource.SaveChanges(); }
                catch (Exception exception) {
                    LogAndThrowException <Exception, EFService1C>(_Logger,
                                                                  "",
                                                                  "Не удалось обновить данные клиента по договору. Клиент {ClientDB}. Ошибка работы" +
                                                                  " с БД./* Метод {methodName}, исключение: {ContextException}*/",
                                                                  new ExLogValue()
                    {
                        LogValue = clientTask.ClientDB,
                        ExValue  = clientTask.ClientDB.Code1C
                    },
                                                                  "UpdateClientsInfo", exception);
                }

                clientTask.ClientDB.GuarantorDBs = guarantorDB;
            }
        }
Пример #10
0
        public async Task <IActionResult> DoneTask([FromBody] ClientTask task)
        {
            var client = await GetClient();

            if (client == null)
            {
                return(NotFound(new ApiNotFoundError("The client has not been found")));
            }

            var result = await Database.FirstAsync <ClientTask>("WHERE client_id = @0 AND task_id = @1", client.ClientId, task.TaskId);

            result.Done = task.Done;
            return(Ok(await Database.UpdateAsync(result)));
        }
Пример #11
0
        public bool Delete(int id)
        {
            ClientTask clientTask = tasksList.FirstOrDefault(t => t.Id == id);

            if (clientTask != null)
            {
                tasksList.Remove(clientTask);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #12
0
        public int Create(ClientTaskDTO clientTaskDTO)
        {
            ClientTask clientTask = new ClientTask();

            clientTask.TaskName      = clientTaskDTO.TaskName;
            clientTask.Description   = clientTaskDTO.Description;
            clientTask.ClientAddress = clientTaskDTO.ClientAddress;
            clientTask.ClientId      = clientTaskDTO.ClientId;
            clientTask.StartTime     = Convert.ToDateTime(clientTaskDTO.StartTime);
            clientTask.EndTime       = Convert.ToDateTime(clientTaskDTO.EndTime);
            clientTask.Id            = tasksList.Max(t => t.Id) + 1;

            tasksList.Add(clientTask);
            return(clientTask.Id);
        }
        async void Button_Clicked(System.Object sender, System.EventArgs e)
        {
            var CellContents = ((Button)sender).BindingContext as RegisterTable;

            //Step1 : Add task title
            var addtasktitle = await DisplayPromptAsync("Question", "What is the task name for  " + CellContents.UserName + " User ");

            //Step 2 : Add total no of tasks
            var addtotaltasks = await DisplayPromptAsync("Question", "How many task assign to  " + CellContents.UserName, keyboard : Keyboard.Numeric);

            int totaltasks = Convert.ToInt32(addtotaltasks);


            //Step 3 : Create a new task for the user
            TasksModel tasksModel = new TasksModel()
            {
                ClientID    = CellContents.UserId,
                TaskId      = Guid.NewGuid(),
                TaskTitle   = addtasktitle,
                clientTasks = new List <ClientTask>()
            };


            //Step 4 : Add tasks to the total no of task
            int i = 1;

            do
            {
                string result = await DisplayPromptAsync("Question", "Add Task " + i + " to " + CellContents.UserName);

                ClientTask clientTask = new ClientTask()
                {
                    TaskName = result
                };

                tasksModel.clientTasks.Add(clientTask);

                i++;
            } while (i <= totaltasks);

            //Step 6 : Push the task to the database

            await ApiServices.ServiceClientInstance.AssignTaskToClient(tasksModel);

            await DisplayAlert("Alert", "Task sucessfully assigned to " + CellContents.UserName, " OK ");

            //Go back to the 1st Screen
        }
Пример #14
0
        public void should_get_tasks_from_server()
        {
            var task = new ClientTask {
                Id = 1
            };
            var tasks = new List <ClientTask> {
                task
            };
            var args = new ListAllTaskArgs();

            service.GetTasks(Arg.Is(args)).Returns(tasks);
            var resultList = client.GetTasks(args);

            host.Close();
            Console.Out.WriteLine(resultList.GetType());
        }
Пример #15
0
        public async Task <IActionResult> PostClientTasks([FromBody] ClientTask task)
        {
            var client = await GetClient();

            if (client == null)
            {
                return(NotFound(new ApiNotFoundError("The client has not been found")));
            }

            task.ClientId = client.ClientId;
            await Database.InsertAsync(task);

            task.Activity = await Database.FirstAsync <Activity>("WHERE activity_id = @0", task.ActivityId);

            return(Ok(task));
        }
Пример #16
0
        public ClientTaskGetByIdDTO GetTasksById(int id)
        {
            ClientTask clientTask = tasksList.Where(task => task.Id == id)
                                    .FirstOrDefault();

            ClientTaskGetByIdDTO clientTaskGetByIdDTO = new ClientTaskGetByIdDTO();

            clientTaskGetByIdDTO.Id            = clientTask.Id;
            clientTaskGetByIdDTO.TaskName      = clientTask.TaskName;
            clientTaskGetByIdDTO.Description   = clientTask.Description;
            clientTaskGetByIdDTO.ClientAddress = clientTask.ClientAddress;
            clientTaskGetByIdDTO.StartTime     = clientTask.StartTime;
            clientTaskGetByIdDTO.EndTime       = clientTask.EndTime;
            clientTaskGetByIdDTO.ClientId      = clientTask.ClientId;

            return(clientTaskGetByIdDTO);
        }
Пример #17
0
        public bool Update(ClientTaskDTO clientTaskDTO)
        {
            ClientTask clientTask = tasksList.FirstOrDefault(t => t.Id == clientTaskDTO.Id);

            if (clientTask != null)
            {
                clientTask.TaskName      = clientTaskDTO.TaskName;
                clientTask.Description   = clientTaskDTO.Description;
                clientTask.ClientAddress = clientTaskDTO.ClientAddress;
                clientTask.StartTime     = Convert.ToDateTime(clientTaskDTO.StartTime);
                clientTask.EndTime       = Convert.ToDateTime(clientTaskDTO.EndTime);
                clientTask.ClientId      = clientTaskDTO.ClientId;

                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #18
0
        public virtual void CallServiceMethod(DataEventArgs de)
        {
            if (ApplicationContext._taskId < int.MaxValue)
            {
                ApplicationContext._taskId++;
            }
            else
            {
                ApplicationContext._taskId = 0;
            }
            de.TaskId = ApplicationContext._taskId;

            try
            {
                ClientTask.Enqueue(de);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Пример #19
0
        public async Task <ClientTask> Post([FromBody] ClientTask task)
        {
            var client = await GetClient();

            if (client == null)
            {
                throw new Exception("Client not found");
            }
            task.ClientId = client.ClientId;
            await DbContext.ClientTasks.InsertOneAsync(task);

            return(await DbContext
                   .ClientTasks
                   .Aggregate()
                   .Match(t => t.TaskId == task.TaskId)
                   .Lookup <Aspect, ClientTaskTempResult>("Aspects", "AspectId", "AspectId", "Aspect")
                   .Lookup <AspectType, ClientTaskTempResult>("AspectTypes", "Aspect.AspectTypeId", "AspectTypeId", "AspectType")
                   .Unwind("Aspect")
                   .Unwind("AspectType")
                   .As <ClientTaskResult>()
                   .FirstAsync());
        }
Пример #20
0
 /// <summary>
 /// 从设备上移除对应员工
 /// </summary>
 /// <param name="empCode"></param>
 /// <returns></returns>
 public bool DeleteRelation(string empCode, OPERATETYPE type)
 {
     try
     {
         using (BemEntities db = new BemEntities())
         {
             var devList = db.deviceemployeerelation.Where(m => m.EmpCode == empCode);
             if (devList.Count() == 0)
             {
                 return(false);
             }
             var           groups   = devList.GroupBy(m => m.DevCode);
             List <string> devCodes = new List <string>();
             foreach (var dev in devList)
             {
                 devCodes.Add(dev.DevCode);
             }
             int count = 0;
             count = db.Database.ExecuteSqlCommand(string.Format("update DeviceEmployeeRelation set operate={0} where EmpCode='{1}';", (int)type, empCode));
             if (count > 0)
             {
                 foreach (string devCode in devCodes)
                 {
                     ClientTask task = new ClientTask();
                     task.ClientID = devCode;
                     task.TaskID   = Guid.NewGuid().ToString();
                     TaskManager.TaskEnqueue(task);
                 }
                 return(true);
             }
         }
         return(false);
     }
     catch (Exception ex)
     {
         LogHelper.Error("删除绑定关系失败", ex);
         return(false);
     }
 }
Пример #21
0
        public void should_get_task_from_repository()
        {
            var spec        = new ListAllServiceSpecification();
            var serviceTask = new ServiceTask {
                Id = 3
            };
            var serviceTasks = new List <ServiceTask> {
                serviceTask
            };
            var expectedTask = new ClientTask {
                Id = 3
            };
            var clientTasks = new List <ClientTask> {
                expectedTask
            };

            repo.GetTasks(spec).Returns(serviceTasks);
            mapper.ConvertToClient(serviceTask).Returns(expectedTask);

            var resultList = todoList.GetTasks(spec);

            resultList.Should().BeEquivalentTo(clientTasks);
        }
Пример #22
0
        public override void Call(object obj, int len)
        {
            DataEventArgs outDea = new DataEventArgs();
            DataEventArgs ea     = (DataEventArgs)obj;

            try
            {
                if (RuningTask == null)
                {
                    RuningTask = new ConcurrentDictionary <int, DataEventArgs>();
                }
                RuningTask.AddOrUpdate(ea.TaskId, ea, (key, value) => value = ea);
                string url = "http://" + Channels[len].IpPoint.Address.ToString() + ":" + (Channels[len].IpPoint.Port + 1);
                Dictionary <string, string> header = new Dictionary <string, string>();
                header.Add("Authorization", "Basic " + this.Authorization);

                int           p                   = ea.ActionParam.LastIndexOf(".");
                List <object> eabinary            = Serializer.ToEntity <List <object> >(ea.Binary);
                string        code                = ea.ActionParam.Substring(p + 1);
                Dictionary <string, string> param = new Dictionary <string, string>();
                param.Add("", Serializer.ToString(eabinary));
                var           result = HttpPost.Post(url + "/" + code, param, header);
                DataEventArgs redata = Serializer.ToEntity <DataEventArgs>(result.Item2);

                if (result.Item1 == HttpStatusCode.OK)
                {
                    ea.StatusCode = StatusCode.Success;
                    dynamic dyjs = Serializer.ToEntity <dynamic>(redata.Json);

                    ea.Json = dyjs.data.ToString();

                    ea.Param = redata.Param;
                    ResultTask.AddOrUpdate(ea.TaskId, ea, (key, value) => value = ea);
                }
                else
                {
                    ea.StatusCode = StatusCode.Error;
                    if (HttpStatusCode.Moved == result.Item1)
                    {
                        ea.Json = result.Item2;
                        RuningTask.TryRemove(ea.TaskId, out outDea);
                        Channels[len].Available = false;
                        ClientTask.Enqueue(ea);
                        CheckServer();
                    }
                    else
                    {
                        ea.Json = result.Item2;
                        ResultTask.AddOrUpdate(ea.TaskId, ea, (key, value) => value = ea);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                _log.Error(ex + ex.StackTrace);
                ea.StatusCode = StatusCode.TimeOut;
                ea.TryTimes++;
                if (ea.TryTimes < 3)
                {
                    RuningTask.TryRemove(ea.TaskId, out outDea);
                    ClientTask.Enqueue(ea);
                    return;
                }

                ResultTask.AddOrUpdate(ea.TaskId, ea, (key, value) => value = ea);
                return;
            }
            finally
            {
                for (int i = 0; i < Channels.Count; i++)
                {
                    if (Channels[i].ActiveHash == ea.TaskId)
                    {
                        Channels[i].ActiveHash = 0;
                    }
                }
                RuningTask.TryRemove(ea.TaskId, out outDea);
            }
        }
Пример #23
0
        public async Task <IActionResult> PutClientTasks([FromBody] ClientTask factor)
        {
            await Database.UpdateAsync(factor);

            return(Ok(factor));
        }
Пример #24
0
        public async void Put([FromBody] ClientTask clientTask)
        {
            await _appContext.ClientTasks.AddAsync(clientTask);

            await _appContext.SaveChangesAsync();
        }
Пример #25
0
        public virtual void Run()
        {
            new Task(runworker =>
            {
                while (!cancelTokenSource.Token.IsCancellationRequested)
                {
                    DataEventArgs e;
                    if (ClientTask.TryPeek(out e))
                    {
                        lock (_timeoutTask)
                        {
                            try
                            {
                                if (_timeoutTask.FirstOrDefault(o => o.TaskId == e.TaskId) != null)
                                {
                                    ClientTask.TryDequeue(out e);
                                    continue;
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }



                        try
                        {
                            ChannelPool channel       = Channels[0];
                            Dictionary <int, int> dic = GetChannel();
                            int k    = dic.Count;
                            int cnum = new Random(unchecked ((int)DateTime.Now.Ticks)).Next(k);
                            int i    = 0;
                            if (dic.TryGetValue(cnum, out i))
                            {
                                channel = Channels[i];
                            }
                            else
                            {
                                int times = 0;
                                while (k == 0 && times < 500)
                                {
                                    dic  = GetChannel();
                                    k    = dic.Count;
                                    cnum = new Random(unchecked ((int)DateTime.Now.Ticks)).Next(Channels.Count);
                                    if (dic.TryGetValue(cnum, out i))
                                    {
                                        channel = Channels[i];
                                        break;
                                    }
                                    Thread.Sleep(2);
                                    times++;
                                }
                                if (times >= 500 && Channels.Count < 50)
                                {
                                    Channels.Add(new ChannelPool {
                                        IpPoint = channel.IpPoint
                                    });
                                    i = Channels.Count - 1;
                                }
                                else
                                {
                                    continue;
                                }
                            }


                            if (ClientTask.TryDequeue(out e))
                            {
                                Channels[i].ActiveHash = 1;
                                Channels[i].RunTimes++;
                                Channels[i].PingActives = DateTime.Now.Ticks;
                                e.CallHashCode          = i;
                                Call(e, i);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            _log.Error(ex);
                        }
                    }
                    else
                    {
                        Thread.Sleep(5);
                    }
                }
            }, TaskCreationOptions.LongRunning).Start();
        }
Пример #26
0
        private IQueryOver <ClientTask> GetClientTaskQuery(IUnitOfWork uow)
        {
            DeliveryPoint            deliveryPointAlias   = null;
            BottlesMovementOperation bottlesMovementAlias = null;
            ClientTask callTaskAlias = null;
            BusinessTaskJournalNode <ClientTask> resultAlias = null;
            Counterparty counterpartyAlias        = null;
            Employee     employeeAlias            = null;
            Phone        deliveryPointPhonesAlias = null;
            Phone        counterpartyPhonesAlias  = null;

            Domain.Orders.Order orderAlias = null;

            var tasksQuery = UoW.Session.QueryOver(() => callTaskAlias)
                             .Left.JoinAlias(() => callTaskAlias.DeliveryPoint, () => deliveryPointAlias);

            switch (FilterViewModel.DateType)
            {
            case TaskFilterDateType.CreationTime:
                tasksQuery.Where(x => x.CreationDate >= FilterViewModel.StartDate.Date)
                .And(x => x.CreationDate <= FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59));
                break;

            case TaskFilterDateType.CompleteTaskDate:
                tasksQuery.Where(x => x.CompleteDate >= FilterViewModel.StartDate.Date)
                .And(x => x.CompleteDate <= FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59));
                break;

            default:
                tasksQuery.Where(x => x.EndActivePeriod >= FilterViewModel.StartDate.Date)
                .And(x => x.EndActivePeriod <= FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59));
                break;
            }

            if (FilterViewModel.Employee != null)
            {
                tasksQuery.Where(x => x.AssignedEmployee == FilterViewModel.Employee);
            }
            else if (FilterViewModel.ShowOnlyWithoutEmployee)
            {
                tasksQuery.Where(x => x.AssignedEmployee == null);
            }

            if (FilterViewModel.HideCompleted)
            {
                tasksQuery.Where(x => !x.IsTaskComplete);
            }

            if (FilterViewModel.DeliveryPointCategory != null)
            {
                tasksQuery.Where(() => deliveryPointAlias.Category == FilterViewModel.DeliveryPointCategory);
            }

            var bottleDebtByAddressQuery = UoW.Session.QueryOver(() => bottlesMovementAlias)
                                           .JoinAlias(() => bottlesMovementAlias.Order, () => orderAlias, NHibernate.SqlCommand.JoinType.LeftOuterJoin)
                                           .Where(() => bottlesMovementAlias.Counterparty.Id == counterpartyAlias.Id)
                                           .And(() => bottlesMovementAlias.DeliveryPoint.Id == deliveryPointAlias.Id || orderAlias.SelfDelivery)
                                           .Select(
                Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int32, "( ?2 - ?1 )"),
                                        NHibernateUtil.Int32, new IProjection[] {
                Projections.Sum(() => bottlesMovementAlias.Returned),
                Projections.Sum(() => bottlesMovementAlias.Delivered)
            }
                                        ));

            var bottleDebtByClientQuery = UoW.Session.QueryOver(() => bottlesMovementAlias)
                                          .Where(() => bottlesMovementAlias.Counterparty.Id == counterpartyAlias.Id)
                                          .Select(
                Projections.SqlFunction(new SQLFunctionTemplate(NHibernateUtil.Int32, "( ?2 - ?1 )"),
                                        NHibernateUtil.Int32, new IProjection[] {
                Projections.Sum(() => bottlesMovementAlias.Returned),
                Projections.Sum(() => bottlesMovementAlias.Delivered)
            }
                                        ));

            tasksQuery.Where(
                GetSearchCriterion(
                    () => callTaskAlias.Id,
                    () => deliveryPointAlias.ShortAddress,
                    () => counterpartyAlias.Name,
                    () => callTaskAlias.TaskState
                    )
                );

            var tasks = tasksQuery
                        .Left.JoinAlias(() => deliveryPointAlias.Phones, () => deliveryPointPhonesAlias)
                        .Left.JoinAlias(() => counterpartyAlias.Phones, () => counterpartyPhonesAlias)
                        .Left.JoinAlias(() => callTaskAlias.Counterparty, () => counterpartyAlias)
                        .Left.JoinAlias(() => callTaskAlias.AssignedEmployee, () => employeeAlias)
                        .SelectList(list => list
                                    .SelectGroup(() => callTaskAlias.Id)
                                    .Select(() => deliveryPointAlias.ShortAddress).WithAlias(() => resultAlias.AddressName)
                                    .Select(() => counterpartyAlias.Name).WithAlias(() => resultAlias.ClientName)
                                    .Select(() => employeeAlias.Name).WithAlias(() => resultAlias.EmployeeName)
                                    .Select(() => employeeAlias.LastName).WithAlias(() => resultAlias.EmployeeLastName)
                                    .Select(() => employeeAlias.Patronymic).WithAlias(() => resultAlias.EmployeePatronymic)
                                    .Select(() => callTaskAlias.EndActivePeriod).WithAlias(() => resultAlias.Deadline)
                                    .Select(() => callTaskAlias.CreationDate).WithAlias(() => resultAlias.CreationDate)
                                    .Select(() => callTaskAlias.Id).WithAlias(() => resultAlias.Id)
                                    .Select(() => callTaskAlias.TaskState).WithAlias(() => resultAlias.TaskStatus)
                                    .Select(() => callTaskAlias.ImportanceDegree).WithAlias(() => resultAlias.ImportanceDegree)
                                    .Select(() => callTaskAlias.IsTaskComplete).WithAlias(() => resultAlias.IsTaskComplete)
                                    .Select(() => callTaskAlias.TareReturn).WithAlias(() => resultAlias.TareReturn)
                                    .Select(Projections.SqlFunction(
                                                new SQLFunctionTemplate(NHibernateUtil.String, "GROUP_CONCAT( CONCAT(?2 , ?1) SEPARATOR ?3 )"),
                                                NHibernateUtil.String,
                                                Projections.Property(() => deliveryPointPhonesAlias.DigitsNumber),
                                                Projections.Constant("+7"),
                                                Projections.Constant("\n"))
                                            ).WithAlias(() => resultAlias.DeliveryPointPhones)
                                    .Select(Projections.SqlFunction(
                                                new SQLFunctionTemplate(NHibernateUtil.String, "GROUP_CONCAT( CONCAT(?2 , ?1) SEPARATOR ?3 )"),
                                                NHibernateUtil.String,
                                                Projections.Property(() => counterpartyPhonesAlias.DigitsNumber),
                                                Projections.Constant("+7"),
                                                Projections.Constant("\n"))
                                            ).WithAlias(() => resultAlias.CounterpartyPhones)
                                    .SelectSubQuery((QueryOver <BottlesMovementOperation>)bottleDebtByAddressQuery).WithAlias(() => resultAlias.DebtByAddress)
                                    .SelectSubQuery((QueryOver <BottlesMovementOperation>)bottleDebtByClientQuery).WithAlias(() => resultAlias.DebtByClient)
                                    )
                        .TransformUsing(Transformers.AliasToBean <BusinessTaskJournalNode <ClientTask> >());

            return(tasks);
        }
Пример #27
0
        private IQueryOver <ClientTask> GetPaymenTaskQuery(IUnitOfWork uow)
        {
            DeliveryPoint deliveryPointAlias = null;
            ClientTask    callTaskAlias      = null;
            BusinessTaskJournalNode <PaymentTask> resultAlias = null;
            Counterparty counterpartyAlias        = null;
            Employee     employeeAlias            = null;
            Phone        deliveryPointPhonesAlias = null;
            Phone        counterpartyPhonesAlias  = null;

            Domain.Orders.Order orderAlias = null;

            var tasksQuery = UoW.Session.QueryOver(() => callTaskAlias)
                             .Left.JoinAlias(() => callTaskAlias.DeliveryPoint, () => deliveryPointAlias);

            switch (FilterViewModel.DateType)
            {
            case TaskFilterDateType.CreationTime:
                tasksQuery.Where(x => x.CreationDate >= FilterViewModel.StartDate.Date)
                .And(x => x.CreationDate <= FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59));
                break;

            case TaskFilterDateType.CompleteTaskDate:
                tasksQuery.Where(x => x.CompleteDate >= FilterViewModel.StartDate.Date)
                .And(x => x.CompleteDate <= FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59));
                break;

            default:
                tasksQuery.Where(x => x.EndActivePeriod >= FilterViewModel.StartDate.Date)
                .And(x => x.EndActivePeriod <= FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59).AddSeconds(59));
                break;
            }

            if (FilterViewModel.Employee != null)
            {
                tasksQuery.Where(x => x.AssignedEmployee == FilterViewModel.Employee);
            }
            else if (FilterViewModel.ShowOnlyWithoutEmployee)
            {
                tasksQuery.Where(x => x.AssignedEmployee == null);
            }

            if (FilterViewModel.HideCompleted)
            {
                tasksQuery.Where(x => !x.IsTaskComplete);
            }

            if (FilterViewModel.DeliveryPointCategory != null)
            {
                tasksQuery.Where(() => deliveryPointAlias.Category == FilterViewModel.DeliveryPointCategory);
            }

            tasksQuery.Where(
                GetSearchCriterion(
                    () => callTaskAlias.Id,
                    () => deliveryPointAlias.ShortAddress,
                    () => counterpartyAlias.Name,
                    () => callTaskAlias.TaskState
                    )
                );

            var tasks = tasksQuery
                        .Left.JoinAlias(() => deliveryPointAlias.Phones, () => deliveryPointPhonesAlias)
                        .Left.JoinAlias(() => counterpartyAlias.Phones, () => counterpartyPhonesAlias)
                        .Left.JoinAlias(() => callTaskAlias.Counterparty, () => counterpartyAlias)
                        .Left.JoinAlias(() => callTaskAlias.AssignedEmployee, () => employeeAlias)
                        .SelectList(list => list
                                    .SelectGroup(() => callTaskAlias.Id)
                                    .Select(() => deliveryPointAlias.ShortAddress).WithAlias(() => resultAlias.AddressName)
                                    .Select(() => counterpartyAlias.Name).WithAlias(() => resultAlias.ClientName)
                                    .Select(() => employeeAlias.Name).WithAlias(() => resultAlias.EmployeeName)
                                    .Select(() => employeeAlias.LastName).WithAlias(() => resultAlias.EmployeeLastName)
                                    .Select(() => employeeAlias.Patronymic).WithAlias(() => resultAlias.EmployeePatronymic)
                                    .Select(() => callTaskAlias.EndActivePeriod).WithAlias(() => resultAlias.Deadline)
                                    .Select(() => callTaskAlias.CreationDate).WithAlias(() => resultAlias.CreationDate)
                                    .Select(() => callTaskAlias.Id).WithAlias(() => resultAlias.Id)
                                    .Select(() => callTaskAlias.TaskState).WithAlias(() => resultAlias.TaskStatus)
                                    .Select(() => callTaskAlias.ImportanceDegree).WithAlias(() => resultAlias.ImportanceDegree)
                                    .Select(() => callTaskAlias.IsTaskComplete).WithAlias(() => resultAlias.IsTaskComplete))
                        .TransformUsing(Transformers.AliasToBean <BusinessTaskJournalNode <PaymentTask> >());

            return(tasks);
        }