Beispiel #1
0
        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");
            }
        }
Beispiel #2
0
        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");
        }
Beispiel #3
0
        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) };
        }
Beispiel #4
0
        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);
        }
Beispiel #5
0
        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");
            }
        }
Beispiel #6
0
        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");
        }
Beispiel #7
0
        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");
            }
        }
Beispiel #8
0
        public ActionResult OrdersToExport(List<int> selectedOrder = null)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);
            if (selectedOrder == null || selectedOrder.Count == 0) return Error(Loc.Dic.error_no_selected_orders);

            StringBuilder builder = new StringBuilder();

            List<Order> ordersToExport = new List<Order>();
            Company userCompany;

            using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
            using (CompaniesRepository companiesRep = new CompaniesRepository())
            {
                ordersToExport = ordersRep.GetList("Orders_Statuses", "Supplier", "User")
                    .Where(x => selectedOrder.Contains(x.Id))
                    .ToList();

                userCompany = companiesRep.GetEntity(CurrentUser.CompanyId);

                if (ordersToExport == null) return Error(Loc.Dic.error_database_error);
                if (userCompany == null) return Error(Loc.Dic.error_database_error);

                if (String.IsNullOrEmpty(userCompany.ExternalCoinCode) || String.IsNullOrEmpty(userCompany.ExternalExpenseCode))
                    return Error(Loc.Dic.error_insufficient_company_info_for_export);

                int numberOfOrders = 0;
                builder.AppendLine(numberOfOrders.ToString().PadRight(180));

                foreach (var order in ordersToExport)
                {
                    decimal orderPrice;

                    if (order.Price.HasValue)
                    {
                        if (order.Price.Value > 999999999) return Error(String.Format("({0}: {1}) {2}", Loc.Dic.Order, order.OrderNumber, Loc.Dic.error_order_price_too_high));

                        orderPrice = order.Price.Value;
                    }
                    else
                    {
                        orderPrice = 0;
                    }

                    if (String.IsNullOrEmpty(order.Supplier.ExternalId))
                        return Error(String.Format("({0}: {1}) {2}", Loc.Dic.Supplier, order.Supplier.Name, Loc.Dic.error_insufficient_supplier_info_for_export));

                    if (String.IsNullOrEmpty(order.InvoiceNumber) || order.InvoiceDate == null)
                        return Error(String.Format("({0}: {1}) {2}", Loc.Dic.Order, order.OrderNumber, Loc.Dic.error_insufficient_order_info_for_export));

                    List<Orders_OrderToAllocation> orderAllocations = order.Orders_OrderToAllocation.ToList();
                    List<Budgets_Allocations> distinctOrderAllocations = orderAllocations.Select(x => x.Budgets_Allocations).Distinct().ToList();

                    if (!orderAllocations.Any()) return Error(String.Format("({0}: {1}) {2}", Loc.Dic.Order, order.OrderNumber, Loc.Dic.error_order_has_no_allocations));

                    foreach (var allocation in distinctOrderAllocations)
                    {
                        if (String.IsNullOrEmpty(allocation.ExternalId)) return Error(String.Format("({0}: {1}) {2}", Loc.Dic.BudgetAllocation, allocation.DisplayName, Loc.Dic.error_insufficient_allocation_info_for_export));

                        decimal allocationSum = orderAllocations.Where(x => x.AllocationId == allocation.Id).Sum(a => a.Amount);

                        builder.AppendLine(
                            String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}{17}{18}",
                            String.Empty.PadLeft(3),
                            order.InvoiceNumber.Substring(Math.Max(0, order.InvoiceNumber.Length - 5)).PadLeft(5),
                            order.InvoiceDate.Value.ToString("ddMMyy"),
                            String.Empty.PadLeft(5),
                            order.ValueDate.Value.ToString("ddMMyy"),
                            userCompany.ExternalCoinCode.PadLeft(3),
                            String.Empty.PadLeft(22),
                            allocation.ExternalId.ToString().PadLeft(8),
                            String.Empty.PadLeft(8),
                            String.Empty.PadLeft(8), //order.Supplier.ExternalId.ToString().PadLeft(8),
                            String.Empty.PadLeft(8),
                            allocationSum.ToString("0.00").PadLeft(12),
                            String.Empty.PadLeft(12),
                            String.Empty.PadLeft(12),
                            String.Empty.PadLeft(12),
                            String.Empty.PadLeft(12),
                            String.Empty.PadLeft(12),
                            String.Empty.PadLeft(12),
                            String.Empty.PadLeft(12)
                            )
                        );
                    }

                    builder.AppendLine(
                        String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}{17}{18}",
                        String.Empty.PadLeft(3),
                        order.InvoiceNumber.PadLeft(5),
                        order.InvoiceDate.Value.ToString("ddMMyy"),
                        String.Empty.PadLeft(5),
                        order.ValueDate.Value.ToString("ddMMyy"),
                        userCompany.ExternalCoinCode.PadLeft(3),
                        String.Empty.PadLeft(22),
                        String.Empty.PadLeft(8),
                        String.Empty.PadLeft(8),
                        order.Supplier.ExternalId.ToString().PadLeft(8),
                        String.Empty.PadLeft(8),
                        String.Empty.PadLeft(12),
                        String.Empty.PadLeft(12),
                        orderPrice.ToString("0.00").PadLeft(12),
                        String.Empty.PadLeft(12),
                        String.Empty.PadLeft(12),
                        String.Empty.PadLeft(12),
                        String.Empty.PadLeft(12),
                        String.Empty.PadLeft(12)
                        )
                    );

                    order.StatusId = (int)StatusType.InvoiceExportedToFile;
                    if (ordersRep.Update(order) == null) return Error(Loc.Dic.error_database_error);

                    int? historyActionId = null;
                    historyActionId = (int)HistoryActions.ExportedToFile;
                    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);
                }

                //FileStream fileStream = new FileStream(//SystemFile.("", FileMode.Open());
                byte[] fileBytes = Encoding.UTF8.GetBytes(builder.ToString());
                string fileName = "MOVEIN.DAT";
                //Stream stream = new MemoryStream(fileBytes);

                SendNotifications.OrdersExported(CurrentUser, Url, ordersToExport.Count, fileBytes);

                Response.AppendHeader("Refresh", "1");
                Response.AppendHeader("Location", Url.Action("OrdersToExport", "Orders", null, "http"));

                return File(fileBytes, "text/plain", fileName);
            }
        }
Beispiel #9
0
        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");
            }
        }
Beispiel #10
0
 /// <summary>
 /// Deprecated Method for adding a new object to the Orders_History EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddToOrders_History(Orders_History orders_History)
 {
     base.AddObject("Orders_History", orders_History);
 }
Beispiel #11
0
 /// <summary>
 /// Create a new Orders_History object.
 /// </summary>
 /// <param name="id">Initial value of the Id property.</param>
 /// <param name="companyId">Initial value of the CompanyId property.</param>
 /// <param name="userId">Initial value of the UserId property.</param>
 /// <param name="orderId">Initial value of the OrderId property.</param>
 /// <param name="orderHistoryActionId">Initial value of the OrderHistoryActionId property.</param>
 /// <param name="creationDate">Initial value of the CreationDate property.</param>
 public static Orders_History CreateOrders_History(global::System.Int32 id, global::System.Int32 companyId, global::System.Int32 userId, global::System.Int32 orderId, global::System.Int32 orderHistoryActionId, global::System.DateTime creationDate)
 {
     Orders_History orders_History = new Orders_History();
     orders_History.Id = id;
     orders_History.CompanyId = companyId;
     orders_History.UserId = userId;
     orders_History.OrderId = orderId;
     orders_History.OrderHistoryActionId = orderHistoryActionId;
     orders_History.CreationDate = creationDate;
     return orders_History;
 }