예제 #1
0
        public IActionResult Invoices([FromForm] HomeViewModel model)
        {
            try
            {
                if (model.File == null || model.File.ContentType != "text/csv")
                {
                    throw new Exception("Please upload a valid CSV file!");
                }

                if (!ModelState.IsValid)
                {
                    throw new Exception("One or more required input fields is empty!");
                }

                var columnPositions = new Dictionary <string, int>
                {
                    { Constants.EMPLOYEE_ID_KEY, model.EmployeeId },
                    { Constants.HOURLY_BILLABLE_RATE_KEY, model.HourlyBillableRate },
                    { Constants.PROJECT_KEY, model.Project },
                    { Constants.DATE_KEY, model.Date },
                    { Constants.START_TIME_KEY, model.StartTime },
                    { Constants.END_TIME_KEY, model.EndTime }
                };

                int        columnPositionsCount = columnPositions.Count();
                List <int> columnPositionValues = columnPositions.Values.Select(c => c).Distinct().ToList();

                if (columnPositionValues.Count() < columnPositionsCount)
                {
                    //Duplicate values for column positions exist
                    throw new Exception("Invalid index set. Indices can not be duplicate");
                }

                if (columnPositions.Values.Min() < 0 || columnPositions.Values.Max() >= columnPositionsCount)
                {
                    throw new Exception("Invalid index set. Index of a column can not be less than 0 or greater than "
                                        + (columnPositionsCount - 1).ToString());
                }


                string csvId = Helper.GenerateCsvId();

                IEnumerable <EmployeeShift> uploadedRecords = Helper.CreateRecordsFromFile(csvId, model.File, columnPositions, model.FirstRowHeader);
                _dataProvider.AddEmployeeShifts(uploadedRecords);

                // Redirects to a page to allow users to download PDF copies of CSV Data
                if (model.GeneratePDF)
                {
                    return(RedirectToAction("Projects", new { csvId }));
                }

                var viewModel = new InvoiceViewModel
                {
                    Invoices = Helper.GetInvoices(uploadedRecords).ToList()
                };

                return(View(viewModel));
            }
            catch (Exception e)
            {
                TempData[ERROR_MESSAGE_KEY] = e.Message;
                return(RedirectToAction("Index"));
            }
        }