Beispiel #1
0
        public async Task <IActionResult> Create([FromBody] CreateUpdateRefund create)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(new ErrorsResponse(ModelState)));
            }

            var username = User.FindFirst(c => c.Type == JwtRegisteredClaimNames.Sub).Value;
            var refund   = new Refund
            {
                Amount         = create.Amount,
                CheckNumber    = create.CheckNumber,
                Date           = create.Date,
                Username       = username,
                SchoolYear     = create.SchoolYear,
                SchoolDistrict = _districts.GetByAun(create.SchoolDistrictAun),
            };

            try
            {
                refund = await Task.Run(() => _context.SaveChanges(() => _refunds.Create(refund)));

                return(new CreatedResult($"/api/refunds/{refund.Id}", new RefundResponse
                {
                    Refund = new RefundDto(refund),
                }));
            }
            catch (DbUpdateException)
            {
                return(new StatusCodeResult(409));
            }
        }
        public async Task <IActionResult> Create(CreateUpdateDigitalSignature create)
        {
            _logger.LogInformation($"DigitalSignatureController#Create():  create is {create}.");

            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(new ErrorsResponse(ModelState)));
            }

            if (create.file == null)
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Could not find parameter named '{nameof(create.file)}'.")));
            }

            Byte[] imgData = new Byte[create.file.Length];

            using (var stream = new MemoryStream())
            {
                create.file.CopyTo(stream);
                imgData = stream.ToArray();
            }

            _logger.LogInformation($"DigitalSignatureController#Create():  imgData length is {imgData.Length}.");
            var username  = User.FindFirst(c => c.Type == JwtRegisteredClaimNames.Sub).Value;
            var signature = new DigitalSignature
            {
                Title    = create.title,
                FileName = create.fileName,
                UserName = username,
                imgData  = imgData
            };

            try {
                signature = await Task.Run(() => _context.SaveChanges(() => _signatures.Create(signature)));

                return(new CreatedResult($"/api/signatures/{signature.Id}", new DigitalSignatureResponse
                {
                    DigitalSignature = new DigitalSignatureDto(signature),
                }));
            }
            catch (DbUpdateException)
            {
                return(new StatusCodeResult(409));
            }
        }
Beispiel #3
0
        public async Task <IActionResult> Create([FromBody] CreateUpdatePayment create)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(new ErrorsResponse(ModelState)));
            }

            var username = User.FindFirst(c => c.Type == JwtRegisteredClaimNames.Sub).Value;
            var payments = new List <Payment>();

            for (var i = 0; i < create.Splits.Count; i++)
            {
                var split = create.Splits[i];

                payments.Add(new Payment
                {
                    Date           = split.Date,
                    ExternalId     = create.ExternalId,
                    Type           = create.Type,
                    SchoolDistrict = _districts.GetByAun(create.SchoolDistrictAun),
                    Split          = i + 1,
                    Amount         = split.Amount,
                    SchoolYear     = split.SchoolYear,
                    Username       = username,
                });
            }

            try
            {
                payments = await Task.Run(() => _context.SaveChanges(() => _payments.CreateMany(payments)).ToList());
            }
            catch (DbUpdateException)             // check the inner exception?
            {
                return(StatusCode(409));
            }

            return(Created($"/api/payments/{payments[0].PaymentId}", new PaymentsResponse
            {
                Payments = payments.Select(p => new PaymentDto(p)).ToList(),
            }));
        }
		public async Task<IActionResult> Update(int id, [FromBody]SchoolDistrictUpdate update)
		{
			if (!ModelState.IsValid)
				return new BadRequestObjectResult(new ErrorsResponse(ModelState));

			if (_schoolDistricts.Get(id) == null)
				return NotFound();

			var district = new SchoolDistrict
			{
				Id = id,
				Aun = update.Aun,
				Name = update.Name,
				Rate = update.Rate,
				AlternateRate = update.AlternateRate,
				SpecialEducationRate = update.SpecialEducationRate,
				AlternateSpecialEducationRate = update.AlternateSpecialEducationRate,
				PaymentType = update.PaymentType,
			};
			await Task.Run(() => _context.SaveChanges(() => _schoolDistricts.CreateOrUpdate(district)));
			return Ok();
		}
        public async Task <IActionResult> LockHeader(string scope)
        {
            await Task.Run(() => _context.SaveChanges(() => _records.Lock(scope)));

            return(Ok());
        }
Beispiel #6
0
        public IActionResult Upload(string year, IFormFile file)
        {
            if (file == null)
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Could not find parameter named '{nameof(file)}'.")));
            }

            if (!_parsers.ContainsKey(file.ContentType))
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Invalid file Content-Type '{file.ContentType}'.")));
            }

            var input    = _parsers[file.ContentType](year, file.OpenReadStream());
            var username = User.FindFirst(c => c.Type == JwtRegisteredClaimNames.Sub).Value;

            Calendar calendar;

            using (var tx = _context.Database.BeginTransaction())
            {
                try
                {
                    calendar = _calendars.Get(input.SchoolYear);
                    if (calendar == null)
                    {
                        calendar             = input;
                        calendar.Created     = DateTime.Now;
                        calendar.LastUpdated = calendar.Created;
                        _context.Add(calendar);
                    }
                    else
                    {
                        var details = new List <AuditDetail>();
                        var added   = input.Days.Where(id => !calendar.Days.Any(cd => cd.Date == id.Date));
                        Console.WriteLine("Added:");
                        foreach (var add in added)
                        {
                            Console.WriteLine($"\t{add.Date}");
                        }

                        foreach (var add in added)
                        {
                            details.Add(new AuditDetail
                            {
                                Field = "Day",
                                Next  = add.Date.ToString("MM/dd/yyyy"),
                            });
                        }

                        var removed = calendar.Days.Where(cd => !input.Days.Any(id => id.Date == cd.Date));
                        Console.WriteLine("Removed:");
                        foreach (var remove in removed)
                        {
                            Console.WriteLine($"\t{remove.Date}");
                        }

                        foreach (var remove in removed)
                        {
                            details.Add(new AuditDetail
                            {
                                Field    = "Day",
                                Previous = remove.Date.ToString("MM/dd/yyyy"),
                            });
                        }

                        _context.Remove(calendar);
                        input.Created     = calendar.Created;
                        input.LastUpdated = DateTime.Now;
                        _context.Add(input);
                        calendar = input;
                        _audits.Create(new AuditHeader
                        {
                            Username   = username,
                            Activity   = AuditActivity.UPDATE_SCHOOL_CALENDAR,
                            Timestamp  = DateTime.Now,
                            Identifier = calendar.SchoolYear,
                            Details    = details,
                        });
                    }

                    _context.SaveChanges();
                    tx.Commit();
                }
                catch (Exception)
                {
                    tx.Rollback();
                    throw;
                }
            }

            return(new CreatedResult($"/api/calendars/{year}", new CalendarResponse
            {
                Calendar = calendar,
            }));
        }
Beispiel #7
0
        public async Task <IActionResult> Upload(string type, string year, IFormFile content)
        {
            if (!ReportType.Values().Contains(type))
            {
                return(new BadRequestObjectResult(new ErrorResponse($"Invalid ReportType '{type}'.")));
            }

            if (!new Regex(@"^\d{4}-\d{4}$").IsMatch(year))
            {
                return(new BadRequestObjectResult(new ErrorResponse($"Invalid SchoolYear '{year}'")));
            }

            if (content == null)
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Could not find parameter named '{nameof(content)}'.")));
            }

            if (content.ContentType != ContentTypes.XLSX)
            {
                return(new BadRequestObjectResult(
                           new ErrorResponse($"Invalid file Content-Type '{content.ContentType}'.")));
            }

            Template template;

            using (var ms = new MemoryStream())
            {
                content.OpenReadStream().CopyTo(ms);
                template = new Template
                {
                    ReportType = ReportType.FromString(type),
                    SchoolYear = year,
                    Name       = content.FileName,
                    Content    = ms.ToArray(),
                };
            }

            template = await Task.Run(() => _context.SaveChanges(() => _templates.CreateOrUpdate(template)));

            var username = User.FindFirst(c => c.Type == JwtRegisteredClaimNames.Sub).Value;

            using (var tx = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.SaveChanges(() => _audits.Create(new AuditHeader
                    {
                        Username   = username,
                        Activity   = AuditActivity.UPDATE_TEMPLATE,
                        Timestamp  = DateTime.Now,
                        Identifier = $"{template.ReportType}_{template.SchoolYear}",
                    }));
                    tx.Commit();
                }
                catch (Exception)
                {
                    tx.Rollback();
                    throw;
                }
            }

            return(new CreatedResult($"/api/templates/{template.ReportType}/{template.SchoolYear}", new TemplateResponse
            {
                Template = new TemplateDto(template),
            }));
        }
        private static void HandleFileChange(object source, FileSystemEventArgs e)
        {
            try
            {
                _processing.WaitOne();

                _context = new PacBillContext(new DbContextOptionsBuilder <PacBillContext>().
                                              UseSqlServer(_connectionString).Options);

                using (var tx = _context.Database.BeginTransaction())
                {
                    string scope;
                    if (IsRecon(e.Name))
                    {
                        scope = GetReconScope();
                    }
                    else
                    {
                        scope = GetMonthlyScope(_context);
                    }

                    Console.WriteLine($"Scope: {scope}");

                    var header = _context.StudentRecordsHeaders.Include(r => r.Records).SingleOrDefault(h => h.Scope == scope);
                    if (header != null)
                    {
                        if (!header.Locked)
                        {
                            Console.WriteLine($"Data for {scope} exists and is not locked. Overwriting.");
                            _context.Remove(header);
                        }
                        else
                        {
                            Console.WriteLine($"Data for {scope} exists and is locked. Aborting import.");
                            return;
                        }
                    }
                    else
                    {
                        header = new StudentRecordsHeader
                        {
                            Scope    = scope,
                            Filename = e.Name,
                            Created  = DateTime.Now,
                            Locked   = false,
                        };
                    }

                    try
                    {
                        using (var streamReader = File.OpenText(e.FullPath))
                        {
                            var lastWrite = File.GetLastWriteTime(e.FullPath);
                            _parser.Parse(lastWrite, streamReader, header);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to read CSV: {ex.Message}.");
                        if (ex.InnerException != null)
                        {
                            Console.WriteLine($"  Inner exception: {ex.InnerException.Message}.");
                        }

                        return;
                    }

                    try
                    {
                        Console.WriteLine("Writing changes to the database...");
                        if (header.Id == 0)
                        {
                            _context.Add(header);
                        }
                        else
                        {
                            _context.Update(header);
                        }

                        _context.SaveChanges();

                        Console.WriteLine("Writing changes to the database done!");
                        tx.Commit();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to write data to database: {ex.Message}.");
                        if (ex.InnerException != null)
                        {
                            Console.WriteLine($"  Inner exception: {ex.InnerException.Message}.");
                        }

                        return;
                    }
                }
            }
            finally
            {
                _processing.Set();
            }
        }