コード例 #1
0
ファイル: DocumentOperation.cs プロジェクト: sidby/sklad
        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;
        }
コード例 #2
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
 // This method is called when the grid requests data
 public JsonResult CustomerOrdersSearchGridDataRequested()
 {
     //// Get both the grid Model and the data Model
     var gridModel = new SkladJqGridModel();
     var datacontextModel = new SkladDataContext();
     // customize the default grid model with our custom settings
     CustomerOrdersSetupGrid(gridModel.DocumentGrid);
     return GetDocumentList(gridModel, datacontextModel, EntityEnum.DocumentTypeEnum.CustomerOrders);
 }
コード例 #3
0
ファイル: WarehouseController.cs プロジェクト: sidby/sklad
        // This method is called when the grid requests data
        public JsonResult CancellationSearchGridDataRequested()
        {
            // Get both the grid Model and the data Model
            // The data model in our case is an autogenerated linq2sql database based on Northwind.
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();
            // customize the default grid model with our custom settings
            CancellationSetupGrid(gridModel.DocumentGrid);

            return gridModel.DocumentGrid.DataBind(datacontextModel.Documents.Where(x =>
                x.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Cancellation));
        }
コード例 #4
0
ファイル: DocumentOperation.cs プロジェクト: sidby/sklad
 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();
     }
 }
コード例 #5
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        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);
        }
コード例 #6
0
ファイル: MyCompanyController.cs プロジェクト: sidby/sklad
        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);
        }
コード例 #7
0
ファイル: MyCompanyController.cs プロジェクト: sidby/sklad
        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);
        }
コード例 #8
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        public ActionResult ExportToExcelRefundsByDay(DateTime? refundsReportDate)
        {
            if(!refundsReportDate.HasValue)
                refundsReportDate = DateTime.Now;

            var gridModel = new SkladJqGridModel();
            var skladModel = new SkladDataContext();
            var grid = gridModel.ProductLineGrid;

            // Get the last grid state the we saved before in Session in the DataRequested action
            JQGridState gridState = Session["refundsProductLinesGridState"] as JQGridState;

            // Need to set grid options again
            SetUpRefundsProductLineColumns(grid);
            SetUpRefundsProductLineGroupingGrandTotal(grid);

            //if (String.IsNullOrEmpty(exportType))
            //    exportType = "1";
            // refundsReportDate
            //switch (exportType)
            //{
            //    case "1":

               // grid.ExportToExcel(GetRefundsProductLines(skladModel, refundsReportDate.Value), "refundsByDateGrid.xls", gridState);
                    //break;
            //    case "2":
            //        grid.ExportSettings.ExportDataRange = ExportDataRange.Filtered;
            //        grid.ExportToExcel(northWindModel.Orders, "grid.xls", gridState);
            //        break;
            //    case "3":
            //        grid.ExportSettings.ExportDataRange = ExportDataRange.FilteredAndPaged;
            //        grid.ExportToExcel(northWindModel.Orders, "grid.xls", gridState);
            //        break;
            //}

            return View();
        }
コード例 #9
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        private List<ProductLine> FilterProductLinesByManager(SkladDataContext context, int managerId, List<ProductLine> prods)
        {
            var filteredProducts = new List<ProductLine>();
            foreach (var product in prods)
            {
                var factory = context.Contractors.Where(x => x.Code.ToLower() == product.SupplierCode.ToLower()).FirstOrDefault();
                // failed to find factory. In this case - dont miss product
                if (factory == null)
                    filteredProducts.Add(product);
                else if(factory.ResponsibleId == managerId)
                    filteredProducts.Add(product);
            }

            return filteredProducts;
        }
コード例 #10
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        public JsonResult RefundsProductSearchGridDataRequested(DateTime? refundsReportDate)
        {
            if (!refundsReportDate.HasValue)
                refundsReportDate = DateTime.Now;

            // Get both the grid Model and the data Model
            // The data model in our case is an autogenerated linq2sql database based on Northwind.
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();
            SetUpRefundsProductLineColumns(gridModel.ProductLineGrid);
            SetUpRefundsProductLineGroupingGrandTotal(gridModel.ProductLineGrid);
            // customize the default grid model with our custom settings
            //JQGridState gridState = gridModel.ProductLineGrid.GetState();

            // Need this to enable ExportToExcelRefundsByDay
            // Session["refundsProductLinesGridState"] = gridState;
            int contractorId = 0;
            if (Request.Params["contractorId"] != null)
                Int32.TryParse(Request.Params["contractorId"].ToString(), out contractorId);

            int managerId = 0;
            if (Request.Params["managerId"] != null)
                Int32.TryParse(Request.Params["managerId"].ToString(), out managerId);

            return gridModel.ProductLineGrid.DataBind(GetRefundsProductLines(datacontextModel, refundsReportDate.Value, contractorId, managerId));
        }
コード例 #11
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        // This method is called when the grid requests data
        public JsonResult ShipmentSearchGridDataRequested()
        {
            // Get both the grid Model and the data Model
            // The data model in our case is an autogenerated linq2sql database based on Northwind.
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();
            // customize the default grid model with our custom settings
            ShipmentSetupGrid(gridModel.DocumentGrid);

            return GetDocumentList(gridModel, datacontextModel, EntityEnum.DocumentTypeEnum.Shipment);
        }
コード例 #12
0
ファイル: HomeController.cs プロジェクト: sidby/sklad
        /*
          "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);
        }
コード例 #13
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        public string GetRefundsReportFileLink(DateTime refundsReportDate, int contractorId, int managerId)
        {
            string relativePath = "../" + Constants.RefundsReportPath;
            string rootPath = Server.MapPath(relativePath);
            string reportFile = String.Empty;

            // Check if file already exists.
            // Than check Modified date of the file in file name
            string docPath = Path.Combine(rootPath, contractorId.ToString(), refundsReportDate.ToString("yyyy-MM-dd"));

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

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

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

            // check if file is actual upon document modified date
            if (existingFile != null)
            {
                // Cache 1 minute
                if (existingFile.CreationTime.AddSeconds(10) > DateTime.Now)
                {
                    // return cached file
                    return String.Format("{0}/{1}/{2}/{3}", relativePath, contractorId.ToString(), refundsReportDate.ToString("yyyy-MM-dd"),
                         existingFile.Name);
                }
                else
                {
                    // delete outdate file
                    existingFile.Delete();
                }
            }

            var context = new SkladDataContext();
            // Get refunds products by day
            var products = GetRefundsProductLines(context, refundsReportDate, contractorId, managerId);
            if (products.Count() > 0)
            {
                string fileName = String.Format("{0}{1}{4}{2}{4}{3}{5}", Constants.RefundsReportPrefix,
                    refundsReportDate.Year, refundsReportDate.ToString("MM"), refundsReportDate.ToString("dd"),
                    dateSeparator, extension);

                string clientName = String.Empty;
                if (contractorId > 0)
                {
                    var contractor = context.Contractors.Where(x => x.ContractorId == contractorId).FirstOrDefault();
                    if (contractor != null)
                        clientName = contractor.Code;
                }
                else
                    clientName = "По всем клиентам";

                string titleRight =  "Возврат от " + refundsReportDate.ToString("dd.MM.yyyy");
                if (managerId > 0)
                {

                    var user = context.UserProfiles.Where(x => x.UserId == managerId).FirstOrDefault();
                    if (user != null)
                        titleRight += ". Менеджер: " + user.DisplayName;
                }

                // create report
                ExcelReportInfo reportInfo = new ExcelReportInfo
                {
                    CreatedOf = refundsReportDate,
                    FileName = fileName,
                    FilePath = docPath,
                    DocumentSubject = "Возврат от " + refundsReportDate.ToString("dd.MM.yyyy"),
                    SheetName = Constants.RefundsReportPrefix + refundsReportDate.ToString("dd.MM.yyyy"),
                    TitleLeft = clientName,
                    TitleCenter = refundsReportDate.ToString("dd.MM.yyyy"),
                    TitleRight = titleRight
                };

                ReportHelper.GenerateProductLinesReport(products.ToList(), reportInfo);
                // ../Reports/Document/1093/e4fmt/Report-2014-10-09.xls
                //  /Reports/Refunds/RefundsReport-2014-10-09.xls
                reportFile = String.Format("{0}/{1}/{2}/{3}", relativePath, contractorId.ToString(), refundsReportDate.ToString("yyyy-MM-dd"),
                   fileName);
            }
            return reportFile;
        }
コード例 #14
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        void RefundsProductLineGroupingGrandTotal_DataResolved(object sender, JQGridDataResolvedEventArgs e)
        {
            if (Request.Params["refundsReportDate"] != null)
            {
                DateTime reportDate = DateTime.Now;
                int contractorId = 0;
                DateTime.TryParse(Request.Params["refundsReportDate"].ToString(), out reportDate);
                Int32.TryParse(Request.Params["contractorId"].ToString(), out contractorId);

                if (reportDate != DateTime.Now)
                {
                    try
                    {
                        JQGridColumn saleSumColumn = e.GridModel.Columns.Find(c => c.DataField == "SaleSum");
                        JQGridColumn sumColumn = e.GridModel.Columns.Find(c => c.DataField == "Sum");
                        JQGridColumn quantityColumn = e.GridModel.Columns.Find(c => c.DataField == "Quantity");
                        // Записывать клиентов от которых были возвраты
                        JQGridColumn commentColumn = e.GridModel.Columns.Find(c => c.DataField == "Comment");
                        var datacontextModel = new SkladDataContext();

                        // TODO: Найти все документы возврата за указанный день и выбрать по ним сумму
                        string saleSum = "0", sum = "0", quantity = "0";
                        List<Document> docs = null;
                        if (contractorId > 0)
                            docs = datacontextModel.Documents.Where(x => x.CreatedOf == reportDate && x.IsCommitted == true
                                && x.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Refunds && x.ContractorId == contractorId).ToList();
                        else
                           docs = datacontextModel.Documents.Where(x => x.CreatedOf == reportDate && x.IsCommitted == true && x.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Refunds).ToList();

                        if (docs != null)
                        {
                            if (docs.Count > 0)
                            {
                                var docIds = docs.Select(x => x.DocumentId).ToArray();
                                commentColumn.FooterValue = "Возвраты от: " +  String.Join(", ",docs.Select(x => x.Contractor.Code).Distinct().ToArray());
                                // ids.Contains(e.SuchID)
                                saleSum = (from o in datacontextModel.ProductLines where docIds.Contains(o.DocumentId) select o.SaleSum)
                                .Sum().ToString();

                                sum = (from o in datacontextModel.ProductLines where docIds.Contains(o.DocumentId) select o.Sum)
                                    .Sum().ToString();

                                quantity = (from o in datacontextModel.ProductLines where docIds.Contains(o.DocumentId) select o.Quantity)
                                .Sum().ToString();
                            }
                        }

                        saleSumColumn.FooterValue = "Итого: " + saleSum;
                        sumColumn.FooterValue = "Итого: " + sum;
                        quantityColumn.FooterValue = "Итого: " + quantity;

                    }
                    catch (Exception ex)
                    {
                        logger.Error("Ошибка при подсчёте итоговых сумм: " + ex.Message);
                    }
                }
            }
        }
コード例 #15
0
ファイル: HomeController.cs プロジェクト: sidby/sklad
        public JsonResult GetContractorByCodeAutoComplete(string term)
        {
            var datacontextModel = new SkladDataContext();

            var result = (from u in datacontextModel.Contractors
                          where u.Code.ToLower().Contains(term.ToLower())
                          select u.Code).ToList();

            return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = result };
        }
コード例 #16
0
ファイル: HomeController.cs プロジェクト: sidby/sklad
        public JsonResult GetProductByArticle(string term, int supplierId)
        {
            if (supplierId <= 0)
                return null;

            var datacontextModel = new SkladDataContext();

            var result = (from u in datacontextModel.Products
                          where u.Article.ToLower().Contains(term.ToLower()) && u.ContractorId ==
                          supplierId
                          select new ProductArticlePriceModel { Article = u.Article, ProductId = u.ProductId, PurchasePrice = u.PurchasePrice, Description = u.Description }).ToList();

            if(result != null)
            {
                if(result.Count > 0)
                {
                    // Check if this product exists in warehouse
                    var inWarehouseDocIds = (from u in datacontextModel.Documents
                                       where u.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Posting && u.IsCommitted == true
                                       select u.DocumentId ).ToList();

                    if (inWarehouseDocIds != null)
                    {
                        if (inWarehouseDocIds.Count > 0)
                        {
                            var productIds = result.Select(x => x.ProductId).ToList();
                            var result2 = (from u in datacontextModel.ProductLines
                                           where inWarehouseDocIds.Contains(u.DocumentId) && productIds.Contains(u.ProductId.Value)
                                           select new ProductArticlePriceModel {  ProductId = u.ProductId.Value, Quantity = u.Quantity, Description = u.Comment }).ToList();
                            if (result2 != null)
                            {
                                if (result2.Count > 0)
                                {
                                    // может быть несколько документов с одинаковым товаром. Поэтому их нужно объединить
                                    List<ProductArticlePriceModel> summed = result2.GroupBy(row => row.ProductId)
                                          .Select(g => new ProductArticlePriceModel()
                                          {
                                              ProductId = g.Key,
                                              Quantity = g.Sum(x => x.Quantity),

                                          }).ToList();

                                    foreach (var item in summed)
                                    {
                                        var it = result.Where(x => x.ProductId == item.ProductId).FirstOrDefault();
                                        if (it != null)
                                        {
                                            it.Quantity = item.Quantity;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = result };
        }
コード例 #17
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        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");
        }
コード例 #18
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        // This method is called when the grid requests data
        public JsonResult ContractorSearchGridDataRequested()
        {
            // Get both the grid Model and the data Model
            // The data model in our case is an autogenerated linq2sql database based on Northwind.
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();
            // customize the default grid model with our custom settings
            ContractorSetupGrid(gridModel.ContractorGrid);

            // return the result of the DataBind method, passing the datasource as a parameter
            // jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
            return gridModel.ContractorGrid.DataBind(datacontextModel.Contractors);
        }
コード例 #19
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        public JsonResult GetSupplierByCode(string term)
        {
            var datacontextModel = new SkladDataContext();

            var result = (from u in datacontextModel.Contractors
                          where u.Code.ToLower().Contains(term.ToLower()) && u.ContractorTypeId ==
                          (int)EntityEnum.ContractorTypeEnum.Factory
                          select new { u.Code, u.ContractorId, u.Name }).ToList();

            return Json(result, JsonRequestBehavior.AllowGet);
        }
コード例 #20
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        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");
        }
コード例 #21
0
ファイル: IndicatorsController.cs プロジェクト: sidby/sklad
        public ActionResult Index()
        {
            ViewBag.Message = "Графики на Highcharts.";

            var gridModel = new LogJqGridModel();
            var grid = gridModel.LogGrid;

            // NOTE: you need to call this method in the action that fetches the data as well,
            // so that the models match
            LogSetupGrid(grid);

            IndicatorsModel model = new IndicatorsModel() { LogGrid = gridModel };
            SkladDataContext context = new SkladDataContext();

            // Check permissions
            int currentUserId = WebSecurity.CurrentUserId;
            string[] roles = Roles.GetRolesForUser(WebSecurity.CurrentUserName);
            if (roles.Contains("limitedemployee"))
            {
                IQueryable<UserProfile> userProfiles = context.UserProfiles.Where(x => x.UserId == currentUserId);
                model.Employees = userProfiles;
                model.Managers = userProfiles;
            }
            else
            {
                model.Employees = context.UserProfiles.Where(x => x.ContactTypeId == (int)EntityEnum.ContactTypeEnum.Employee);
                model.Managers = context.UserProfiles
                .Where(x => x.ContactTypeId == (int)EntityEnum.ContactTypeEnum.Manager || x.ContactTypeId == (int)EntityEnum.ContactTypeEnum.Employee);
            }
            /*employee

            var result = (from u in datacontextModel.UserProfiles
                          where u.DisplayName.ToLower().Contains(term.ToLower()) && (u.ContactTypeId ==
                          (int)EntityEnum.ContactTypeEnum.Manager || u.ContactTypeId == (int)EntityEnum.ContactTypeEnum.Employee)
                          select new { u.DisplayName, u.UserId }).ToList();
             */

            return View(model);
        }
コード例 #22
0
ファイル: HomeController.cs プロジェクト: sidby/sklad
        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";
             */
        }
コード例 #23
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        private JsonResult GetDocumentList(SkladJqGridModel gridModel, 
            SkladDataContext datacontextModel, EntityEnum.DocumentTypeEnum docType)
        {
            string contractorIdStr = Request.QueryString["ContractorId"];
            if (!String.IsNullOrEmpty(contractorIdStr))
            {
                var contractor = datacontextModel.Contractors.Where(x =>
                    x.Code.ToLower() == contractorIdStr.ToLower()).FirstOrDefault();
                if (contractor != null)
                {
                    // ContractorName
                    return gridModel.DocumentGrid.DataBind(datacontextModel
                        .Documents.Include("Contractor").Where(x => x.ContractorId == contractor.ContractorId &&
                           x.DocumentTypeId == (int)docType));
                }
            }

            return gridModel.DocumentGrid.DataBind(datacontextModel.Documents.Include("Contractor").Where(x =>
                x.DocumentTypeId == (int)docType));
        }
コード例 #24
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        // This method is called when the grid requests data
        public JsonResult ProductSearchGridDataRequested()
        {
            // Get both the grid Model and the data Model
            // The data model in our case is an autogenerated linq2sql database based on Northwind.
            var gridModel = new SkladJqGridModel();
            var datacontextModel = new SkladDataContext();
            // customize the default grid model with our custom settings
            ProductSetupGrid(gridModel.ProductGrid);

            string contractorIdStr = Request.QueryString["ContractorId"];
            if (!String.IsNullOrEmpty(contractorIdStr))
            {
                var contractor = datacontextModel.Contractors.Where(x =>
                    x.Code.ToLower() == contractorIdStr.ToLower()).FirstOrDefault();
                if (contractor != null)
                {

                    return gridModel.ProductGrid.DataBind(datacontextModel
                        .Products.Where(x => x.ContractorId == contractor.ContractorId).Include(x => x.Supplier));
                }
            }

            // return the result of the DataBind method, passing the datasource as a parameter
            // jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
            return gridModel.ProductGrid.DataBind(datacontextModel.Products.Include(x => x.Supplier));
        }
コード例 #25
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        private IQueryable<ProductLine> GetRefundsProductLines(SkladDataContext context, DateTime day, int? contractorId, int? managerId)
        {
            List<Document> docs = null;
            if (contractorId.HasValue && contractorId.Value > 0)
            {
                docs = context.Documents
                .Where(x => x.CreatedOf == day && x.IsCommitted == true && x.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Refunds
                && x.ContractorId == contractorId.Value).ToList();
            }
            else {
                docs = context.Documents
                  .Where(x => x.CreatedOf == day && x.IsCommitted == true && x.DocumentTypeId == (int)EntityEnum.DocumentTypeEnum.Refunds).ToList();
            }
            if (docs != null)
            {
                if (docs.Count > 0)
                {
                    var docIds = docs.Select(x => x.DocumentId).ToArray();
                    var products = context.ProductLines.Where(x => docIds.Contains(x.DocumentId));

                    if (managerId.HasValue && managerId.Value > 0)
                        products = FilterProductLinesByManager(context, managerId.Value, products.ToList()).AsQueryable();
                    if (contractorId.HasValue && contractorId.Value > 0)
                        return products;
                    else
                    {
                        // в комментариях указать клиента
                        foreach (var product in products)
                        {
                            var docsP = context.Documents.Where(x => x.DocumentId == product.DocumentId).FirstOrDefault();
                            if (docsP != null) {
                                product.Comment = "Возврат от: " + docsP.Contractor.Code + ". " + product.Comment;
                            }
                        }

                        return products.AsQueryable();
                    }
                }
            }

            return new List<ProductLine>().AsQueryable();
        }
コード例 #26
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        private void SetUpContractorEditDropDown(JQGrid itemGrid)
        {
            // setup the grid search criteria for the columns
            JQGridColumn responsibleIdColumn = itemGrid.Columns.Find(c => c.DataField == "ResponsibleId");
            //JQGridColumn responsibleNameColumn = itemGrid.Columns.Find(c => c.DataField == "ResponsibleName");

            //JQGridColumn regionIdColumn = itemGrid.Columns.Find(c => c.DataField == "RegionId");
            JQGridColumn contractorTypeIdColumn = itemGrid.Columns.Find(c => c.DataField == "ContractorTypeId");

            // Populate the search dropdown only on initial request, in order to optimize performance
            if (itemGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
            {
                var skladModel = new SkladDataContext();

                // Выбрать только Сотрудников и менеджеров
                var usersList = (from m in skladModel.UserProfiles where m.ContactTypeId < 3 select m).AsEnumerable()
                               .Select(x => new SelectListItem
                               {
                                   Text = x.DisplayName,
                                   Value = x.UserId.ToString()
                               });

                //var regionsList = (from m in skladModel.Regions select m).AsEnumerable()
                //              .Select(x => new SelectListItem
                //              {
                //                  Text = x.Name,
                //                  Value = x.RegionId.ToString()
                //              });

                var contractorTypesList = (from m in skladModel.ContractorTypes select m).AsEnumerable()
                            .Select(x => new SelectListItem
                            {
                                Text = x.Name,
                                Value = x.ContractorTypeId.ToString()
                            });

                responsibleIdColumn.EditList.AddRange(usersList.ToList<SelectListItem>());
                responsibleIdColumn.SearchList = usersList.ToList<SelectListItem>();
                responsibleIdColumn.SearchList.Insert(0, new SelectListItem { Text = "Все", Value = "" });

                //regionIdColumn.SearchList = regionsList.ToList<SelectListItem>();
                //regionIdColumn.SearchList.Insert(0, new SelectListItem { Text = "Все", Value = "" });
                //regionIdColumn.EditList.AddRange(regionsList.ToList<SelectListItem>());

                contractorTypeIdColumn.SearchList = contractorTypesList.ToList<SelectListItem>();
                contractorTypeIdColumn.SearchList.Insert(0, new SelectListItem { Text = "Все", Value = "" });
                contractorTypeIdColumn.EditList.AddRange(contractorTypesList.ToList<SelectListItem>());
            }
        }
コード例 #27
0
ファイル: SaleController.cs プロジェクト: sidby/sklad
        private void SetUpContractorEmployeeEditDropDown(JQGrid itemGrid)
        {
            JQGridColumn employeeNameColumn = itemGrid.Columns.Find(c => c.DataField == "EmployeeName");
            employeeNameColumn.Visible = true;

            JQGridColumn contractorNameColumn = itemGrid.Columns.Find(c => c.DataField == "ContractorName");
            contractorNameColumn.Visible = true;
            JQGridColumn contractorIdColumn = itemGrid.Columns.Find(c => c.DataField == "ContractorId");
            contractorIdColumn.Visible = true;

            JQGridColumn saleSumColumn = itemGrid.Columns.Find(c => c.DataField == "SaleSum");
            saleSumColumn.Visible = true;

            // setup the grid search criteria for the columns
            JQGridColumn employeeIdColumn = itemGrid.Columns.Find(c => c.DataField == "EmployeeId");
            employeeIdColumn.Visible = true;

            // Populate the search dropdown only on initial request, in order to optimize performance
            if (itemGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
            {
                var skladModel = new SkladDataContext();

                // Выбрать только Сотрудников и менеджеров
                var usersList = (from m in skladModel.UserProfiles
                                 where m.ContactTypeId == (int)EntityEnum.ContactTypeEnum.Employee select m).AsEnumerable()
                               .Select(x => new SelectListItem
                               {
                                   Text = x.DisplayName,
                                   Value = x.UserId.ToString()
                               });

                employeeIdColumn.EditList.AddRange(usersList.ToList<SelectListItem>());
                employeeIdColumn.SearchList = usersList.ToList<SelectListItem>();
                employeeIdColumn.SearchList.Insert(0, new SelectListItem { Text = "Все", Value = "" });
            }
        }
コード例 #28
0
ファイル: HomeController.cs プロジェクト: sidby/sklad
        public JsonResult GetDocumentsByProduct(int productId, int documentTypeId)
        {
            if (productId <= 0)
                return null;

            var datacontextModel = new SkladDataContext();

            // Get product Id

            var result = (from u in datacontextModel.ProductLines.Include("Document")

                          where u.ProductId == productId
                          select new { u.DocumentId,
                              u.Document.IsCommitted, u.Document.Number,
                              u.Document.DocumentTypeId,
                              u.Document.CreatedOf,
                                }).Where(x => x.DocumentTypeId == documentTypeId).OrderByDescending(u => u.CreatedOf).ToList();

            return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = result };
        }
コード例 #29
0
ファイル: ReferenceController.cs プロジェクト: sidby/sklad
        public JsonResult GetSupplierByCodeAutoComplete(string term)
        {
            var datacontextModel = new SkladDataContext();

            var result = (from u in datacontextModel.Contractors
                          where u.Code.ToLower().Contains(term.ToLower()) && u.ContractorTypeId ==
                          (int)EntityEnum.ContractorTypeEnum.Factory
                          select u.Code).ToList();
            // "name":"ContractorId","index":"ContractorId"
            //  return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = dataSource.ToListOfString(this) };
            // List<string>
             //22 - Бьюти
            return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = result };
        }
コード例 #30
0
ファイル: HomeController.cs プロジェクト: sidby/sklad
        /*
              "documentId": $("#DocId").val(),
                          "docNumber": $("#DocumentItem_Number").val(),
                          "docCreatedOf": $("#createdOfDatepicker").datepicker("getDate").toJSONLocal(),
                          "docComment": $("#DocumentItem_Comment").val(),
                          "docContractorId": $("#ContractorDocId").val(),
                          "docEmployeeId": $("#DocumentItem_Employee_UserId").val(),
                          "docPlanDate": !$("#planDateDatepicker").val() ? null : $("#planDateDatepicker").datepicker("getDate").toJSONLocal(),

         */
        public string GetReportFileLink(int documentId, string docNumber,
           DateTime docCreatedOf, string docComment,
           int? docContractorId, int? docEmployeeId,
           DateTime? docPlanDate
         )
        {
            if (documentId <= 0)
                return Constants.ErrorUrl;

            var datacontextModel = new SkladDataContext();

            var document = datacontextModel.Documents.Include("Products")
                .Include("Contractor").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;

            // 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);

            return GetReportFile(datacontextModel, document, EntityEnum.ReportType.SaleReport);
        }