Esempio n. 1
0
        public ActionResult Create(string RNAME, List <Product> prod, List <float> quantity, List <bool> selected)
        {
            Recipe NewRecipe = new Recipe {
                RecipeName = RNAME
            };
            int            index     = 0;
            List <Product> _products = (List <Product>)db.Products.GetList();

            foreach (var currentProduct in prod)
            {
                if (selected[index])
                {
                    Ingredient NewIngredient = new Ingredient();// { product = currentProduct, quantity = 5 };
                    NewIngredient.ProductId   = currentProduct.Id;
                    NewIngredient.quantity    = quantity[index];
                    NewIngredient.productName = _products.Find(x => x.Id == currentProduct.Id).Name;

                    NewRecipe.Ingredients.Add(NewIngredient);
                }
                index++;
            }
            if (RNAME != "" && (NewRecipe.Ingredients.Count() != 0))
            {
                db.Recipes.Create(NewRecipe);
                db.Save();
                return(RedirectToAction("Index"));
            }
            else
            {
                return(View(db.Products.GetList()));
            }
        }
        public ActionResult Create(ProductArrival pa)
        {
            try
            {
                Product _prod = db.Products.Get(pa.Ingredient.Id);
                if (_prod != null) //Если уже есть такой продукт
                {                  //пересчет цены товара
                    float newBalance   = _prod.Balance + pa.Ingredient.quantity;
                    float newSellPrice = ((_prod.Balance * _prod.SellPrice) + (pa.Ingredient.quantity * pa.Ingredient.price))
                                         / newBalance;
                    _prod.Balance             = newBalance;
                    _prod.SellPrice           = newSellPrice;
                    pa.Ingredient.productName = _prod.Name;
                    db.Products.Update(_prod);
                    //db.Entry(_prod).State = EntityState.Modified;
                }
                else
                {
                    _prod.MinBalance = 5;
                    _prod.Name       = pa.Ingredient.productName;
                    _prod.Balance    = pa.Ingredient.quantity;
                    db.Products.Create(_prod);
                }
                db.ProductsArrival.Create(pa);
                db.Save();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 3
0
        public ActionResult Create([Bind(Include = "Id,Name,NumberPhone,email")] Client client)
        {
            if (ModelState.IsValid)
            {
                db.Clients.Create(client);
                db.Save();
                return(RedirectToAction("Index"));
            }

            return(View(client));
        }
Esempio n. 4
0
        public ActionResult Buy(Order _ord)
        {
            DishSelect dishSelect = db.DishSelects.Get(db.DishSelects.Count());

            _ord.DishSelectId = dishSelect.Id;
            _ord.DishName     = dishSelect.Name;
            _ord.DishAmount   = dishSelect.DishesAmount;
            _ord.DishPrice    = dishSelect.price;
            var ClientsList = db.Clients.GetList();

            foreach (var client in ClientsList)
            {
                if ((client.email == _ord.Client.email) && (client.NumberPhone == _ord.Client.NumberPhone))
                {
                    _ord.ClientId = client.Id;
                    _ord.Client   = null;
                    break;
                }
            }

            //Вычитаем продукты со склада
            foreach (Ingredient _ingredient in dishSelect.Ingredients)
            {
                Product p = db.Products.Get((int)_ingredient.ProductId);
                p.Balance = p.Balance - (_ingredient.quantity * dishSelect.DishesAmount);
                db.Products.Update(p);
            }
            //Если превышен лимит минимального остатка продуктов => формируем заказ

            foreach (Ingredient _ingredient in dishSelect.Ingredients)
            {
                Product p = db.Products.Get((int)_ingredient.ProductId);
                if (p.Balance < p.MinBalance)
                {
                    _OrderTP.Ingredients.Add(new Ingredient()
                    {
                        price = p.SellPrice, ProductId = p.Id, productName = p.Name, quantity = p.MinBalance
                    });
                    _OrderTP.Message += "Закончился товар - " + p.Name + ", везите ещё;";
                }
            }
            _OrderTP.TotalPrice = GetTotalPrice();
            if (_OrderTP.Ingredients.Count() > 0)
            {
                db.OrdersToProvisioner.Create(_OrderTP);
            }

            db.Orders.Create(_ord);
            db.Save();
            return(RedirectToAction("Index"));
        }
Esempio n. 5
0
        protected override void BeforeSave()
        {
            if (!HasChanges)
            {
                return;
            }

            var operationFrom = Entity.OrganisationCashMovementOperationFrom = Entity.OrganisationCashMovementOperationFrom ?? new OrganisationCashMovementOperation {
                OperationTime = DateTime.Now
            };
            var operationTo = Entity.OrganisationCashMovementOperationTo = Entity.OrganisationCashMovementOperationTo ?? new OrganisationCashMovementOperation {
                OperationTime = DateTime.Now
            };

            operationFrom.Organisation  = Entity.OrganizationFrom;
            operationFrom.Amount        = -Entity.TransferedSum;
            operationFrom.OperationTime = Entity.DocumentDate;

            operationTo.Organisation  = Entity.OrganizationTo;
            operationTo.Amount        = Entity.TransferedSum;
            operationTo.OperationTime = Entity.DocumentDate;

            UoW.Save(operationFrom);
            UoW.Save(operationTo);
        }
Esempio n. 6
0
        private void EmployeeAdvanceOrder(decimal cashInput)         // Метод создаёт расходник выдачи аванса из МЛ и выводит сообщение. @Дима
        {
            string message, ifAdvanceIsBigger;

            Expense cashExpense  = null;
            decimal cashToReturn = Entity.MoneyToReturn - cashInput;

            ifAdvanceIsBigger = (cashToReturn > 0) ? "Сумма для сдачи в кассу" : "Сумма для выдачи из кассы";              // Выбор варианта сообщения. @Дима

            var cashier = EmployeeRepository.GetEmployeeForCurrentUser(UoW);

            if (cashier == null)
            {
                MessageDialogHelper.RunErrorDialog("Ваш пользователь не привязан к действующему сотруднику, вы не можете закрыть МЛ, так как некого указывать в качестве кассира.");
                return;
            }
            Entity.Cashier = cashier;

            message = Entity.EmployeeAdvanceOperation(ref cashExpense, cashInput);               // Создание расходника. @Дима

            if (cashExpense != null)
            {
                UoW.Save(cashExpense);
            }
            cashExpense.UpdateWagesOperations(UoW);
            UoW.Save();

            MessageDialogHelper.RunInfoDialog(String.Format("{0}\n\n{1}: {2:C0}", message, ifAdvanceIsBigger, Math.Abs(cashToReturn)));
        }
Esempio n. 7
0
        public DishesController()
        {
            db = new UoW();

            if (db.Groups.Count() == 0)
            {
                db.Groups.Create(new Group {
                    GroupName = "Блюдо", SubName = "Пицца", FullName = "Блюдо: Пицца"
                });
                db.Groups.Create(new Group {
                    GroupName = "Блюдо", SubName = "Соусы", FullName = "Блюдо: Соусы"
                });
                db.Groups.Create(new Group {
                    GroupName = "Блюдо", SubName = "Салаты", FullName = "Блюдо: Салаты"
                });;
                db.Groups.Create(new Group {
                    GroupName = "Блюдо", SubName = "Горячие блюда", FullName = "Блюдо: Горячие блюда"
                });
                db.Groups.Create(new Group {
                    GroupName = "Напитки", SubName = "Вода газированная и негазированная", FullName = "Напитки: Вода газированная и негазированная"
                });
                db.Groups.Create(new Group {
                    GroupName = "Напитки", SubName = "Соки", FullName = "Напитки: Соки"
                });
                db.Groups.Create(new Group {
                    GroupName = "Готовая продукция", SubName = "Чипсы", FullName = "Готовая продукция: Чипсы"
                });
                db.Groups.Create(new Group {
                    GroupName = "Готовая продукция", SubName = "Сухарики", FullName = "Готовая продукция: Сухарики"
                });

                db.Save();
            }
        }
        public IHttpActionResult Put(int dossierId, int noteId, int id, [FromBody] NoteMedia noteMediaModel)
        {
            var dossier = default(DossierData);

            if (!CurrentUser.TryGetDossier(dossierId, out dossier))
            {
                return(NotFound());
            }

            var note = default(NoteData);

            if (!dossier.TryGetNote(noteId, out note))
            {
                return(NotFound());
            }

            var media = default(NoteMediaData);

            if (!note.TryGetMedia(id, out media))
            {
                return(NotFound());
            }

            var filename = StorageHelper.GetFileNameFromSasUri(media.MediaLocation);

            media.MediaLocation = StorageHelper.GetReadableSasUri(filename, new TimeSpan(0, 2, 0)).AbsoluteUri;
            //media.MediaLocation = StorageHelper.GetReadableSasUri(filename, new TimeSpan(1, 0, 0)).AbsoluteUri;

            UoW.Save();

            var result = Converter.ToNoteMedia(media);

            return(Ok(result));
        }
        public IHttpActionResult Delete(int dossierId, int noteId, int id)
        {
            var dossier = default(DossierData);

            if (!CurrentUser.TryGetDossier(dossierId, out dossier))
            {
                return(NotFound());
            }

            var note = default(NoteData);

            if (!dossier.TryGetNote(noteId, out note))
            {
                return(NotFound());
            }

            var media = default(NoteMediaData);

            if (!note.TryGetMedia(id, out media))
            {
                return(NotFound());
            }

            string location = media.MediaLocation;

            UoW.NoteMediaRepository.Delete(media);
            UoW.Save();

            StorageHelper.RemoveFromStorageByUri(location);

            return(Ok());
        }
        /// <summary>
        /// Creates a new note and adds it to the database.
        /// </summary>
        /// <param name="dossierId">The id of the dossier to which this note belongs.</param>
        /// <param name="noteModel">The model used to create the note.</param>
        /// <returns></returns>
        public IHttpActionResult Post(int dossierId, [FromBody] Note noteModel)
        {
            var dossier = default(DossierData);

            if (!CurrentUser.TryGetDossier(dossierId, out dossier))
            {
                return(NotFound());
            }

            var noteData = new NoteData
            {
                Text        = noteModel.Text,
                DateCreated = noteModel.DateCreated,
                PosterId    = CurrentUser.Id
            };

            foreach (var media in noteModel.Media)
            {
                var noteMediaData = new NoteMediaData
                {
                    Name          = media.Name,
                    MediaLocation = GetStorageUri(media.Name)
                };

                noteData.Media.Add(noteMediaData);
            }

            dossier.Notes.Add(noteData);
            UoW.Save();

            var note = Converter.ToNote(noteData);

            return(CreatedAtRoute("NoteApi", new { dossierId = dossierId }, note));
        }
Esempio n. 11
0
        protected void OnButtonSaveClicked(object sender, EventArgs e)
        {
            var valid = new QSValidator <UndeliveredOrder>(undelivery);

            if (valid.RunDlgIfNotValid((Window)this.Toplevel))
            {
                return;
            }
            undeliveryView.BeforeSaving();
            if (!CanCreateUndelivery())
            {
                this.OnCloseTab(false);
                if (DlgSaved != null)
                {
                    DlgSaved(this, new UndeliveryOnOrderCloseEventArgs(undelivery));
                }
                return;
            }
            UoW.Save(undelivery);
            OnCloseTab(false);
            if (DlgSaved != null)
            {
                DlgSaved(this, new UndeliveryOnOrderCloseEventArgs(undelivery));
            }
        }
Esempio n. 12
0
        public DeleteCompanyProductResult DeleteCompanyProduct(DeleteCompanyProductRequest request)
        {
            var result = new DeleteCompanyProductResult();

            try
            {
                result.Errors.AddRange(ValidateProductSkuRequired(request.ProductSku));
                result.Errors.AddRange(ValidateCompanyCodeRequired(request.CompanyCode));
                result.Errors.AddRange(ValidateCompanyProductExist(request.ProductSku, request.CompanyCode));

                if (result.Errors.Any())
                {
                    return(result);
                }

                var companyProduct = GetCompanyProduct(request.ProductSku, request.CompanyCode);
                companyProduct.IsDeleted = true;
                UoW.Save();

                result.Success = true;
            }
            catch (Exception e)
            {
                result.Success = false;
                result.Errors.Add(new ExceptionError(e.Message));
            }

            return(result);
        }
Esempio n. 13
0
 public override bool Save()
 {
     UoW.Save();
     logger.Info("Save note on " + Entity.Date);
     Respond(ResponseType.Ok);
     return(true);
 }
        public IHttpActionResult Put(int dossierId, int id, [FromBody] DossierDetail dossierDetailModel)
        {
            var dossier = default(DossierData);

            if (!CurrentUser.TryGetDossier(dossierId, out dossier))
            {
                return(NotFound());
            }

            var detail = default(DossierDetailData);

            if (!dossier.TryGetDetail(id, out detail))
            {
                return(NotFound());
            }

            if (detail.Category != dossierDetailModel.Category)
            {
                detail.Category = dossierDetailModel.Category;
            }

            if (detail.Contents != dossierDetailModel.Contents)
            {
                detail.Contents = dossierDetailModel.Contents;
            }

            UoW.Save();

            var model = Converter.ToDossierDetail(detail);

            return(Ok(model));
        }
        public async Task <IHttpActionResult> Post(string userId, [FromBody] Dossier dossier)
        {
            var user = await UserManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(NotFound());
            }

            var dossierData = new DossierData()
            {
                Name     = dossier.Name,
                OwnerId  = user.Id,
                Watchers = new List <UserData>()
            };

            dossierData.Watchers.Add(user);

            UoW.DossierRepository.Insert(dossierData);
            UoW.Save();

            var result = Converter.ToDossier(dossierData);

            return(Created(Request.RequestUri, result));
        }
Esempio n. 16
0
 public ActionResult Create(Product product, HttpPostedFileBase file)
 {
     if (ModelState.IsValid)
     {
         if (file != null)
         {
             string g1 = System.Web.Hosting.HostingEnvironment.MapPath("~/") + "Content\\Images\\" + file.FileName;
             file.SaveAs(g1);
             product.ImagePath = file.FileName;
         }
         db.Products.Create(product);
         db.Save();
         return(RedirectToAction("Index"));
     }
     return(View(product));
 }
Esempio n. 17
0
 private void CreateToDraftNodeAction()
 {
     PopupActionsList.Add(
         new JournalAction(
             "В черновик",
             selectedItems => canUpdate &&
             selectedItems.OfType <DistrictsSetJournalNode>().FirstOrDefault()?.Status == DistrictsSetStatus.Closed,
             selectedItems => true,
             selectedItems => {
         var selectedNodes = selectedItems.OfType <DistrictsSetJournalNode>();
         var selectedNode  = selectedNodes.FirstOrDefault();
         if (selectedNode != null)
         {
             var districtsSet = UoW.GetById <DistrictsSet>(selectedNode.Id);
             if (districtsSet != null)
             {
                 districtsSet.Status        = DistrictsSetStatus.Draft;
                 districtsSet.DateClosed    = null;
                 districtsSet.DateActivated = null;
                 UoW.Save(districtsSet);
                 UoW.Commit();
                 Refresh();
             }
         }
     }
             )
         );
 }
        private void CreateCloseNodeAction()
        {
            PopupActionsList.Add(
                new JournalAction(
                    "Закрыть",
                    selectedItems => canUpdate &&
                    selectedItems.OfType <FinancialDistrictsSetsJournalNode>().FirstOrDefault()?.Status == DistrictsSetStatus.Draft,
                    selectedItems => true,
                    selectedItems => {
                var selectedNodes = selectedItems.OfType <FinancialDistrictsSetsJournalNode>();
                var selectedNode  = selectedNodes.FirstOrDefault();

                if (selectedNode != null)
                {
                    var districtsSet = UoW.GetById <FinancialDistrictsSet>(selectedNode.Id);

                    if (districtsSet != null)
                    {
                        districtsSet.Status        = DistrictsSetStatus.Closed;
                        districtsSet.DateClosed    = DateTime.Now;
                        districtsSet.DateActivated = null;
                        UoW.Save(districtsSet);
                        UoW.Commit();
                        Refresh();
                    }
                }
            }
                    )
                );
        }
Esempio n. 19
0
        public virtual bool Save(bool needClose = true)
        {
            var valid = new QSValidator <UndeliveredOrder>(UndeliveredOrder);

            if (valid.RunDlgIfNotValid((Window)this.Toplevel))
            {
                return(false);
            }
            if (UndeliveredOrder.Id == 0)
            {
                UndeliveredOrder.OldOrder.SetUndeliveredStatus(UoW, new BaseParametersProvider(), CallTaskWorker);
            }
            undeliveryView.BeforeSaving();
            //случай, если создавать новый недовоз не нужно, но нужно обновить старый заказ
            if (!CanCreateUndelivery())
            {
                UoW.Save(UndeliveredOrder.OldOrder);
                UoW.Commit();
                this.OnCloseTab(false);
                return(false);
            }

            UoW.Save(UndeliveredOrder);
            if (needClose)
            {
                this.OnCloseTab(false);
            }
            return(true);
        }
Esempio n. 20
0
 public override bool Save()
 {
     UoW.Save();
     logger.Info("Save shedule works on " + Entity.DateWork);
     Respond(ResponseType.Ok);
     return(true);
 }
        public override bool Save()
        {
            if (!Entity.CanEdit)
            {
                return(false);
            }

            Entity.UpdateAlreadyLoaded(UoW, _routeListRepository);
            var valid = new QS.Validation.QSValidator <CarLoadDocument> (UoWGeneric.Root);

            if (valid.RunDlgIfNotValid((Gtk.Window) this.Toplevel))
            {
                return(false);
            }

            Entity.LastEditor     = _employeeRepository.GetEmployeeForCurrentUser(UoW);
            Entity.LastEditedTime = DateTime.Now;
            if (Entity.LastEditor == null)
            {
                MessageDialogHelper.RunErrorDialog("Ваш пользователь не привязан к действующему сотруднику, вы не можете изменять складские документы, так как некого указывать в качестве кладовщика.");
                return(false);
            }

            if (Entity.Items.Any(x => x.Amount == 0))
            {
                var res = MessageDialogHelper.RunQuestionYesNoCancelDialog(
                    "<span foreground=\"red\">В списке есть нулевые позиции. Убрать нулевые позиции перед сохранением?</span>");
                switch (res)
                {
                case -4:                                                //DeleteEvent
                case -6:                                                //Cancel
                    return(false);

                case -8:                                                //Yes
                    Entity.ClearItemsFromZero();
                    break;

                case -9:                                                //No
                    break;
                }
            }

            Entity.UpdateOperations(UoW);

            logger.Info("Сохраняем погрузочный талон...");
            UoWGeneric.Save();

            logger.Info("Меняем статус маршрутного листа...");
            if (Entity.RouteList.ShipIfCan(UoW, CallTaskWorker, out _))
            {
                MessageDialogHelper.RunInfoDialog("Маршрутный лист отгружен полностью.");
            }
            UoW.Save(Entity.RouteList);
            UoW.Commit();

            logger.Info("Ok.");

            return(true);
        }
Esempio n. 22
0
 private void SaveUoW()
 {
     UoW.Save();
     if (UoW.RootObject != null)
     {
         EntitySaved?.Invoke(this, new EntitySavedEventArgs(UoW.RootObject));
     }
 }
Esempio n. 23
0
        protected void OnButtonTransferClicked(object sender, EventArgs e)
        {
            var itemsFrom = ytreeviewFrom.ItemsDataSource as IList <CarUnloadDocumentNode>;
            var itemsTo   = ytreeviewTo.ItemsDataSource as IList <CarUnloadDocumentNode>;
            var fromDoc   = ylistcomboReceptionTicketFrom.SelectedItem as CarUnloadDocument;
            var toDoc     = ylistcomboReceptionTicketTo.SelectedItem as CarUnloadDocument;

            foreach (var from in itemsFrom.Where(i => i.TransferCount > 0))
            {
                int transfer = from.TransferCount;
                //Заполняем для краткости
                var nomenclature = from.DocumentItem.WarehouseMovementOperation.Nomenclature;
                var receiveType  = from.DocumentItem.ReciveType;

                var to = itemsTo
                         .FirstOrDefault(i => i.DocumentItem.WarehouseMovementOperation.Nomenclature.Id == nomenclature.Id);

                if (to == null)
                {
                    toDoc.AddItem(receiveType, nomenclature, null, transfer, null);

                    foreach (var item in toDoc.Items)
                    {
                        var exist = itemsTo.FirstOrDefault(i => i.DocumentItem.Id == item.Id);
                        if (exist == null)
                        {
                            itemsTo.Add(new CarUnloadDocumentNode {
                                DocumentItem = item
                            });
                        }
                    }
                }
                else
                {
                    to.DocumentItem.WarehouseMovementOperation.Amount += transfer;

                    UoW.Save(to.DocumentItem.WarehouseMovementOperation);
                }

                from.DocumentItem.WarehouseMovementOperation.Amount -= transfer;
                if (from.DocumentItem.WarehouseMovementOperation.Amount == 0)
                {
                    var item = fromDoc.Items.First(i => i.Id == from.DocumentItem.Id);
                    fromDoc.Items.Remove(item);

                    UoW.Delete(from.DocumentItem.WarehouseMovementOperation);
                }
                else
                {
                    UoW.Save(from.DocumentItem.WarehouseMovementOperation);
                }

                from.TransferCount = 0;
            }
            UoW.Save(fromDoc);
            UoW.Save(toDoc);
            CheckSensitivities();
        }
Esempio n. 24
0
        static void Main(string[] args)
        {
            Categories cat = AddNewCat();

            try
            {
                foreach (var item in _uow.Categories.GetAll())
                {
                    if (item.CategoryName == cat.CategoryName)
                    {
                        throw new Exception("Such category already exists!"); //Система выдает ошыбку!
                    }
                }
                _uow.Categories.Create(cat);
                _uow.Save();
                Console.WriteLine("Category succesfully added!"); //Посылка EMAIL модератору!
            }
            catch (Exception e) { Console.WriteLine(e.Message); }
            foreach (var item in _uow.Categories.GetAll())
            {
                Console.WriteLine(item.CategoryName);
            }

            Posts post = AddNewPost();

            try
            {
                foreach (var item in _uow.Posts.GetAll())
                {
                    if (item.PostName == post.PostName)
                    {
                        throw new Exception("Such post already exists!"); //Система выдает ошыбку!
                    }
                }
                _uow.Posts.Create(post);
                _uow.Save();
                Console.WriteLine("Post succesfully added!"); //Посылка EMAIL модератору!
            }
            catch (Exception e) { Console.WriteLine(e.Message); }
            foreach (var item in _uow.Posts.GetAll())
            {
                Console.WriteLine(item.PostName);
            }
            Console.ReadLine();
        }
Esempio n. 25
0
        protected void OnButtonSendSMSClicked(object sender, EventArgs e)
        {
            logger.Info("Сохраняем заказ перед отправкой SMS...");
            PrepareSave();
            UoW.Save();
            logger.Info("Ok");
            var page = navigation.OpenViewModel <SendMessageViewModel, OrderMessagesModel>(null, orderMessages);

            page.PageClosed += SentMessage_PageClosed;
        }
 public override bool Save()
 {
     if (UoW.IsNew)
     {
         Entity.Employee.AddVacation(Entity);
     }
     Entity.UpdateRelatedOperations(UoW, new EmployeeIssueRepository(), baseParameters, new GtkQuestionDialogsInteractive());
     UoW.Save(Entity.Employee);
     return(base.Save());
 }
Esempio n. 27
0
 public bool UpdateTask(TASK task)
 {
     // var original = UoW.TASK_Repository.GetByID(task.PK_ID_TASK);
     if (task.PK_ID_TASK != 0)
     {
         UoW.TASK_Repository.UpdateOnlyTask(task);
         UoW.Save();
         return(true);
     }
     return(false);
 }
Esempio n. 28
0
 public bool AddTrace(TRACE trace)
 {
     if (UoW.TRACE_Repository.Insert(trace))
     {
         UoW.Save();
         return(true);
     }
     else
     {
         return(false);
     }
 }
Esempio n. 29
0
        public void SetAllTasksPaidForTransaction(int transactionId)
        {
            var tasks = UoW.TASK_Repository.Get(t => t.FK_ID_TRANSACTION == transactionId);

            foreach (var task in tasks)
            {
                task.IS_PAID = true;
                UoW.TASK_Repository.Update(task);
            }

            UoW.Save();
        }
 protected void OnBtnAddCommentClicked(object sender, EventArgs e)
 {
     if (String.IsNullOrWhiteSpace(txtAddComment.Buffer.Text))
     {
         return;
     }
     CreateComment();
     UoW.Save(Comment);
     UoW.Commit();
     GetComments();
     Comment = null;
     OnCommentAdded();
 }