Example #1
0
        public int GetDocumentNumber(SkladDataContext context, int year, int documentTypeId)
        {
            int documentNumber = 1;

            // lock to all rows
            var transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead, Timeout = TimeSpan.MaxValue };
            using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
            {
                var item = context.DocumentCounters.Where(x => x.DocumentTypeId == documentTypeId &&
                    x.Year == year).FirstOrDefault();
                if (item == null)
                {
                    context.DocumentCounters.Add(new DocumentCounter {
                        Counter = documentNumber,
                        Year = year,
                        DocumentTypeId = documentTypeId
                    });
                }
                else
                {
                    item.Counter = item.Counter + 1;
                    documentNumber = item.Counter;
                }
                context.SaveChanges();
                scope.Complete();
            }

            return documentNumber;
        }
Example #2
0
 public void DeleteDocument(SkladDataContext context, Document document)
 {
     // При удалении возврата - обновить поле Shipment в родителе
     if (document.DocumentTypeId == (int)SidBy.Sklad.Domain.Enums.EntityEnum.DocumentTypeEnum.Refunds)
     {
         foreach (var product in document.Products)
         {
             var productLineToUpdate = context.ProductLines.Where(x => x.ProductId == product.ProductId).FirstOrDefault();
             if (productLineToUpdate != null) {
                 productLineToUpdate.Shipped = productLineToUpdate.Shipped - product.Quantity;
                 if (productLineToUpdate.Shipped < 0)
                     productLineToUpdate.Shipped = 0;
             }
         }
         context.SaveChanges();
     }
 }
Example #3
0
        public void AddNewProduct(int contractorId,
           string article,
           decimal purchaseprice,
           decimal saleprice,
           decimal vat)
        {
            if (contractorId <= 0 || String.IsNullOrEmpty(article))
                return;

            Product item = new Product()
            {
                Article = article,
                PurchasePrice = purchaseprice,
                SalePrice = saleprice,
                VAT = vat,
                ContractorId = contractorId
            };

            var datacontextModel = new SkladDataContext();

            PrepareProductData(item);

            item.Supplier = (from x in datacontextModel.Contractors
                                  where x.ContractorId == item.ContractorId &&
                                  x.ContractorTypeId == (int)EntityEnum.ContractorTypeEnum.Factory
                                  select x).First<Contractor>();

            if (item.Supplier == null)
            {
                logger.ErrorFormat("для товара {0} не найден поставщик с id={1}", item.Article, item.ContractorId);
                return;
            }

            string validationMessage = ValidateProductData(datacontextModel.Products, item, true);
            if (!String.IsNullOrEmpty(validationMessage))
            {
                logger.Error(validationMessage);
                return;
            }

            datacontextModel.Products.Add(item);
            datacontextModel.SaveChanges();

            logger.InfoFormat("Создан товар {0} от поставщика {1}", item.Article, item.Supplier.Code);
        }
Example #4
0
        public void AddContactById(int contractorId, int userId)
        {
            if (contractorId <= 0 || userId <= 0)
                return;

            var datacontextModel = new SkladDataContext();

            UserProfile item = (from x in datacontextModel.UserProfiles.Include(x => x.Contractors)
                                where x.UserId == userId
                                select x)
                                 .First<UserProfile>();

            Contractor contractor = datacontextModel.Contractors
                .Where(x => x.ContractorId == contractorId).FirstOrDefault<Contractor>();

            item.Contractors.Add(contractor);
            datacontextModel.SaveChanges();
            logger.InfoFormat("у контрагента {0} появился контакт {1}", contractor.Code, item.DisplayName);
        }
Example #5
0
        public ActionResult ContractorEditRows(Contractor editedItem)
        {
            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            // If we are in "Edit" mode
            if (gridModel.ContractorGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                PrepareContractorData(editedItem);

                string validationMessage = ValidateContractorData(datacontextModel.Contractors, editedItem, false);
                if (!String.IsNullOrEmpty(validationMessage))
                    return gridModel.ContractorGrid.ShowEditValidationMessage(validationMessage);

                // Get the data from and find the item corresponding to the edited row
                Contractor item = (from x in datacontextModel.Contractors
                               where x.ContractorId == editedItem.ContractorId
                               select x).First<Contractor>();

                // update the item information
                UpdateContractor(item, editedItem);

                datacontextModel.SaveChanges();
                logger.InfoFormat("контрагент изменён {0}", item.Code);

            }

            if (gridModel.ContractorGrid.AjaxCallBackMode == AjaxCallBackMode.AddRow)
            {
                PrepareContractorData(editedItem);

                string validationMessage = ValidateContractorData(datacontextModel.Contractors, editedItem, true);
                if (!String.IsNullOrEmpty(validationMessage))
                    return gridModel.ContractorGrid.ShowEditValidationMessage(validationMessage);

                // since we are adding a new item, create a new istance
                Contractor item = new Contractor() { IsArchived = false, CreatedAt = DateTime.Now };
                // set the new item information
                UpdateContractor(item, editedItem);

                datacontextModel.Contractors.Add(item);
                datacontextModel.SaveChanges();
                logger.InfoFormat("контрагент добавлен {0}", item.Code);

            }
            if (gridModel.ContractorGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {
                Contractor item = (from x in datacontextModel.Contractors
                                   where x.ContractorId == editedItem.ContractorId
                               select x)
                               .First<Contractor>();

                // delete the record
                datacontextModel.Contractors.Remove(item);
                datacontextModel.SaveChanges();
                logger.InfoFormat("контрагент удалён {0}", item.Code);
            }

            return RedirectToAction("Contractor", "Reference");
        }
Example #6
0
        private string CreateRelatedDocument(SkladDataContext datacontextModel, int documentId, string selectedRowsIds)
        {
            Document parentDoc = datacontextModel.Documents.Include("Products").Where(x => x.DocumentId == documentId)
                 .FirstOrDefault();

            if(parentDoc == null)
                return Constants.ErrorUrl;

            // TODO: split selectedRowsIds to array of int. Transfer to a new document only items with specified ids.

            int newDocumentTypeId = 0;
            if(parentDoc.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.CustomerOrders)
            {
                newDocumentTypeId = (int)EntityEnum.DocumentTypeEnum.Shipment;
            }

            if(parentDoc.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Shipment)
            {
                newDocumentTypeId = (int)EntityEnum.DocumentTypeEnum.Refunds;
            }
            if(newDocumentTypeId == 0)
                return Constants.ErrorUrl;

            DocumentOperation operation = new DocumentOperation();

            string secureFolderName = GenerateFolderName(String.Empty);
            string commonFolderName = GenerateFolderName(secureFolderName);

            Document newDocument = new Document
            {
                Number = parentDoc.Number + "-"
                        + operation.GetDocumentNumber(datacontextModel, DateTime.Now.Year,newDocumentTypeId).ToString(),
                CreatedOf = parentDoc.CreatedOf,
                ContractorId = parentDoc.ContractorId,
                EmployeeId = parentDoc.EmployeeId,
                CreatedAt = DateTime.Now,
                FromWarehouseId = parentDoc.FromWarehouseId,
                ToWarehouseId = parentDoc.ToWarehouseId,
                DocumentTypeId = newDocumentTypeId,
                ParentDocumentId = parentDoc.DocumentId,
                SecureFolderName = secureFolderName,
                CommonFolderName = commonFolderName,
                IsReportOutdated = true,
            };

            datacontextModel.Documents.Add(newDocument);

            datacontextModel.SaveChanges();

            newDocument = datacontextModel.Documents.Where(x => x.ParentDocumentId == parentDoc.DocumentId &&
                  x.DocumentTypeId == newDocumentTypeId
                  && x.Number == newDocument.Number
                  && x.CreatedAt.Year == newDocument.CreatedAt.Year
                  && x.CreatedAt.Month == newDocument.CreatedAt.Month
                  && x.CreatedAt.Day == newDocument.CreatedAt.Day

                  ).FirstOrDefault();

            //Clone list
            newDocument.Products = new List<ProductLine>();
                //parentDoc.Products.Where(x => x.Shipped < x.Quantity)
                //.Select(c => { c.DocumentId = newDocument.DocumentId; c.Document = null;
                //c.Product = null;
                //    return c; }).ToList()
                //);
            List<ProductLine> productsToCopy = null;
            if (!String.IsNullOrEmpty(selectedRowsIds))
            {
                string[] idsStr = selectedRowsIds.Split(',');
                idsStr = idsStr.Where(x => !String.IsNullOrEmpty(x)).ToArray();
                int[] ids = Array.ConvertAll<string, int>(idsStr, int.Parse);
                productsToCopy = parentDoc.Products.Where(x => x.Shipped < x.Quantity
                    && ids.Contains(x.ProductLineId))
                .ToList();
            }
            else
            {
                productsToCopy = parentDoc.Products.Where(x => x.Shipped < x.Quantity)
              .ToList();
            }

            /*
             * string values = "1,2,3,4,5,6,7,8,9,10";
            string[] tokens = values.Split(',');

            int[] convertedItems = Array.ConvertAll<string, int>(tokens, int.Parse);

             *
             int[] ids = // populate ids
            var query = from e in db.SomeTable
            where ids.Contains(e.SuchID)
            select e
             */

            foreach (var product in productsToCopy)
            {
                newDocument.Products.Add(new ProductLine
                {
                    DocumentId = newDocument.DocumentId,
                    ProductId = product.ProductId,
                    SupplierId = product.SupplierId,
                    ProductArticle = product.ProductArticle,
                    SupplierCode = product.SupplierCode,
                    Quantity = product.Quantity,
                    Discount = product.Discount,
                    Reserve = product.Reserve,
                    Shipped = product.Shipped,
                    Available = product.Available,
                    PurchasePrice = product.PurchasePrice,
                    SalePrice = product.SalePrice,
                    MarginAbs = product.MarginAbs,
                    Sum = product.Sum,
                    SaleSum = product.SaleSum,
                    VAT = product.VAT,
                    IsPriceIncludesVAT = product.IsPriceIncludesVAT,
                    Comment = product.Comment
                });
            }

            datacontextModel.SaveChanges();

            return "/Home/Document?documentId=" + newDocument.DocumentId;
            // Cre

            /*
                   case (int)EntityEnum.DocumentTypeEnum.CustomerOrders:
                    return "/Sale/CustomerOrders";
                case (int)EntityEnum.DocumentTypeEnum.Shipment:
                    return "/Sale/Shipment";
             */
        }
Example #7
0
        /*
          "docContractorId": $("#ContractorDocId").val(),
                        "docEmployeeId": $("#DocumentItem_Employee_UserId").val(),
                        "docPlanDate": $("#planDateDatepicker").datepicker("getDate").toJSONLocal(),
         */
        public string SaveDocument(int documentId, string docNumber,
            DateTime docCreatedOf, string docComment,
            bool docIsComitted, int? docContractorId, int? docEmployeeId,
            DateTime? docPlanDate, bool createRelatedDoc, string selectedRowsIds
          )
        {
            if (documentId <= 0)
                return Constants.ErrorUrl;

            var datacontextModel = new SkladDataContext();

            var document = datacontextModel.Documents.Include("Products").Where(x => x.DocumentId == documentId).FirstOrDefault();

            if (document == null)
                return Constants.ErrorUrl;

            if (document.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Posting
                || document.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Cancellation)
            {
                docContractorId = null;
                docEmployeeId = null;
                docPlanDate = null;
            }

            if (document.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.CustomerOrders
                || document.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Refunds
                || document.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Shipment)
            {
                if(docContractorId == null || docEmployeeId == null)
                    return Constants.ErrorUrl;
            }

            if(!String.IsNullOrEmpty(docNumber))
                document.Number = docNumber;

            document.CreatedOf = docCreatedOf;
            document.Comment = docComment;
            document.ContractorId = docContractorId;
            document.EmployeeId = docEmployeeId;
            document.PlannedDate = docPlanDate;
            document.IsReportOutdated = true;

            // calculate sum
            document.Sum = datacontextModel.ProductLines
                .Where(x => x.DocumentId == document.DocumentId).Sum(x => x.Sum);

            document.SaleSum = datacontextModel.ProductLines
                .Where(x => x.DocumentId == document.DocumentId).Sum(x => x.SaleSum);

            DocumentOperation docOperation = new DocumentOperation();
            docOperation.UpdateDocument(datacontextModel, document.DocumentId);

            if (createRelatedDoc)
                docIsComitted = true;

            document.IsCommitted = docIsComitted;

            datacontextModel.SaveChanges();

            // TODO: if there was ParentDocumentId than check all productLines
            // and update Shipped.
            if (document.ParentDocumentId != null)
            {
                // get parent document
                var parentDoc = datacontextModel.Documents.Include("Products").Where(x => x.DocumentId == document.ParentDocumentId)
                    .FirstOrDefault();
                if (parentDoc != null)
                {
                    // TODO: Check all ProductLines that were shipped
                    if (parentDoc.Products != null)
                    {
                        foreach (var product in parentDoc.Products)
                        {
                            int? shipped = 0;
                            shipped = datacontextModel.ProductLines
                                .Where(x => x.ProductId == product.ProductId &&
                                    x.DocumentId == documentId)
                                .Select(x => x.Quantity).FirstOrDefault();
                            if (shipped != null)
                                product.Shipped = (int)shipped;
                        }

                        datacontextModel.SaveChanges();
                    }
                }
            }

            if (document.Products != null)
                docOperation.UpdateDocumentProducts(document.Products.ToList());

            if (createRelatedDoc)
                return CreateRelatedDocument(datacontextModel, documentId, selectedRowsIds);

            return DocumentOperation.UrlToDocumentList(document.DocumentTypeId);
        }
Example #8
0
        public ActionResult DocumentItemEditRows(Document editedItem)
        {
            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            // If we are in "Edit" mode
            if (gridModel.DocumentGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                return RedirectToAction("Document", new { documentId = editedItem.DocumentId });
            }

            if (gridModel.DocumentGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {
                Document item = (from x in datacontextModel.Documents
                                    where x.DocumentId == editedItem.DocumentId
                                    select x)
                               .First<Document>();

                DocumentOperation operation = new DocumentOperation();
                operation.DeleteDocument(datacontextModel, item);

                datacontextModel.Documents.Remove(item);
                datacontextModel.SaveChanges();

                logger.InfoFormat("удален документ {0} от {1}", editedItem.Number, editedItem.CreatedOf);
            }

            return RedirectToDocumentList(editedItem.DocumentTypeId);
        }
Example #9
0
        public ActionResult DocumentEditRows(ProductLine editedItem)
        {
            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            int documentId = -1;
            // If we are in "Edit" mode

            if (gridModel.ProductLineGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                // Get the data from and find the item corresponding to the edited row
                ProductLine item = (from x in datacontextModel.ProductLines
                                    where x.ProductLineId == editedItem.ProductLineId
                                    select x).First<ProductLine>();

                // update the Order information
                UpdateProductLine(item, editedItem);

                // save comment to iriginal product item description
                var product = datacontextModel.Products.Where(x => x.ProductId == item.ProductId).FirstOrDefault();
                if (product != null)
                {
                    if (String.IsNullOrEmpty(product.Description))
                    { product.Description = editedItem.Comment; }
                    else if (product.Description.IndexOf(editedItem.Comment) == -1)
                    {
                        product.Description += ". " + editedItem.Comment;
                    }
                    else
                        product.Description = editedItem.Comment;
                }

                documentId = item.DocumentId;
                datacontextModel.SaveChanges();
            }

            if (gridModel.ProductLineGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {
                ProductLine item = (from x in datacontextModel.ProductLines
                                    where x.ProductLineId == editedItem.ProductLineId
                                    select x)
                               .First<ProductLine>();
                documentId = item.DocumentId;
                // delete the record
                datacontextModel.ProductLines.Remove(item);
                datacontextModel.SaveChanges();
            }

            var document = datacontextModel.Documents.Where(x => x.DocumentId == documentId).FirstOrDefault();

            if (document != null)
            {
                document.IsReportOutdated = true;
                datacontextModel.SaveChanges();
            }

            // Add
            //DocumentOperation operation = new DocumentOperation();
            //operation.UpdateDocument(datacontextModel, documentId);

            return RedirectToAction("Document", "Home", new { documentId = documentId });
        }
Example #10
0
        public int AddNewProductLine(int? documentId, int doctypeId, string docNumber,
            DateTime docCreatedOf, string docComment,
            int supplierId,
            string article,
            decimal purchaseprice, decimal marginabs, decimal discount, int quantity, int quantityW, string comment)
        {
            if (supplierId <= 0 || String.IsNullOrEmpty(article) || purchaseprice < 0
                || doctypeId <= 0
                )
                return -1;

            var datacontextModel = new SkladDataContext();
            // check for valid supplier
            var supplier = datacontextModel.Contractors.Where(x => x.ContractorId == supplierId &&
                x.ContractorTypeId == (int)EntityEnum.ContractorTypeEnum.Factory).FirstOrDefault();

            if (supplier == null)
                return -1;

            article = article.Trim().Replace(" ","").ToLower();
            comment = comment.Trim();
            // get product
            Product product = GetOrCreateProduct(datacontextModel, supplierId, purchaseprice, marginabs, article, comment);

            // Add DocumentId if null
            Document document = null;

            if (documentId == null || documentId <= 0)
            {
                DocumentOperation docOp = new DocumentOperation();

                docNumber = String.IsNullOrEmpty(docNumber) ?
                    docOp.GetDocumentNumber(datacontextModel, DateTime.Now.Year, doctypeId).ToString()
                    : docNumber.Trim().Replace(" ", "");

                string secureFolderName = GenerateFolderName(String.Empty);
                string commonFolderName = GenerateFolderName(secureFolderName);
                // Create new document
                document = new Document
                {
                    DocumentTypeId = doctypeId,
                    CreatedOf = docCreatedOf,
                    Comment = docComment,
                    CreatedAt = DateTime.Now,
                    Number = docNumber,
                    IsCommitted = false,
                    SecureFolderName = secureFolderName,
                    CommonFolderName = commonFolderName,
                    IsReportOutdated = true,
                };
                datacontextModel.Documents.Add(document);
                datacontextModel.SaveChanges();

                document = datacontextModel.Documents.Where(x => x.Number == docNumber &&
                    x.DocumentTypeId == doctypeId
                    && x.CreatedAt.Year == document.CreatedAt.Year
                    && x.CreatedAt.Month == document.CreatedAt.Month
                    && x.CreatedAt.Day == document.CreatedAt.Day
                    && x.CreatedAt.Hour == document.CreatedAt.Hour
                    && x.CreatedAt.Minute == document.CreatedAt.Minute).FirstOrDefault();
            }
            else
            {
                document = datacontextModel.Documents.Where(x => x.DocumentId == documentId).FirstOrDefault();
            }

            if (document == null)
            {
                logger.ErrorFormat("Ошибка создания документа № {0} от {1}", docNumber, docCreatedOf);
                return -1;
            }

            document.IsReportOutdated = true;

            // Check if this productline already exists in document. if so, just
            // change it value
            ProductLine line = datacontextModel.ProductLines.Where(x => x.ProductId == product.ProductId &&
                 x.DocumentId == document.DocumentId).FirstOrDefault();

            string productComment = comment;
              //  int productQuantity = quantity;
            if (quantityW > 0)
            {
                productComment += "со склада [" + quantityW + "] ед. ";
            }

            if (line == null)
            {
                // Attach productLine to document
                line = new ProductLine
                {
                    ProductArticle = article,
                    SupplierCode = supplier.Code,
                    SupplierId = supplier.ContractorId,
                    Quantity = quantity + quantityW,
                    PurchasePrice = purchaseprice,
                    SalePrice = purchaseprice + marginabs,
                    MarginAbs = marginabs,
                    Discount = discount,
                    Comment = productComment,
                    ProductId = product.ProductId,
                    DocumentId = document.DocumentId,
                    Sum = (quantity + quantityW) * purchaseprice,
                    SaleSum = (quantity + quantityW) * (purchaseprice + marginabs)
                };

                if (document.Products == null)
                    document.Products = new List<ProductLine>();

                document.Products.Add(line);
            }
            else
            {
                line.ProductArticle = article;
                line.SupplierCode = supplier.Code;
                line.SupplierId = supplier.ContractorId;
                line.Quantity = quantity + quantityW;
                line.PurchasePrice = purchaseprice;
                line.MarginAbs = marginabs;
                line.Discount = discount;
                line.SalePrice = purchaseprice + marginabs;
                line.Comment = productComment;
                line.ProductId = product.ProductId;
                line.Sum = (quantity + quantityW) * purchaseprice;
                line.SaleSum = (quantity + quantityW) * (purchaseprice + marginabs);
            }

            // обновить документы оприходования где имеется этот товар
            RemoveProductFromPostingDocument(datacontextModel, product.ProductId, quantityW);

            datacontextModel.SaveChanges();

            return document.DocumentId;
        }
Example #11
0
        public ActionResult MyEmployeesEditRows(UserProfile editedItem)
        {
            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            // If we are in "Edit" mode
            if (gridModel.MyEmployeesGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                if (editedItem.UserName == "admin" && !User.IsInRole("admin"))
                    return gridModel.MyEmployeesGrid.ShowEditValidationMessage("Эту запись изменить нельзя");

                PrepareUsersData(editedItem);

                string validationMessage = ValidateUsersData(datacontextModel.UserProfiles, editedItem, false);
                if (!String.IsNullOrEmpty(validationMessage))
                    return gridModel.MyEmployeesGrid.ShowEditValidationMessage(validationMessage);

                // Get the data from and find the item corresponding to the edited row
                UserProfile item = (from x in datacontextModel.UserProfiles
                                   where x.UserId == editedItem.UserId
                                   select x).First<UserProfile>();
                if (editedItem.UserId == item.UserId)
                {
                    // update the item information
                    UpdateMyEmployees(item, editedItem);

                    datacontextModel.SaveChanges();
                    UpdateUserRole(datacontextModel, item);
                    logger.InfoFormat("изменён контакт {0}", editedItem.DisplayName);

                    // Change password if need it
                    if (!String.IsNullOrEmpty(editedItem.NewPassword))
                    {
                        string resetToken = WebSecurity.GeneratePasswordResetToken(editedItem.UserName);
                        WebSecurity.ResetPassword(resetToken, editedItem.NewPassword);
                        logger.InfoFormat("изменён пароль контакта {0}", editedItem.DisplayName);
                    }
                }
            }

            if (gridModel.MyEmployeesGrid.AjaxCallBackMode == AjaxCallBackMode.AddRow)
            {
                PrepareUsersData(editedItem);
                string validationMessage = ValidateUsersData(datacontextModel.UserProfiles, editedItem, true);
                if (!String.IsNullOrEmpty(validationMessage))
                    return gridModel.MyEmployeesGrid.ShowEditValidationMessage(validationMessage);

                    // since we are adding a new item, create a new istance
                    string newPassword = editedItem.NewPassword;
                    if (String.IsNullOrEmpty(newPassword))
                        editedItem.NewPassword = System.Web.Security.Membership.GeneratePassword(5, 1);

                    // Create membership account
                    WebSecurity.CreateUserAndAccount(editedItem.UserName, editedItem.NewPassword);
                    UserProfile item = (from x in datacontextModel.UserProfiles
                                        where x.UserName == editedItem.UserName
                                        select x).First<UserProfile>();
                    // set the new item information
                    UpdateMyEmployees(item, editedItem);

                    datacontextModel.SaveChanges();
                    UpdateUserRole(datacontextModel, item);
                    logger.InfoFormat("добавлен контакт {0} с паролем - {1}", editedItem.DisplayName, editedItem.NewPassword);
            }
            if (gridModel.MyEmployeesGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {
                UserProfile item = (from x in datacontextModel.UserProfiles
                                    where x.UserId == editedItem.UserId
                                    select x)
                               .First<UserProfile>();

                if (item.ContactTypeId == 1)
                    return gridModel.MyEmployeesGrid.ShowEditValidationMessage("Невозможно удалить сотрудника");

                // delete the record
                Membership.DeleteUser(item.UserName);
                logger.InfoFormat("удален контакт {0}", editedItem.DisplayName);
            }

            return RedirectToAction("MyEmployees", "MyCompany");
        }
Example #12
0
        public ActionResult ContactListEditRows(UserProfile editedItem)
        {
            int contractorId = 0;

            Int32.TryParse(Request.QueryString["contractorId"], out contractorId);

            if (contractorId <= 0)
                return null;

            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            // If we are in "Edit" mode
            if (gridModel.MyEmployeesGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                PrepareUsersData(editedItem);

                string validationMessage = ValidateUsersData(datacontextModel.UserProfiles, editedItem, false);
                if (!String.IsNullOrEmpty(validationMessage))
                    return gridModel.MyEmployeesGrid.ShowEditValidationMessage(validationMessage);

                // Get the data from and find the item corresponding to the edited row
                UserProfile item = (from x in datacontextModel.UserProfiles
                                    where x.UserId == editedItem.UserId
                                    select x).First<UserProfile>();

                if (item.ContactTypeId != 3)
                    return null;

                // update the item information
                UpdateMyEmployees(item, editedItem);

                datacontextModel.SaveChanges();
                logger.InfoFormat("контакт {0} изменён", item.DisplayName);

                // Change password if need it
                if (!String.IsNullOrEmpty(editedItem.NewPassword))
                {
                    string resetToken = WebSecurity.GeneratePasswordResetToken(editedItem.UserName);
                    WebSecurity.ResetPassword(resetToken, editedItem.NewPassword);
                    logger.InfoFormat("у контакта {0} был изменён пароль", editedItem.DisplayName);
                }
            }

            if (gridModel.MyEmployeesGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {

                UserProfile item = (from x in datacontextModel.UserProfiles.Include(x => x.Contractors)
                                    where x.UserId == editedItem.UserId
                                    select x)
                               .First<UserProfile>();

                Contractor contractor = datacontextModel.Contractors
                    .Where(x => x.ContractorId == contractorId).FirstOrDefault<Contractor>();
                item.Contractors.Remove(contractor);
                datacontextModel.SaveChanges();
            }

            return RedirectToAction("ContactList", "MyCompany", new { contractorId = contractorId });
        }
Example #13
0
        // TODO: create ajax method which creates datacontextModel
        private string GetReportFile(SkladDataContext datacontextModel, 
            Document document, 
            EntityEnum.ReportType type)
        {
            if (document == null)
            {
                logger.ErrorFormat("GetReportFile. Document is null");
                throw new ArgumentException("GetReportFile. Document is null");
            }

            bool saveChanges = false;
            // check for folder names
            if (String.IsNullOrEmpty(document.SecureFolderName))
            {
                document.SecureFolderName = GenerateFolderName(document.CommonFolderName);
                saveChanges = true;
            }

            if (String.IsNullOrEmpty(document.CommonFolderName))
            {
                document.CommonFolderName = GenerateFolderName(document.SecureFolderName);
                saveChanges = true;
            }

            if (saveChanges)
                datacontextModel.SaveChanges();

            string relativePath = "../" + Constants.DocumentReportPath;
            string rootPath = Server.MapPath(relativePath);
            string reportFile = String.Empty;

            if (type == EntityEnum.ReportType.SaleReport)
            {
                // Check if file already exists.
                // Than check Modified date of the file in file name
                string docPath = Path.Combine(rootPath, document.DocumentId.ToString(), document.SecureFolderName);

                if(!Directory.Exists(docPath))
                    Directory.CreateDirectory(docPath);

                string dateSeparator = "-";
                string extension = ".xls";
                string mask = String.Format("{0}*{1}", Constants.DocumentReportPrefix, extension);

                var directory = new DirectoryInfo(docPath);
                // get last created file in directory
                var existingFile = directory.GetFiles(mask).OrderByDescending(f => f.LastWriteTime).FirstOrDefault();

                if (existingFile != null && !document.IsReportOutdated)
                {
                    // check if file is actual upon document modified date
                    reportFile = String.Format("{0}/{1}/{2}/{3}", relativePath,
                        document.DocumentId.ToString(), document.SecureFolderName, existingFile.Name);
                }
                else
                {
                    string fileName = String.Format("{0}{1}{4}{2}{4}{3}{5}", Constants.DocumentReportPrefix,
                        DateTimeOffset.Now.Year, DateTimeOffset.Now.ToString("MM"), DateTimeOffset.Now.ToString("dd"),
                        dateSeparator, extension);

                    // create report
                    ExcelReportInfo reportInfo = new ExcelReportInfo
                    {
                        CreatedOf = document.CreatedOf,
                        FileName = fileName,
                        FilePath = docPath,
                        DocumentSubject = "Отчёт №" + document.Number + " от " + document.CreatedOf,
                        SheetName = "Report-" + document.CreatedOf.ToString("dd.MM.yyyy"),
                        TitleLeft = (document.Contractor != null) ? document.Contractor.Code : String.Empty,
                        TitleCenter = document.CreatedOf.ToString("dd.MM.yyyy"),
                        TitleRight = "Док. №" + document.Number + " от " + document.CreatedOf.ToString("dd.MM.yyyy")
                    };

                    ReportHelper.GenerateProductLinesReport(document.Products, reportInfo);

                    document.IsReportOutdated = false;
                    datacontextModel.SaveChanges();
                    reportFile = String.Format("{0}/{1}/{2}/{3}", relativePath,
                        document.DocumentId.ToString(), document.SecureFolderName, fileName);
                }
            }

            return reportFile;
        }
Example #14
0
        private Product GetOrCreateProduct(SkladDataContext datacontextModel, int supplierId, decimal purchaseprice, decimal marginabs, string article, string comment)
        {
            Product product = datacontextModel.Products.Where(x => x.Article.ToLower() == article &&
                x.ContractorId == supplierId).FirstOrDefault();

            if (product == null)
            {
                // Add new product
                Product item = new Product
                {
                    Article = article,
                    ContractorId = supplierId,
                    PurchasePrice = purchaseprice,
                    SalePrice = purchaseprice + marginabs,
                    CreatedAt = DateTime.Now,
                };

                datacontextModel.Products.Add(item);
                datacontextModel.SaveChanges();

                product = datacontextModel.Products.Where(x => x.Article.ToLower() == article &&
                x.ContractorId == supplierId).FirstOrDefault();
            }

            if (String.IsNullOrEmpty(product.Description))
                product.Description = comment;
            else if (product.Description.IndexOf(comment) == -1)
                product.Description += ". " + comment;
            else
                product.Description = comment;

            datacontextModel.SaveChanges();

            return product;
        }
Example #15
0
        public void AddNewContact(int contractorId,
            string displayName,
            string name,
            string surname,
            string phone1,
            string userEmail,
            string skype)
        {
            if (contractorId <= 0 || String.IsNullOrEmpty(displayName))
                return;

            UserProfile item = new UserProfile() { DisplayName = displayName,
            Name = name, Surname = surname, Phone1 = phone1, UserEmail = userEmail, Skype = skype};

            var datacontextModel = new SkladDataContext();

            PrepareUsersData(item);
            item.ContactTypeId = 3;

            string validationMessage = ValidateUsersData(datacontextModel.UserProfiles, item, true);
            if (!String.IsNullOrEmpty(validationMessage))
            {
                logger.Error(validationMessage);
                return;
            }

            // since we are adding a new item, create a new istance
            item.NewPassword = System.Web.Security.Membership.GeneratePassword(5, 1);

            // Create membership account
            WebSecurity.CreateUserAndAccount(item.UserName, item.NewPassword);
            UserProfile newItem = (from x in datacontextModel.UserProfiles
                                where x.UserName == item.UserName
                                select x).First<UserProfile>();
            // set the new item information
            UpdateMyEmployees(newItem, item);

            Contractor contractor = datacontextModel.Contractors
              .Where(x => x.ContractorId == contractorId).FirstOrDefault<Contractor>();

            newItem.Contractors.Add(contractor);
            datacontextModel.SaveChanges();

            logger.InfoFormat("добавлен контакт {0} с паролем - {1}", item.DisplayName, item.NewPassword);
        }
Example #16
0
        public ActionResult WarehouseEditRows(Warehouse editedItem)
        {
            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            // If we are in "Edit" mode
            if (gridModel.WarehouseGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                // Get the data from and find the item corresponding to the edited row
                Warehouse item = (from x in datacontextModel.Warehouses
                                    where x.WarehouseId == editedItem.WarehouseId
                                    select x).First<Warehouse>();

                // update the item information
                UpdateWarehouse(item, editedItem);

                datacontextModel.SaveChanges();
            }

            if (gridModel.WarehouseGrid.AjaxCallBackMode == AjaxCallBackMode.AddRow)
            {
                // since we are adding a new item, create a new istance
                Warehouse item = new Warehouse();
                // set the new item information
                UpdateWarehouse(item, editedItem);

                datacontextModel.Warehouses.Add(item);
                datacontextModel.SaveChanges();
            }
            if (gridModel.WarehouseGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {
                Warehouse item = (from x in datacontextModel.Warehouses
                                    where x.WarehouseId == editedItem.WarehouseId
                                    select x)
                               .First<Warehouse>();

                // delete the record
                datacontextModel.Warehouses.Remove(item);
                datacontextModel.SaveChanges();
            }

            return RedirectToAction("Warehouse", "MyCompany");
        }
Example #17
0
        public ActionResult ProductEditRows(Product editedItem)
        {
            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            // If we are in "Edit" mode
            if (gridModel.WarehouseGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                // Get the data from and find the item corresponding to the edited row
                Product item = (from x in datacontextModel.Products
                                where x.ProductId == editedItem.ProductId
                                  select x).First<Product>();

                // update the item information
                UpdateProduct(item, editedItem);

                datacontextModel.SaveChanges();
            }

            if (gridModel.WarehouseGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {
                Product item = (from x in datacontextModel.Products
                                where x.ProductId == editedItem.ProductId
                                  select x)
                               .First<Product>();

                // delete the record
                datacontextModel.Products.Remove(item);
                datacontextModel.SaveChanges();
            }

            return RedirectToAction("Product", "Reference");
        }
Example #18
0
        public ActionResult Document(IEnumerable<HttpPostedFileBase> files, int? documentId,
            int doctypeId)
        {
            int? contractorId =null;

            string contractorIdStr = Request.Params["contractorId"].ToString();

            if (!String.IsNullOrEmpty(contractorIdStr))
            {
                int contractorIdInt = 0;
                Int32.TryParse(contractorIdStr, out contractorIdInt);
                if (contractorIdInt <= 0)
                    return Json(new { message = "Сначала выберите контрагента!", documentId = -1 });
                contractorId = contractorIdInt;
            }

            string docNumber = Request.Params["docNumber"];
            DateTime docCreatedOf = DateTime.Now;

            if(Request.Params["docCreatedOf"] != null)
            {
                docCreatedOf = Convert.ToDateTime(Request.Params["docCreatedOf"].ToString());
            }

            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                {
                    //Stream uploadFileStream = file.InputStream;

                    // If the file uploaded is "XLSX", convert it's Sheet1 to a NPOI document
                    if (file.FileName.EndsWith("xlsx"))
                    {
                        //logger.InfoFormat("Загружается файл:{0}", file.FileName);

                        string extension = ".xlsx";
                        string uploadsPath = Server.MapPath("~/uploads");
                        var filename = Path.Combine(uploadsPath, Session.LCID.ToString() + extension);
                        if (!Directory.Exists(uploadsPath))
                        {
                            Directory.CreateDirectory(uploadsPath);
                        }

                        file.SaveAs(filename);
                        //logger.InfoFormat("Загружен файл:{0}", filename);

                        var products = ExcelHelper.GetProductsData(filename, extension, "ProductLine-Template");

                        if (products != null)
                        {
                            // TODO: dublicated code. Merge with code in AddNewProductLine() method
                            var datacontextModel = new SkladDataContext();

                            // Add DocumentId if null
                            Document document = null;

                            if (documentId == null || documentId <= 0)
                            {
                                DocumentOperation docOp = new DocumentOperation();

                                docNumber = String.IsNullOrEmpty(docNumber) ?
                                    docOp.GetDocumentNumber(datacontextModel, DateTime.Now.Year, doctypeId).ToString()
                                    : docNumber.Trim().Replace(" ", "");

                                string secureFolderName = GenerateFolderName(String.Empty);
                                string commonFolderName = GenerateFolderName(secureFolderName);
                                // Create new document
                                document = new Document
                                {
                                    DocumentTypeId = doctypeId,
                                    CreatedOf = docCreatedOf,
                                    Comment = String.Empty,
                                    CreatedAt = DateTime.Now,
                                    Number = docNumber,
                                    IsCommitted = false,
                                    SecureFolderName = secureFolderName,
                                    CommonFolderName = commonFolderName,
                                    IsReportOutdated = true,
                                };
                                datacontextModel.Documents.Add(document);
                                datacontextModel.SaveChanges();

                                document = datacontextModel.Documents.Where(x => x.Number == docNumber &&
                                    x.DocumentTypeId == doctypeId
                                    && x.CreatedAt.Year == document.CreatedAt.Year
                                    && x.CreatedAt.Month == document.CreatedAt.Month
                                    && x.CreatedAt.Day == document.CreatedAt.Day
                                    && x.CreatedAt.Hour == document.CreatedAt.Hour
                                    && x.CreatedAt.Minute == document.CreatedAt.Minute).FirstOrDefault();
                            }
                            else
                            {
                                document = datacontextModel.Documents.Where(x => x.DocumentId == documentId).FirstOrDefault();
                            }

                            if (document == null)
                                return Json(new { message = String.Format("Не найден документ {0}!", documentId), documentId = -1 });

                            var contractor = datacontextModel.Contractors.Where(x => x.ContractorId == contractorId).FirstOrDefault();

                            if (contractor == null)
                                return Json(new { message = String.Format("Не найден контрагент {0}!", contractorId), documentId = -1 });

                            foreach (var productLine in products)
                            {
                                string article = productLine.ProductArticle.Trim().ToLower().Replace(" ", "");

                                var supplier = datacontextModel.Contractors.Where(x => x.Code == productLine.SupplierCode.Trim() &&
                                        x.ContractorTypeId == (int)EntityEnum.ContractorTypeEnum.Factory).FirstOrDefault();

                                if (supplier == null)
                                    return Json(new { message = String.Format("Фабрика {0} не найдена!", productLine.SupplierCode.Trim()), documentId = -1 });

                                decimal marginAbs = 0;

                                if (productLine.MarginAbs > 0)
                                    marginAbs = productLine.MarginAbs;
                                else if (productLine.SalePrice > 0)
                                {
                                    marginAbs = Math.Abs(productLine.SalePrice - productLine.PurchasePrice);

                                    if (marginAbs == 0)
                                        marginAbs = contractor.MarginAbs;
                                }
                                else
                                    marginAbs = contractor.MarginAbs;

                                Product product = GetOrCreateProduct(datacontextModel,
                                    supplier.ContractorId,
                                    productLine.PurchasePrice,
                                    marginAbs,
                                    article, String.Empty);

                                // Check if this productline already exists in document. if so, just
                                // change it value
                                ProductLine line = datacontextModel.ProductLines.Where(x => x.ProductId == product.ProductId &&
                                    x.DocumentId == document.DocumentId).FirstOrDefault();

                                string comment = productLine.Comment;
                                if (comment != null)
                                    comment = comment.Trim();

                                if (line == null)
                                {
                                    // Attach productLine to document
                                    line = new ProductLine
                                    {
                                        ProductArticle = article,
                                        SupplierCode = supplier.Code,
                                        SupplierId = supplier.ContractorId,
                                        Quantity = productLine.Quantity,
                                        PurchasePrice = productLine.PurchasePrice,
                                        SalePrice = productLine.PurchasePrice + marginAbs,
                                        MarginAbs = marginAbs,
                                        Discount = productLine.Discount,
                                        Comment = comment,
                                        ProductId = product.ProductId,
                                        DocumentId = document.DocumentId,
                                        Sum = productLine.Quantity * productLine.PurchasePrice,
                                        SaleSum = productLine.Quantity * (productLine.PurchasePrice + marginAbs)
                                    };

                                    if (document.Products == null)
                                        document.Products = new List<ProductLine>();

                                    document.Products.Add(line);
                                }
                                else
                                {
                                    line.ProductArticle = article;
                                    line.SupplierCode = supplier.Code;
                                    line.SupplierId = supplier.ContractorId;
                                    line.Quantity = productLine.Quantity;
                                    line.PurchasePrice = productLine.PurchasePrice;
                                    line.SalePrice = productLine.PurchasePrice + marginAbs;
                                    line.MarginAbs = marginAbs;
                                    line.Comment = comment;
                                    line.Discount = productLine.Discount;
                                    line.ProductId = product.ProductId;
                                    line.Sum = productLine.Quantity * productLine.PurchasePrice;
                                    line.SaleSum = productLine.Quantity * (productLine.PurchasePrice + marginAbs);
                                }
                                document.IsReportOutdated = true;
                                datacontextModel.SaveChanges();
                            }

                            document.IsReportOutdated = true;
                            datacontextModel.SaveChanges();

                            return Json(new { message = "Документ успешно обновлен/добавлен", documentId = document.DocumentId });
                        }
                    }
                    else
                    {
                        return Json(new { message = "Вы можете загружать только файлы Excel 2007-2010!", documentId = -1 });
                    }
                }
            }
            return Json(new { message = "Возникла критическая ошибка!", documentId = -1 });
        }
Example #19
0
        /// <summary>
        /// Удалить позиции из оприходования
        /// </summary>
        /// <param name="datacontextModel"></param>
        /// <param name="productId"></param>
        /// <param name="quantity"></param>
        private void RemoveProductFromPostingDocument(SkladDataContext datacontextModel, 
            int productId, int quantity)
        {
            var plines = datacontextModel.ProductLines.Where(x => x.ProductId == productId).ToList();

            foreach (var pline in plines)
            {
                // выбирать только из документа оприходование
                var doc = datacontextModel.Documents.Where(x => x.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Posting &&
                    x.DocumentId == pline.DocumentId && x.IsCommitted == true).FirstOrDefault();
                if(doc != null)
                {
                    if (pline.Quantity > quantity)
                    {
                        // just update product line
                        pline.Quantity = pline.Quantity - quantity;

                        break;
                    }
                    else if (pline.Quantity == quantity)
                    {
                        datacontextModel.ProductLines.Remove(pline);
                        break;
                    }
                    else
                    {
                        datacontextModel.ProductLines.Remove(pline);

                    }
                }
            }
            datacontextModel.SaveChanges();
        }
Example #20
0
        public ActionResult LegalEntityEditRows(LegalEntity editedItem)
        {
            // Get the grid and database models
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();

            // If we are in "Edit" mode
            if (gridModel.LegalEntityGrid.AjaxCallBackMode == AjaxCallBackMode.EditRow)
            {
                // Get the data from and find the item corresponding to the edited row
                LegalEntity item = (from x in datacontextModel.LegalEntities
                                    where x.LegalEntityId == editedItem.LegalEntityId
                               select x).First<LegalEntity>();

                // update the Order information
                UpdateLegalEntity(item, editedItem);

                datacontextModel.SaveChanges();
            }

            if (gridModel.LegalEntityGrid.AjaxCallBackMode == AjaxCallBackMode.AddRow)
            {
                // since we are adding a new item, create a new istance
                LegalEntity item = new LegalEntity();
                // set the new item information
                UpdateLegalEntity(item, editedItem);

                datacontextModel.LegalEntities.Add(item);
                datacontextModel.SaveChanges();
            }
            if (gridModel.LegalEntityGrid.AjaxCallBackMode == AjaxCallBackMode.DeleteRow)
            {
                LegalEntity item = (from x in datacontextModel.LegalEntities
                                    where x.LegalEntityId == editedItem.LegalEntityId
                               select x)
                               .First<LegalEntity>();

                // delete the record
                datacontextModel.LegalEntities.Remove(item);
                datacontextModel.SaveChanges();
            }

            return RedirectToAction("LegalEntity", "MyCompany");
        }