public ActionResult AddToInventory(int id = 0) { if (!Authorized(RoleType.InventoryManager)) return Error(Loc.Dic.error_no_permission); Order order; List<Location> locations = null; AddToInventoryModel model = new AddToInventoryModel(); using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId)) using (LocationsRepository locationsRep = new LocationsRepository(CurrentUser.CompanyId)) { order = orderRep.GetEntity(id, "Supplier", "Orders_OrderToItem", "Orders_OrderToItem.Orders_Items"); if (order == null) return Error(Loc.Dic.error_order_not_found); if (order.StatusId < (int)StatusType.InvoiceApprovedByOrderCreatorPendingFileExport) return Error(Loc.Dic.error_order_not_approved); locations = locationsRep.GetList().OrderBy(x => x.Name).ToList(); if (locations == null || locations.Count == 0) return Error(Loc.Dic.error_no_locations_found); } model.OrderId = order.Id; model.OrderItems = order.Orders_OrderToItem.ToList(); model.LocationsList = new SelectList(locations, "Id", "Name"); return View(model); }
public ActionResult AddToInventory(AddToInventoryModel model) { if (!Authorized(RoleType.InventoryManager)) return Error(Loc.Dic.error_no_permission); Order order; List<Inventory> createdItems = new List<Inventory>(); List<Location> locations; bool noCreationErrors = true; using (InventoryRepository inventoryRep = new InventoryRepository(CurrentUser.CompanyId)) using (LocationsRepository locationsRep = new LocationsRepository(CurrentUser.CompanyId)) using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRep.GetEntity(model.OrderId, "Supplier", "Orders_OrderToItem", "Orders_OrderToItem.Orders_Items"); if (order == null) return Error(Loc.Dic.error_order_get_error); if (order.WasAddedToInventory) return Error(Loc.Dic.error_order_was_added_to_inventory); if (order.StatusId < (int)StatusType.InvoiceApprovedByOrderCreatorPendingFileExport) return Error(Loc.Dic.error_invoice_not_scanned_and_approved); locations = locationsRep.GetList().ToList(); if (locations == null || locations.Count == 0) return Error(Loc.Dic.error_no_locations_found); foreach (SplittedInventoryItem splitedItem in model.InventoryItems) { if (!noCreationErrors) break; if (!splitedItem.AddToInventory) continue; int? itemId = splitedItem.ItemsToAdd[0].ItemId; Orders_OrderToItem originalItem = order.Orders_OrderToItem.FirstOrDefault(x => x.Id == itemId); bool isValidList = originalItem != null && splitedItem.ItemsToAdd.All(x => x.ItemId == itemId); if (!isValidList) { noCreationErrors = false; break; } if (splitedItem.ItemsToAdd.Count == 1) { Inventory listItem = splitedItem.ItemsToAdd[0]; if (!locations.Any(x => x.Id == listItem.LocationId)) return Error(Loc.Dic.error_invalid_form); Inventory newItem = new Inventory() { AssignedTo = listItem.AssignedTo, LocationId = listItem.LocationId, Notes = listItem.Notes, SerialNumber = listItem.SerialNumber, Status = listItem.Status, WarrentyPeriodStart = listItem.WarrentyPeriodStart, WarrentyPeriodEnd = listItem.WarrentyPeriodEnd, ItemId = originalItem.ItemId, OrderId = order.Id, CompanyId = CurrentUser.CompanyId, IsOutOfInventory = false, OriginalQuantity = originalItem.Quantity, RemainingQuantity = originalItem.Quantity }; if (!inventoryRep.Create(newItem)) { noCreationErrors = false; break; } createdItems.Add(newItem); } else if (originalItem.Quantity == splitedItem.ItemsToAdd.Count) { foreach (var item in splitedItem.ItemsToAdd) { if (!locations.Any(x => x.Id == item.LocationId)) { noCreationErrors = false; break; } item.ItemId = originalItem.ItemId; item.OrderId = order.Id; item.CompanyId = CurrentUser.CompanyId; item.IsOutOfInventory = false; if (!inventoryRep.Create(item)) { noCreationErrors = false; break; } createdItems.Add(item); } } else { noCreationErrors = false; break; } } if (!noCreationErrors) { foreach (var item in createdItems) { inventoryRep.Delete(item.Id); } return Error(Loc.Dic.error_inventory_create_error); } order.WasAddedToInventory = true; order.LastStatusChangeDate = DateTime.Now; if (ordersRep.Update(order) == null) return Error(Loc.Dic.error_database_error); bool hasInventoryItems = model.InventoryItems.Any(x => x.AddToInventory); string notes = hasInventoryItems ? Loc.Dic.AddToInventory_with_inventory_items : Loc.Dic.AddToInventory_no_inventory_items; int? historyActionId = null; historyActionId = (int)HistoryActions.AddedToInventory; Orders_History orderHistory = new Orders_History(); using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, order.Id)) if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value, notes); return RedirectToAction("PendingInventory"); } }
public ActionResult Edit(CreateOrderModel model, string itemsString) { if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission); if (!ModelState.IsValid) return Error(Loc.Dic.error_invalid_form); // Initializing needed temporary variables bool wasReturnedToCreator; bool allowExeeding = true; List<Orders_OrderToAllocation> AllocationsToCreate = new List<Orders_OrderToAllocation>(); Order orderFromDatabase; List<Orders_OrderToItem> itemsFromEditForm = new List<Orders_OrderToItem>(); List<Orders_OrderToItem> itemsToDelete = new List<Orders_OrderToItem>(); List<Orders_OrderToItem> itemsToCreate = new List<Orders_OrderToItem>(); List<Orders_OrderToItem> itemsToUpdate = new List<Orders_OrderToItem>(); decimal totalOrderPrice; decimal totalAllocation; List<Budgets_Allocations> orderAllocations = new List<Budgets_Allocations>(); using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId)) { orderFromDatabase = orderRep.GetEntity(model.Order.Id, "Supplier", "Orders_OrderToItem", "Orders_OrderToAllocation", "Users_ApprovalRoutes.Users_ApprovalStep"); } if (orderFromDatabase == null) return Error(Loc.Dic.error_order_not_found); if (orderFromDatabase.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission); if (orderFromDatabase.StatusId != (int)StatusType.Pending && orderFromDatabase.StatusId != (int)StatusType.PendingOrderCreator) return Error(Loc.Dic.error_order_edit_after_approval); wasReturnedToCreator = orderFromDatabase.StatusId == (int)StatusType.PendingOrderCreator; itemsFromEditForm = ItemsFromString(itemsString, model.Order.Id); if (itemsFromEditForm == null) return Error(Loc.Dic.error_invalid_form); if (itemsFromEditForm.Count == 0) return Error(Loc.Dic.error_order_has_no_items); if (itemsFromEditForm.Count == 0) return Error(Loc.Dic.error_order_has_no_items); totalOrderPrice = (decimal.Floor(itemsFromEditForm.Sum(x => x.SingleItemPrice * x.Quantity) * 1000) / 1000); if (model.Allocations == null || model.Allocations.Where(x => x.IsActive).Count() == 0) return Error(Loc.Dic.error_invalid_form); model.Allocations = model.Allocations.Where(x => x.IsActive).ToList(); totalAllocation = (decimal.Floor(model.Allocations.Sum(x => x.Amount) * 1000) / 1000); if (totalOrderPrice != totalAllocation) return Error(Loc.Dic.error_order_insufficient_allocation); using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId)) using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId)) { Budget currentBudget = budgetsRep.GetList().SingleOrDefault(x => x.CompanyId == CurrentUser.CompanyId && x.IsActive); if (currentBudget == null) return Error(Loc.Dic.error_database_error); model.Order.BudgetId = currentBudget.Id; int[] orderAllocationsIds = model.Allocations.Select(x => x.AllocationId).Distinct().ToArray(); var allocationsData = allocationsRep.GetAllocationsData(orderAllocationsIds, StatusType.Pending); bool IsValidAllocations = (allocationsData.Count == orderAllocationsIds.Length) && model.Allocations.All(x => (x.MonthId == null || (x.MonthId >= 1 && x.MonthId <= 12)) && x.Amount > 0); if (!IsValidAllocations) return Error(Loc.Dic.error_invalid_form); if (model.IsFutureOrder) { foreach (var allocationData in allocationsData) { List<OrderAllocation> allocationMonths = model.Allocations.Where(x => x.AllocationId == allocationData.AllocationId).ToList(); foreach (var month in allocationMonths) { if (month.MonthId == DateTime.Now.Month) { OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId); var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month, orderFromDatabase.Id); if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation); AllocationsToCreate.AddRange(newAllocations); } else { var monthData = allocationData.Months.SingleOrDefault(x => x.MonthId == month.MonthId); if (!allowExeeding && month.Amount > monthData.RemainingAmount) return Error(Loc.Dic.error_order_insufficient_allocation); Orders_OrderToAllocation newAllocation = new Orders_OrderToAllocation() { AllocationId = allocationData.AllocationId, MonthId = month.MonthId.Value, Amount = month.Amount, OrderId = orderFromDatabase.Id }; AllocationsToCreate.Add(newAllocation); } } } } else { foreach (var allocationData in allocationsData) { OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId); var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month, orderFromDatabase.Id); if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation); AllocationsToCreate.AddRange(newAllocations); } } } using (OrderToAllocationRepository orderAllocationRep = new OrderToAllocationRepository()) { foreach (var item in orderFromDatabase.Orders_OrderToAllocation) { orderAllocationRep.Delete(item.Id); } foreach (var item in AllocationsToCreate) { orderAllocationRep.Create(item); } } foreach (var newItem in itemsFromEditForm) { Orders_OrderToItem existingItem = orderFromDatabase.Orders_OrderToItem.SingleOrDefault(x => x.ItemId == newItem.ItemId); if (existingItem != null) { if ( existingItem.Quantity != newItem.Quantity || existingItem.SingleItemPrice != newItem.SingleItemPrice ) { newItem.Id = existingItem.Id; itemsToUpdate.Add(newItem); } } else { itemsToCreate.Add(newItem); } } foreach (var existingItem in orderFromDatabase.Orders_OrderToItem) { Orders_OrderToItem newItem = itemsFromEditForm.SingleOrDefault(x => x.ItemId == existingItem.ItemId); if (newItem == null) { itemsToDelete.Add(existingItem); } } bool noErrors = true; using (OrderToItemRepository orderToItemRep = new OrderToItemRepository()) { foreach (var item in itemsToCreate) { if (!orderToItemRep.Create(item) && noErrors) noErrors = false; } foreach (var item in itemsToUpdate) { if (orderToItemRep.Update(item) == null && noErrors) noErrors = false; } foreach (var item in itemsToDelete) { if (!orderToItemRep.Delete(item.Id) && noErrors) noErrors = false; } using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { if (!CurrentUser.OrdersApprovalRouteId.HasValue) { model.Order.NextOrderApproverId = null; model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice; } else { Users_ApprovalRoutes orderRoute = orderFromDatabase.Users_ApprovalRoutes; //routesRep.GetEntity(CurrentUser.OrdersApprovalRouteId.Value, "Users_ApprovalStep"); Users_ApprovalStep firstStep = orderRoute.Users_ApprovalStep.OrderBy(x => x.StepNumber).FirstOrDefault(); if (firstStep != null) { model.Order.ApprovalRouteId = orderRoute.Id; model.Order.ApprovalRouteStep = firstStep.StepNumber; model.Order.NextOrderApproverId = firstStep.UserId; model.Order.StatusId = (int)StatusType.Pending; } else { model.Order.ApprovalRouteId = null; model.Order.ApprovalRouteStep = null; model.Order.NextOrderApproverId = null; model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice; } } model.Order.CompanyId = orderFromDatabase.CompanyId; model.Order.CreationDate = orderFromDatabase.CreationDate; model.Order.SupplierId = orderFromDatabase.SupplierId; model.Order.UserId = orderFromDatabase.UserId; model.Order.OrderNumber = orderFromDatabase.OrderNumber; model.Order.InvoiceNumber = orderFromDatabase.InvoiceNumber; model.Order.InvoiceDate = orderFromDatabase.InvoiceDate; model.Order.LastStatusChangeDate = DateTime.Now; model.Order.ValueDate = orderFromDatabase.ValueDate; model.Order.WasAddedToInventory = orderFromDatabase.WasAddedToInventory; model.Order.IsFutureOrder = model.IsFutureOrder; model.Order.Price = totalOrderPrice; ordersRep.Update(model.Order); model.Order = ordersRep.GetEntity(model.Order.Id, "User", "User1"); } } if (noErrors) { int? historyActionId = null; historyActionId = (int)HistoryActions.Edited; Orders_History orderHistory = new Orders_History(); using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, model.Order.Id)) if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value, model.NotesForApprover); if (wasReturnedToCreator) { if (model.Order.NextOrderApproverId.HasValue) { SendNotifications.OrderPendingApproval(model.Order, Url); } } return RedirectToAction("MyOrders"); } else return Error(Loc.Dic.error_order_update_items_error); }
public ActionResult Edit(int id = 0) { if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission); CreateOrderModel model = new CreateOrderModel(); using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId)) using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId)) using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId)) { model.Order = orderRep.GetEntity(id, "Supplier", "Orders_OrderToItem", "Orders_OrderToItem.Orders_Items", "Orders_OrderToAllocation.Budgets_Allocations"); if (model.Order == null) return Error(Loc.Dic.error_order_not_found); if (model.Order.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission); Budget activeBudget = budgetsRep.GetList().SingleOrDefault(x => x.CompanyId == CurrentUser.CompanyId && x.IsActive); if (activeBudget == null) return Error(Loc.Dic.error_no_active_budget); model.IsFutureOrder = model.Order.IsFutureOrder; List<Budgets_Allocations> userAllocations = allocationsRep.GetUserAllocations(CurrentUser.UserId, activeBudget.Id, id); if (!userAllocations.Any()) return Error(Loc.Dic.error_user_have_no_allocations); model.Allocations = new List<OrderAllocation>(); List<Orders_OrderToAllocation> validOrderAllocations = model.Order.Orders_OrderToAllocation.ToList(); var distinctAllocationIds = validOrderAllocations.Select(x => x.AllocationId).Distinct().ToList(); foreach (var allocationId in distinctAllocationIds) { var combineSplitted = validOrderAllocations.Where(x => x.MonthId <= model.Order.CreationDate.Month && x.AllocationId == allocationId); model.Allocations.Add( new OrderAllocation() { AllocationId = allocationId, Name = validOrderAllocations.First(x => x.AllocationId == allocationId).Budgets_Allocations.DisplayName, MonthId = model.Order.CreationDate.Month, IsActive = true, Amount = combineSplitted.Sum(x => x.Amount) } ); validOrderAllocations.RemoveAll(x => x.MonthId <= model.Order.CreationDate.Month && x.AllocationId == allocationId); } foreach (var allocation in validOrderAllocations) { model.Allocations.Add( new OrderAllocation() { AllocationId = allocation.AllocationId, Name = allocation.Budgets_Allocations.Name, MonthId = allocation.MonthId, IsActive = true, Amount = allocation.Amount } ); } ViewBag.Allocations = userAllocations; int allAllocationsCount = model.Allocations.Count; model.Allocations = model.Allocations.Where(x => userAllocations.Any(a => a.Id == x.AllocationId)).ToList(); int validAllocationsCount = model.Allocations.Count; ViewBag.ReAllocationRequired = allAllocationsCount > validAllocationsCount; ViewBag.BudgetYear = activeBudget.Year; ViewBag.ExistingItems = ItemsToString(model.Order.Orders_OrderToItem); return View(model); } }
public ActionResult DownloadReceipt(int id = 0) { Order order; using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRep.GetEntity(id); if (order == null) return Error(Loc.Dic.Error_OrderNotFound); if (!Authorized(RoleType.OrdersViewer) && order.UserId != CurrentUser.UserId) return Error(Loc.Dic.Error_NoPermission); if (order.StatusId < (int)StatusType.ReceiptScanned) return Error(Loc.Dic.Error_ReceiptNotScanned); UploadedFile file = GetUniqueFile(RECEIPT_FOLDER_NAME, id); if (file == null) return Error(Loc.Dic.Error_ReceiptFileNotFound); return File(file.Content, file.MimeType, String.Format("Order_{0}-Receipt.{1}", order.OrderNumber, file.Extension)); } }
public ActionResult DownloadOrderAsPdf(int id = 0) { string cookieName = OpenIdMembershipService.LOGIN_COOKIE_NAME; HttpCookie cookie = Request.Cookies[cookieName]; Dictionary<string, string> cookies = new Dictionary<string, string>(); cookies.Add(cookieName, cookie.Value); int? historyActionId = null; Order order; using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, id)) using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRep.GetEntity(id); historyActionId = (int)HistoryActions.OrderPrinted; Orders_History orderHistory = new Orders_History(); if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value); } return new ActionAsPdf("PrintOrderToScreen", new { password = PRINT_PASSWORD, id = id, companyId = CurrentUser.CompanyId, userId = CurrentUser.UserId, userRoles = CurrentUser.Roles, languageCode = CurrentUser.LanguageCode, coinSign = CurrentUser.CompanyCoinSign }) { FileName = String.Format("Order_{0}.pdf", order.OrderNumber) }; }
public ActionResult DeleteConfirmed(int id = 0) { if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission); Order order; using (OrderToItemRepository orderToItemRep = new OrderToItemRepository()) using (OrderToAllocationRepository orderToAllocationRep = new OrderToAllocationRepository()) using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId)) { order = orderRep.GetEntity(id); if (order == null) return Error(Loc.Dic.error_order_not_found); if (order.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission); if (order.StatusId != (int)StatusType.Pending && order.StatusId != (int)StatusType.PendingOrderCreator) return Error(Loc.Dic.error_order_delete_after_approval); if (!orderRep.Delete(order.Id)) return Error(Loc.Dic.error_orders_delete_error); } return RedirectToAction("MyOrders"); }
//[OpenIdAuthorize] public ActionResult PrintOrderToScreen(string password, int userId, int userRoles, int id = 0, int companyId = 0, string languageCode = "he", string coinSign = "$") { if (password != PRINT_PASSWORD) return Error(Loc.Dic.Error_NoPermission); CultureInfo ci = new CultureInfo(languageCode); System.Threading.Thread.CurrentThread.CurrentUICulture = ci; System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name); Order order; using (OrdersRepository ordersRep = new OrdersRepository(companyId)) { order = ordersRep.GetEntity(id, "User", "Company", "Supplier", "Orders_OrderToItem.Orders_Items"); } if (!Roles.HasRole(userRoles, RoleType.OrdersViewer) && order.UserId != userId) return Error(Loc.Dic.Error_NoPermission); if (order == null) return Error(Loc.Dic.error_order_not_found); string fileName = order.Company.Id + ".png"; string path = Path.Combine(Server.MapPath("~/Content/LogoImages/"), fileName); ViewBag.LogoExists = System.IO.File.Exists(path); ViewBag.LanguageCode = languageCode; ViewBag.CompanyCoinSign = coinSign; return View(order); }
public ActionResult UploadReceiptFile(UploadReceiptModel model, int id = 0) { if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.Error_NoPermission); if (!ModelState.IsValid) { ViewBag.OrderID = id; return View(model); } Order order; bool isModelValid = true; int? historyActionId = null; using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, id)) using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRep.GetEntity(id); if (order == null) return Error(Loc.Dic.Error_OrderNotFound); if (order.StatusId < (int)StatusType.InvoiceExportedToFile) return Error(Loc.Dic.error_wrongStatus); if (!model.File.FileName.Contains('.')) { isModelValid = false; ModelState.AddModelError("File", Loc.Dic.validation_FileNameIsInvalid); } if (!isModelValid) { ViewBag.OrderID = id; return View(model); } if (!model.isUpdate) { order.StatusId = (int)StatusType.ReceiptScanned; order.LastStatusChangeDate = DateTime.Now; if (ordersRep.Update(order) == null) return Error(Loc.Dic.Error_DatabaseError); } SaveUniqueFile(model.File, RECEIPT_FOLDER_NAME, id); historyActionId = (int)HistoryActions.ReceiptScanned; Orders_History orderHistory = new Orders_History(); if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value); //EmailMethods emailMethods = new EmailMethods("*****@*****.**", Loc.Dic.OrdersSystem, "noreply50100200"); //emailMethods.sendGoogleEmail(order.User.Email, order.User.FirstName, Loc.Dic.OrderStatusUpdateEvent, Loc.Dic.OrderStatusOf + order.OrderNumber + Loc.Dic.OrderStatusChangedTo + Translation.Status((StatusType)order.StatusId) + Url.Action("MyOrders", "Orders", null, "http")); SendNotifications.OrderStatusChanged(order, CurrentUser, Url); return RedirectToAction("Index"); } }
public ActionResult Create(CreateOrderModel model) { /// Validating user input if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission); if (!ModelState.IsValid) return Error(Loc.Dic.error_invalid_form); if (String.IsNullOrEmpty(model.ItemsString)) return Error(Loc.Dic.error_invalid_form); List<Orders_OrderToItem> ItemsList = ItemsFromString(model.ItemsString, 0); if (ItemsList == null || ItemsList.Count == 0) return Error(Loc.Dic.error_invalid_form); if (model.IsFutureOrder && !Authorized(RoleType.FutureOrderWriter)) return Error(Loc.Dic.Error_NoPermission); if (model.Allocations == null || model.Allocations.Where(x => x.IsActive).Count() == 0) return Error(Loc.Dic.error_invalid_form); model.Allocations = model.Allocations.Where(x => x.IsActive).ToList(); decimal totalOrderPrice = (decimal.Floor(ItemsList.Sum(x => x.SingleItemPrice * x.Quantity) * 1000) / 1000); decimal totalAllocation = (decimal.Floor(model.Allocations.Sum(x => x.Amount) * 1000) / 1000); if (totalOrderPrice != totalAllocation) return Error(Loc.Dic.error_order_insufficient_allocation); // Initializing needed temporary variables bool allowExeeding = true; List<Orders_OrderToAllocation> AllocationsToCreate = new List<Orders_OrderToAllocation>(); // Setting order properties model.Order.UserId = CurrentUser.UserId; model.Order.Price = totalOrderPrice; model.Order.IsFutureOrder = model.IsFutureOrder; using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId)) using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId)) using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId)) { Budget currentBudget = budgetsRep.GetList().SingleOrDefault(x => x.IsActive); if (currentBudget == null) return Error(Loc.Dic.error_database_error); model.Order.BudgetId = currentBudget.Id; int[] orderAllocationsIds = model.Allocations.Select(x => x.AllocationId).Distinct().ToArray(); var allocationsData = allocationsRep.GetAllocationsData(orderAllocationsIds, StatusType.Pending); bool IsValidAllocations = (allocationsData.Count == orderAllocationsIds.Length) && model.Allocations.All(x => (x.MonthId == null || (x.MonthId >= 1 && x.MonthId <= 12)) && x.Amount > 0); if (!IsValidAllocations) return Error(Loc.Dic.error_invalid_form); if (model.IsFutureOrder) { foreach (var allocationData in allocationsData) { List<OrderAllocation> allocationMonths = model.Allocations.Where(x => x.AllocationId == allocationData.AllocationId).ToList(); foreach (var month in allocationMonths) { if (month.MonthId == DateTime.Now.Month) { OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId); var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month); if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation); AllocationsToCreate.AddRange(newAllocations); } else { var monthData = allocationData.Months.SingleOrDefault(x => x.MonthId == month.MonthId); if (!allowExeeding && month.Amount > monthData.RemainingAmount) return Error(Loc.Dic.error_order_insufficient_allocation); Orders_OrderToAllocation newAllocation = new Orders_OrderToAllocation() { AllocationId = allocationData.AllocationId, MonthId = month.MonthId.Value, Amount = month.Amount, OrderId = 0 }; AllocationsToCreate.Add(newAllocation); } } } } else { foreach (var allocationData in allocationsData) { OrderAllocation currentAllocation = model.Allocations.SingleOrDefault(x => x.AllocationId == allocationData.AllocationId); var newAllocations = allocationsRep.GenerateOrderAllocations(allocationData, currentAllocation.Amount, allowExeeding, DateTime.Now.Month); if (newAllocations == null) return Error(Loc.Dic.error_order_insufficient_allocation); AllocationsToCreate.AddRange(newAllocations); } } if (!CurrentUser.OrdersApprovalRouteId.HasValue) { model.Order.NextOrderApproverId = null; model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice; } else { Users_ApprovalRoutes orderRoute = routesRep.GetEntity(CurrentUser.OrdersApprovalRouteId.Value, "Users_ApprovalStep"); Users_ApprovalStep firstStep = orderRoute.Users_ApprovalStep.OrderBy(x => x.StepNumber).FirstOrDefault(); if (firstStep != null) { model.Order.ApprovalRouteId = orderRoute.Id; model.Order.ApprovalRouteStep = firstStep.StepNumber; model.Order.NextOrderApproverId = firstStep.UserId; model.Order.StatusId = (int)StatusType.Pending; } else { model.Order.ApprovalRouteStep = null; model.Order.NextOrderApproverId = null; model.Order.StatusId = (int)StatusType.ApprovedPendingInvoice; } } } using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) using (OrderToItemRepository orderToItemRep = new OrderToItemRepository()) using (OrderToAllocationRepository orderAllocationsRep = new OrderToAllocationRepository()) { bool creationError = false; if (!ordersRep.Create(model.Order)) return Error(Loc.Dic.error_orders_create_error); model.Order = ordersRep.GetEntity(model.Order.Id, "User", "User1"); foreach (Orders_OrderToItem item in ItemsList) { item.OrderId = model.Order.Id; if (!orderToItemRep.Create(item)) { creationError = true; break; } } foreach (var allocation in AllocationsToCreate) { allocation.OrderId = model.Order.Id; if (!orderAllocationsRep.Create(allocation)) { creationError = true; break; } } if (creationError) { ordersRep.Delete(model.Order.Id); return Error(Loc.Dic.error_orders_create_error); } } using (OrdersHistoryRepository ordersHistoryRepository = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, model.Order.Id)) { Orders_History orderHis = new Orders_History(); ordersHistoryRepository.Create(orderHis, (int)HistoryActions.Created, model.NotesForApprover); } if (model.Order.NextOrderApproverId.HasValue) { SendNotifications.OrderPendingApproval(model.Order, Url); } return RedirectToAction("MyOrders"); }
public ActionResult UploadReceiptFile(int id = 0) { if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.Error_NoPermission); Order order; using (OrdersRepository orderRep = new OrdersRepository(CurrentUser.CompanyId)) { order = orderRep.GetEntity(id); if (order == null) return Error(Loc.Dic.Error_OrderNotFound); if (order.StatusId < (int)StatusType.InvoiceExportedToFile) return Error(Loc.Dic.error_wrongStatus); ViewBag.OrderId = id; if (order.StatusId >= (int)StatusType.ReceiptScanned) { UploadReceiptModel model = new UploadReceiptModel(); model.isUpdate = true; return View(model); } else { return View(); } } }
public ActionResult UploadInvoiceFile(UploadInvoiceModel model, int id = 0) { int? historyActionId = null; if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission); if (!ModelState.IsValid) { ViewBag.OrderID = id; return View(model); } Order order; bool isModelValid = true; using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, id)) using (OrderToAllocationRepository orderAlloRep = new OrderToAllocationRepository()) using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRep.GetEntity(id, "Budget", "Orders_OrderToAllocation"); if (order == null) return Error(Loc.Dic.error_order_get_error); if (order.StatusId < (int)StatusType.ApprovedPendingInvoice) return Error(Loc.Dic.error_order_not_approved); DateTime minValueDate = new DateTime(order.Budget.Year, order.Orders_OrderToAllocation.Max(x => x.MonthId), FIRST_DAY_OF_MONTH); if (model.ValueDate < minValueDate) { isModelValid = false; ModelState.AddModelError("ValueDate", Loc.Dic.error_ValueDateHaveToBeLaterThenLatestAllocationDate); } if (!model.File.FileName.Contains('.')) { isModelValid = false; ModelState.AddModelError("File", Loc.Dic.validation_FileNameIsInvalid); } if (!isModelValid) { ViewBag.OrderID = id; return View(model); } if (!model.isUpdate) { order.StatusId = (int)StatusType.InvoiceScannedPendingOrderCreator; order.LastStatusChangeDate = DateTime.Now; } order.InvoiceNumber = model.InvoiceNumber; order.InvoiceDate = model.InvoiceDate; order.ValueDate = model.ValueDate; if (ordersRep.Update(order) == null) return Error(Loc.Dic.error_database_error); historyActionId = (int)HistoryActions.InvoiceScanned; Orders_History orderHistory = new Orders_History(); if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value); SaveUniqueFile(model.File, INVOICE_FOLDER_NAME, id); //EmailMethods emailMethods = new EmailMethods("*****@*****.**", Loc.Dic.OrdersSystem, "noreply50100200"); //emailMethods.sendGoogleEmail(order.User.Email, order.User.FirstName, Loc.Dic.OrderStatusUpdateEvent, Loc.Dic.OrderStatusOf + " " + order.OrderNumber + " " + Loc.Dic.OrderStatusChangedTo + Translation.Status((StatusType)order.StatusId) + "\n" + Url.Action("MyOrders", "Orders", null, "http")); SendNotifications.OrderStatusChanged(order, CurrentUser, Url); return RedirectToAction("Index"); } }
public ActionResult UploadInvoiceFile(int id = 0) { if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission); Order order; using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRep.GetEntity(id); } if (order == null) return Error(Loc.Dic.error_order_not_found); if (order.StatusId < (int)StatusType.ApprovedPendingInvoice) return Error(Loc.Dic.error_order_not_approved); ViewBag.OrderID = id; if (order.StatusId > (int)StatusType.ApprovedPendingInvoice) { UploadInvoiceModel model = new UploadInvoiceModel(); model.InvoiceNumber = order.InvoiceNumber; model.InvoiceDate = order.InvoiceDate.Value; model.ValueDate = order.ValueDate.Value; model.isUpdate = true; return View(model); } else { return View(); } }
public ActionResult InvoiceApproval(int id = 0) { if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission); Order order; using (OrdersRepository ordersRepository = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRepository.GetEntity(id); } if (order == null) return Error(Loc.Dic.error_order_not_found); if (order.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission); ViewBag.orderId = id; return View(); }
public ActionResult DownloadInvoice(int id = 0) { Order order; using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRep.GetEntity(id); if (order == null) return Error(Loc.Dic.Error_OrderNotFound); if (!Authorized(RoleType.OrdersViewer) && order.UserId != CurrentUser.UserId) return Error(Loc.Dic.Error_NoPermission); if (order.StatusId < (int)StatusType.InvoiceScannedPendingOrderCreator) return Error(Loc.Dic.Error_InvoiceNotScanned); UploadedFile file = GetUniqueFile(INVOICE_FOLDER_NAME, id); if (file == null) return Error(Loc.Dic.Error_InvoiceFileNotFound); return File(file.Content, file.MimeType, String.Format("Order_{0}-Invoice_{1}.{2}", order.OrderNumber, order.InvoiceNumber, file.Extension)); } }
public ActionResult InvoiceApproval(string selectedStatus, int orderId = 0) { if (!Authorized(RoleType.OrdersWriter)) return Error(Loc.Dic.error_no_permission); Order order; int? historyActionId = null; using (OrdersRepository ordersRepository = new OrdersRepository(CurrentUser.CompanyId)) { order = ordersRepository.GetEntity(orderId); if (order == null) return Error(Loc.Dic.error_order_not_found); if (order.UserId != CurrentUser.UserId) return Error(Loc.Dic.error_no_permission); if (selectedStatus == Loc.Dic.ApproveInvoce) { order.StatusId = (int)StatusType.InvoiceApprovedByOrderCreatorPendingFileExport; order.LastStatusChangeDate = DateTime.Now; historyActionId = (int)HistoryActions.InvoiceApproved; } if (selectedStatus == Loc.Dic.CancelOrder) { order.StatusId = (int)StatusType.OrderCancelled; order.LastStatusChangeDate = DateTime.Now; historyActionId = (int)HistoryActions.Canceled; } Orders_History orderHistory = new Orders_History(); using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, order.Id)) if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value); if (ordersRepository.Update(order) == null) return Error(Loc.Dic.error_database_error); } return RedirectToAction("MyOrders"); }
public ActionResult ModifyStatus(string approverNotes, string selectedStatus, int id = 0) { int? historyActionId = null; if (!Authorized(RoleType.OrdersApprover)) return Error(Loc.Dic.error_no_permission); if (approverNotes != null && approverNotes.Length > 250) return Error(Loc.Dic.error_order_notes_too_long); Order orderFromDB; using (OrdersHistoryRepository ordersHistoryRep = new OrdersHistoryRepository(CurrentUser.CompanyId, CurrentUser.UserId, id)) using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId)) using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId)) using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId)) { orderFromDB = ordersRep.GetEntity(id, "User", "Users_ApprovalRoutes"); if (orderFromDB == null) return Error(Loc.Dic.error_order_get_error); if ((orderFromDB.NextOrderApproverId != CurrentUser.UserId) && !Authorized(RoleType.SuperApprover)) return Error(Loc.Dic.error_no_permission); if (orderFromDB.StatusId == (int)StatusType.OrderCancelled) return Error(Loc.Dic.error_order_is_canceled); if (orderFromDB.StatusId >= (int)StatusType.ApprovedPendingInvoice) return Error(Loc.Dic.error_order_already_approved); List<Users_ApprovalStep> orderRouteSteps = orderFromDB.Users_ApprovalRoutes.Users_ApprovalStep.OrderBy(x => x.StepNumber).ToList(); Users_ApprovalStep firstStep = orderRouteSteps.FirstOrDefault(); Users_ApprovalStep currentStep = orderRouteSteps.Single(x => x.StepNumber == orderFromDB.ApprovalRouteStep); Users_ApprovalStep nextStep = orderRouteSteps.FirstOrDefault(x => x.StepNumber > currentStep.StepNumber); if (selectedStatus == Loc.Dic.ApproveOrder) { if (Authorized(RoleType.SuperApprover) || nextStep == null) { orderFromDB.ApprovalRouteStep = null; orderFromDB.NextOrderApproverId = null; orderFromDB.StatusId = (int)StatusType.ApprovedPendingInvoice; historyActionId = (int)HistoryActions.PassedApprovalRoute; } else { orderFromDB.ApprovalRouteStep = nextStep.StepNumber; orderFromDB.NextOrderApproverId = nextStep.UserId; orderFromDB.StatusId = (int)StatusType.PartiallyApproved; historyActionId = (int)HistoryActions.PartiallyApproved; } } else if (selectedStatus == Loc.Dic.DeclineOrder) { orderFromDB.NextOrderApproverId = null; orderFromDB.StatusId = (int)StatusType.Declined; historyActionId = (int)HistoryActions.Declined; } else if (selectedStatus == Loc.Dic.SendBackToUser) { orderFromDB.ApprovalRouteStep = firstStep.StepNumber; orderFromDB.NextOrderApproverId = firstStep.UserId; orderFromDB.StatusId = (int)StatusType.PendingOrderCreator; historyActionId = (int)HistoryActions.ReturnedToCreator; } orderFromDB.LastStatusChangeDate = DateTime.Now; if (ordersRep.Update(orderFromDB) == null) return Error(Loc.Dic.error_database_error); Orders_History orderHistory = new Orders_History(); if (historyActionId.HasValue) ordersHistoryRep.Create(orderHistory, historyActionId.Value, approverNotes); //EmailMethods emailMethods = new EmailMethods("*****@*****.**", Loc.Dic.OrdersSystem, "noreply50100200"); //string emailSubject = String.Format("{0} {1} {2} {3} {4}", Loc.Dic.Order, orderFromDB.OrderNumber, Translation.Status((StatusType)orderFromDB.StatusId), Loc.Dic.By, CurrentUser.FullName); //StringBuilder emailBody = new StringBuilder(); //emailBody.AppendLine(emailSubject); //emailBody.AppendLine(); //emailBody.AppendLine(String.Format("{0}: {1}", Loc.Dic.SeeDetailsAt, Url.Action("Details", "Orders", new { id = id }, "http"))); //emailMethods.sendGoogleEmail(orderFromDB.User.Email, orderFromDB.User.FirstName, emailSubject, emailBody.ToString()); SendNotifications.OrderStatusChanged(orderFromDB, CurrentUser, Url); if (orderFromDB.StatusId == (int)StatusType.PartiallyApproved) SendNotifications.OrderPendingApproval(orderFromDB, Url); return RedirectToAction("PendingOrders"); } }