Example #1
0
        public static async Task <object> Handle(string organizationId, RosterRequest request)
        {
            request.pathParameters.TryGetValue("washbacksEventId", out string washbacksEventId);

            var washbacksEventService = new WashbacksEventService(organizationId);

            return(request.resource switch
            {
                "/washbacks-events" => request.httpMethod switch
                {
                    "GET" => await washbacksEventService.GetWashbacksEvents(),
                    _ => throw new ArgumentOutOfRangeException(ErrorHelper.InvalidHttpMethodForResource(request.httpMethod, request.resource)),
                },
        public static async Task <object> Handle(string organizationId, RosterRequest request)
        {
            var response = new ContentDto();

            var reportOptions = JsonSerializer.Deserialize <ReportOptionsDateRangeDto>(request.body.GetRawText());

            reportOptions.dateFrom ??= "0000-00-00";
            reportOptions.dateThru ??= "9999-99-99";

            var hatchlingsEventService = new HatchlingsEventService(organizationId);
            var hatchlingsEvents       = (await hatchlingsEventService.GetHatchlingsEvents()).Where(x => !string.IsNullOrEmpty(x.eventDate) &&
                                                                                                    (reportOptions.dateFrom.CompareTo(x.eventDate) <= 0 && x.eventDate.CompareTo(reportOptions.dateThru) <= 0));

            var washbacksEventService = new WashbacksEventService(organizationId);
            var washbacksEvents       = (await washbacksEventService.GetWashbacksEvents()).Where(x => !string.IsNullOrEmpty(x.eventDate) &&
                                                                                                 (reportOptions.dateFrom.CompareTo(x.eventDate) <= 0 && x.eventDate.CompareTo(reportOptions.dateThru) <= 0));

            var countyNames = hatchlingsEvents.Select(x => x.eventCounty)
                              .Union(washbacksEvents.Select(x => x.eventCounty))
                              .Distinct()
                              .Where(x => !string.IsNullOrEmpty(x))
                              .OrderBy(x => x).ToList();

            var allCountiesCount = new CountyCountDto()
            {
                countyName = "ALL COUNTIES"
            };

            foreach (var countyName in countyNames)
            {
                var hatchlingsEventsForCounty = hatchlingsEvents.Where(x => x.eventCounty == countyName);

                int GetHatchlingsEventCount(string[] species, string eventType) =>
                hatchlingsEventsForCounty
                .Where(x => (species.Length == 0 || species.Contains(x.species)) && x.eventType == eventType)
                .Sum(x => x.eventCount + x.beachEventCount + x.offshoreEventCount);

                var washbacksEventsForCounty = washbacksEvents.Where(x => x.eventCounty == countyName);

                int GetWashbacksEventCount(string[] species, string eventType, bool under5cmClsl) =>
                washbacksEventsForCounty
                .Where(x => (species.Length == 0 || species.Contains(x.species)) && x.eventType == eventType && x.under5cmClsl == under5cmClsl)
                .Sum(x => x.eventCount + x.beachEventCount + x.offshoreEventCount);

                DetailItemDto GetSpeciesCounts(string[] species) =>
                new DetailItemDto
                {
                    hatchlingsAcquired        = GetHatchlingsEventCount(species, "Acquired"),
                    hatchlingsDoa             = GetHatchlingsEventCount(species, "DOA"),
                    washbacksUnder5cmAcquired = GetWashbacksEventCount(species, "Acquired", true),
                    washbacksOver5cmAcquired  = GetWashbacksEventCount(species, "Acquired", false),
                    washbacksUnder5cmDoa      = GetWashbacksEventCount(species, "DOA", true),
                    washbacksOver5cmDoa       = GetWashbacksEventCount(species, "DOA", false),
                };

                var countyCount = new CountyCountDto()
                {
                    countyName = countyName
                };

                countyCount.ccCount      = GetSpeciesCounts(ReportHelper.speciesCc);
                countyCount.cmCount      = GetSpeciesCounts(ReportHelper.speciesCm);
                countyCount.dcCount      = GetSpeciesCounts(ReportHelper.speciesDc);
                countyCount.otherCount   = GetSpeciesCounts(ReportHelper.speciesOther);
                countyCount.unknownCount = GetSpeciesCounts(ReportHelper.speciesUnknown);
                countyCount.totalCount   = GetSpeciesCounts(new string[] { });

                response.countyCounts.Add(countyCount);

                allCountiesCount.AppendCounts(countyCount);
            }

            foreach (var countyCount in response.countyCounts)
            {
                countyCount.SetPercentageOfGrandTotal(allCountiesCount.totalCount);
            }

            response.countyCounts.Insert(0, allCountiesCount);

            return(response);
        }
Example #3
0
        public static async Task <object> Handle(string organizationId, RosterRequest request)
        {
            var reportOptions = JsonSerializer.Deserialize <MarineTurtleCaptiveFacilityQuarterlyReportOptionsDto>(request.body.GetRawText());

            var fileTimestamp = $"{DateTime.Now:yyyyMMddHHmmss} UTC";

            var baseMasterReportFileName = $"MASTER - Marine Turtle Captive Facility Quarterly Report For {reportOptions.subjectType}.pdf";
            var basePath = AppDomain.CurrentDomain.BaseDirectory;

            var masterReportFileName = Path.Combine(basePath, "pdf", baseMasterReportFileName);
            var filledReportFileName = Path.Combine("/tmp", baseMasterReportFileName.Replace("MASTER - ", "FILLED - ").Replace(".pdf", $" - {fileTimestamp}.pdf"));

            var organizationService = new OrganizationService(organizationId);
            var organization        = await organizationService.GetOrganization();

            var organizationAndPermitNumber = $"{organization.organizationName} - {organization.permitNumber}";

            string monthsAndYearOfReport;
            var    dateFrom = ReportHelper.ToDate(reportOptions.dateFrom);
            var    dateThru = ReportHelper.ToDate(reportOptions.dateThru);

            if (dateFrom.Year == dateThru.Year)
            {
                monthsAndYearOfReport = $"{dateFrom:dd} {dateFrom:MMMM} - {dateThru:dd} {dateThru:MMMM} {dateThru.Year}";
            }
            else
            {
                monthsAndYearOfReport = $"{dateFrom:dd} {dateFrom:MMMM} {dateFrom.Year} - {dateThru:dd} {dateThru:MMMM} {dateThru.Year}";
            }

            var balanceAsOfDate = reportOptions.subjectType == "Hatchlings" ? organization.hatchlingsBalanceAsOfDate : organization.washbacksBalanceAsOfDate;
            var useOrganizationStartingBalances = !string.IsNullOrEmpty(balanceAsOfDate) && balanceAsOfDate.CompareTo(reportOptions.dateFrom) <= 0;

            var items = new Dictionary <string, CaptiveFacilityReportItem>
            {
                { "Cc", new CaptiveFacilityReportItem(ReportHelper.speciesCc) },
                { "Cm", new CaptiveFacilityReportItem(ReportHelper.speciesCm) },
                { "Dc", new CaptiveFacilityReportItem(ReportHelper.speciesDc) },
                { "Other", new CaptiveFacilityReportItem(ReportHelper.speciesOther) },
                { "Unknown", new CaptiveFacilityReportItem(ReportHelper.speciesUnknown) }
            };
            var categories = items.Keys;

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <HatchlingsEventModel, CaptiveFacilityReportEvent>();
                cfg.CreateMap <WashbacksEventModel, CaptiveFacilityReportEvent>();
            });
            var mapper = new Mapper(config);

            var hatchlingsEventService = new HatchlingsEventService(organizationId);
            var washbacksEventService  = new WashbacksEventService(organizationId);
            var events = reportOptions.subjectType == "Hatchlings"
                ? (await hatchlingsEventService.GetHatchlingsEvents()).Select(x => mapper.Map <CaptiveFacilityReportEvent>(x))
                : (await washbacksEventService.GetWashbacksEvents()).Select(x => mapper.Map <CaptiveFacilityReportEvent>(x));

            int GetCountsPriorToThisPeriod(string[] eventTypes, string[] species) =>
            events
            .Where(x => eventTypes.Contains(x.eventType) && species.Contains(x.species))
            .Where(x => x.eventDate.CompareTo(reportOptions.dateFrom) <= 0)
            .Where(x => !string.IsNullOrEmpty(balanceAsOfDate) && balanceAsOfDate.CompareTo(x.eventDate) <= 0)
            .Sum(x => x.eventCount + x.beachEventCount + x.offshoreEventCount);

            int GetCountsForThisPeriod(string eventType, string[] species, string eventCountType = null) =>
            events
            .Where(x => x.eventType == eventType && species.Contains(x.species))
            .Where(x => reportOptions.dateFrom.CompareTo(x.eventDate) <= 0)
            .Where(x => x.eventDate.CompareTo(reportOptions.dateThru) <= 0)
            .Sum(x => eventCountType == "beachEventCount" ? x.beachEventCount : (eventCountType == "offshoreEventCount" ? x.offshoreEventCount : x.eventCount));

            int GetStartingBalance(string category) =>
            useOrganizationStartingBalances
                    ? Convert.ToInt32(organization.GetType().GetProperty($"{category.ToLower()}{reportOptions.subjectType}StartingBalance").GetValue(organization))
                    : 0;

            //----------------------------------------------------------------------------------------------------

            var pdfReader = new PdfReader(masterReportFileName);

            pdfReader.RemoveUsageRights();

            var fs         = new FileStream(filledReportFileName, FileMode.Create);
            var pdfStamper = new PdfStamper(pdfReader, fs, '\0', false);

            var info = pdfReader.Info;

            info["Title"]       = baseMasterReportFileName.Replace("MASTER - ", "").Replace(".pdf", $" - {fileTimestamp}.pdf");
            pdfStamper.MoreInfo = info;

            var acroFields = pdfStamper.AcroFields;

            acroFields.SetField("txtOrganizationAndPermitNumber", organizationAndPermitNumber);
            acroFields.SetField("txtMonthsAndYearOfReport", monthsAndYearOfReport);

            var sbComments = new StringBuilder();

            foreach (var category in categories)
            {
                var item = items[category];

                item.StartingBalance = GetStartingBalance(category);

                item.AdditionsBeforeThisPeriod    = GetCountsPriorToThisPeriod(new[] { "Acquired" }, item.SpeciesSelector);
                item.SubtractionsBeforeThisPeriod = GetCountsPriorToThisPeriod(new[] { "Died", "Released" }, item.SpeciesSelector);
                item.AcquiredThisPeriod           = GetCountsForThisPeriod("Acquired", item.SpeciesSelector);
                item.DiedThisPeriod = GetCountsForThisPeriod("Died", item.SpeciesSelector);
                item.ReleasedOnTheBeachThisPeriod = GetCountsForThisPeriod("Released", item.SpeciesSelector, "beachEventCount");
                item.ReleasedOffshoreThisPeriod   = GetCountsForThisPeriod("Released", item.SpeciesSelector, "offshoreEventCount");
                item.DoaThisPeriod = GetCountsForThisPeriod("DOA", item.SpeciesSelector);

                item.PreviousBalance = item.StartingBalance + item.AdditionsBeforeThisPeriod - item.SubtractionsBeforeThisPeriod;
                acroFields.SetField($"txt{category}PrevBal", item.PreviousBalance);
                acroFields.SetField($"txt{category}Acquired", item.AcquiredThisPeriod);
                acroFields.SetField($"txt{category}Died", item.DiedThisPeriod);
                acroFields.SetField($"txt{category}Released", item.ReleasedOnTheBeachThisPeriod + item.ReleasedOffshoreThisPeriod);
                acroFields.SetField($"txt{category}EndBal", item.PreviousBalance + item.AcquiredThisPeriod - item.DiedThisPeriod - item.ReleasedOnTheBeachThisPeriod - item.ReleasedOffshoreThisPeriod);
                acroFields.SetField($"txt{category}BeachVsOffshore", $"Beach: {item.ReleasedOnTheBeachThisPeriod}{Environment.NewLine}Offshore: {item.ReleasedOffshoreThisPeriod}");

                if (reportOptions.includeDoaCounts)
                {
                    sbComments.AppendLine($"DOA {category} hatchlings = {item.DoaThisPeriod}");
                }
            }

            sbComments.AppendLine(reportOptions.comments);
            acroFields.SetField("txtComments", sbComments.ToString());

            // =============================================================================

            pdfStamper.FormFlattening = true; // 'true' to make the PDF read-only
            pdfStamper.Close();
            pdfReader.Close();

            var bytes = await File.ReadAllBytesAsync(filledReportFileName);

            return(bytes);
        }