Exemple #1
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();
     }
 }
Exemple #2
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";
             */
        }
Exemple #3
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);
        }
Exemple #4
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;
        }
Exemple #5
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 });
        }
Exemple #6
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;
        }
Exemple #7
0
        private static void GenerateDocumentInfoRow(Document document, SheetStyle style)
        {
            string documentInfo = "Док. №"  + document.Number + ". "+ document.Contractor.Code + " от " + document.CreatedOf.ToString("dd.MM.yyyy");
            IRow row = style.Sheet.CreateRow(style.CurrentRowNum);
            ICell contractorCodeCell = row.CreateCell(0);
            contractorCodeCell.CellStyle = style.StyleBold;
            contractorCodeCell.SetCellValue(documentInfo);
            contractorCodeCell.RichStringCellValue.ApplyFont(0, documentInfo.Length, style.Font);
            contractorCodeCell.CellStyle = style.StyleBold;

            style.CurrentRowNum += 1;
        }