예제 #1
0
        private void DrawBarsForLocation(long originSeconds, Instant originInstant, Instant endInstant, Location location, int y)
        {
            LocalDateTime dt1 = originInstant.InZone(location.TimeZone).Date.AtMidnight();
            LocalDateTime dt2 = endInstant.InZone(location.TimeZone).LocalDateTime;

            Debug.Assert(dt1 < dt2);

            if (dt1.DayOfWeekend(location.Country) == 2)
            {
                DrawBar(originSeconds, location, dt1, dt1.PlusDays(1), BarSize.Weekend, "Weekend;W", y);
            }

            for (LocalDateTime dt = dt1; dt < dt2; dt = dt.PlusDays(1))
            {
                int dayOfWeekend = dt.DayOfWeekend(location.Country);
                if (dayOfWeekend == 1)
                {
                    DrawBar(originSeconds, location, dt, dt.PlusDays(2), BarSize.Weekend, "Weekend;W", y);
                }
                if (dayOfWeekend == 1 || dayOfWeekend == 2)
                {
                    continue;
                }

                EarlyClose?earlyClose = location.EarlyCloses.Where(x => x.DateTime.Date == dt.Date).SingleOrDefault();
                Holiday?   holiday    = Holidays.TryGetHoliday(location.Country, location.Region, dt.Date);
                if (holiday is not null && earlyClose is null)
                {
                    DrawBar(originSeconds, location, dt, dt.PlusDays(1), BarSize.Holiday, "Holiday: " + holiday.Name + ";Holiday;H", y);
                    continue;
                }

                foreach (Bar bar in location.Bars)
                {
                    LocalDateTime start = dt.Date + bar.Start;
                    LocalDateTime end   = dt.Date + bar.End;
                    if (earlyClose is not null)
                    {
                        if (earlyClose.DateTime.TimeOfDay <= bar.Start)
                        {
                            continue;
                        }
                        if (earlyClose.DateTime.TimeOfDay < bar.End)
                        {
                            end = earlyClose.DateTime;
                        }
                    }
                    string label = bar.Label;
                    if (string.IsNullOrEmpty(label))
                    {
                        label = location.Name + " TIME";
                    }
                    if (label.Contains("TIME"))
                    {
                        label = label.Replace("TIME", Clock.GetCurrentInstant().InZone(location.TimeZone).ToString("H:mm", null));
                    }
                    DrawBar(originSeconds, location, start, end, bar.BarSize, label, y);
                }
            }
        }
예제 #2
0
        public void BetweenLocalDateTimes_AcrossDays()
        {
            Period expected = Period.FromHours(23) + Period.FromMinutes(59);
            Period actual   = Period.Between(TestDateTime1, TestDateTime1.PlusDays(1).PlusMinutes(-1));

            Assert.AreEqual(expected, actual);
        }
예제 #3
0
        /// <summary>
        /// Get the start or end date time in a time zone for the specified date range type.
        /// </summary>
        /// <param name="nowInTimeZone">Now in time zone</param>
        /// <param name="dateRangeType">The date range type (today, current week etc.)</param>
        /// <param name="isStart">True for start and false for end of date range</param>
        /// <param name="useEndOfCurrentDay">Flag to indicate if end of current periods are now or the end of the current day</param>
        /// <returns>The start or end date time for the range in the time zone</returns>
        public static LocalDateTime LocalDateTimeForDateRangeType(this LocalDateTime nowInTimeZone, DateRangeType dateRangeType, bool isStart, bool useEndOfCurrentDay = false)
        {
            LocalDateTime startToday = nowInTimeZone.PlusTicks(-nowInTimeZone.TickOfDay);
            LocalDateTime endToday   = startToday.PlusDays(1).PlusSeconds(-1);
            var           currentEnd = useEndOfCurrentDay ? endToday : nowInTimeZone;

            var startThisWeek  = startToday.With(DateAdjusters.PreviousOrSame(IsoDayOfWeek.Monday));
            var startThisMonth = startToday.With(DateAdjusters.StartOfMonth);

            LocalDateTime dateTimeInTimeZone = nowInTimeZone;

            switch (dateRangeType)
            {
            case DateRangeType.Today:
                dateTimeInTimeZone = isStart ? startToday : currentEnd;
                break;

            case DateRangeType.Yesterday:
            case DateRangeType.PriorToYesterday:
                dateTimeInTimeZone = isStart ? startToday.PlusDays(-1) : startToday.PlusSeconds(-1);
                if (dateRangeType == DateRangeType.PriorToYesterday)
                {
                    dateTimeInTimeZone = dateTimeInTimeZone.PlusDays(-1);
                }
                break;

            case DateRangeType.CurrentWeek:
                dateTimeInTimeZone = isStart ? startThisWeek : currentEnd;
                break;

            case DateRangeType.PreviousWeek:
            case DateRangeType.PriorToPreviousWeek:
                dateTimeInTimeZone = isStart ? startThisWeek.PlusDays(-7) : startThisWeek.PlusSeconds(-1);
                if (dateRangeType == DateRangeType.PriorToPreviousWeek)
                {
                    dateTimeInTimeZone = dateTimeInTimeZone.PlusDays(-7);
                }
                break;

            case DateRangeType.CurrentMonth:
                dateTimeInTimeZone = isStart ? startThisMonth : currentEnd;
                break;

            case DateRangeType.PreviousMonth:
            case DateRangeType.PriorToPreviousMonth:
                dateTimeInTimeZone = isStart ? startThisMonth.PlusMonths(-1) : startThisMonth.PlusSeconds(-1);
                if (dateRangeType == DateRangeType.PriorToPreviousMonth)
                {
                    dateTimeInTimeZone = dateTimeInTimeZone.PlusMonths(-1);
                }
                break;

            case DateRangeType.ProjectExtents:
            case DateRangeType.Custom:
                //do nothing
                break;
            }
            return(dateTimeInTimeZone);
        }
        public void PlusDays_Simple()
        {
            LocalDateTime start = new LocalDateTime(2011, 1, 15, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2011, 1, 23, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusDays(8));

            expected = new LocalDateTime(2011, 1, 7, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusDays(-8));
        }
        public void PlusDays_EndOfFebruary_InLeapYear()
        {
            LocalDateTime start    = new LocalDateTime(2012, 2, 26, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2012, 3, 5, 12, 15, 8);

            Assert.AreEqual(expected, start.PlusDays(8));
            // Round-trip back across the boundary
            Assert.AreEqual(start, start.PlusDays(8).PlusDays(-8));
        }
        public void PlusDays_MonthBoundary()
        {
            LocalDateTime start = new LocalDateTime(2011, 1, 26, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2011, 2, 3, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusDays(8));

            // Round-trip back across the boundary
            Assert.AreEqual(start, start.PlusDays(8).PlusDays(-8));
        }
        public void PlusDays_YearBoundary()
        {
            LocalDateTime start    = new LocalDateTime(2011, 12, 26, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2012, 1, 3, 12, 15, 8);

            Assert.AreEqual(expected, start.PlusDays(8));

            // Round-trip back across the boundary
            Assert.AreEqual(start, start.PlusDays(8).PlusDays(-8));
        }
        public void PlusDays_Simple()
        {
            LocalDateTime start    = new LocalDateTime(2011, 1, 15, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2011, 1, 23, 12, 15, 8);

            Assert.AreEqual(expected, start.PlusDays(8));

            expected = new LocalDateTime(2011, 1, 7, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusDays(-8));
        }
예제 #9
0
        public void CreateResolver_Ambiguous()
        {
            ZonedDateTime         zoned               = new ZonedDateTime(TimeInTransition.PlusDays(1).WithOffset(GapZone.EarlyInterval.WallOffset), GapZone);
            AmbiguousTimeResolver ambiguityResolver   = (earlier, later) => zoned;
            SkippedTimeResolver   skippedTimeResolver = (local, zone, before, after) => { Assert.Fail("Shouldn't be called"); return(default(ZonedDateTime)); };
            var resolver = Resolvers.CreateMappingResolver(ambiguityResolver, skippedTimeResolver);

            var resolved = resolver(AmbiguousZone.MapLocal(TimeInTransition));

            Assert.AreEqual(zoned, resolved);
        }
예제 #10
0
        public void InPeriod()
        {
            Assert.IsFalse(_tick.InPeriod(null));

            Assert.IsFalse(_tick.InPeriod(_beginTime.PlusDays(-1)));
            Assert.IsFalse(_tick.InPeriod(_beginTime.PlusDays(1)));
            Assert.IsTrue(_tick.InPeriod(_beginTime.PlusMinutes(30)));
            Assert.IsFalse(_tick.InPeriod(_beginTime.PlusMinutes(90)));

            Assert.IsTrue(_tick.InPeriod(_beginTime));
            Assert.IsFalse(_tick.InPeriod(_endTime));
        }
예제 #11
0
    private static List <(LocalDateTime start, LocalDateTime end)> GetSessions(string s)
    {
        List <(LocalDateTime start, LocalDateTime end)> list = new();

        if (string.IsNullOrEmpty(s))
        {
            return(list);
        }

        string[] days = s.Split(';');
        foreach (string day in days)
        {
            string[] parts = day.Split(':');

            Debug.Assert(parts.Length == 2);
            LocalDate            date     = DatePattern.Parse(parts[0]).Value;
            IEnumerable <string> sessions = parts[1].Split(',').Distinct(); // the sessions may be repeated(?)
            foreach (string session in sessions.Where(x => x != "CLOSED"))
            {
                (LocalTime startTime, LocalTime endTime) = GetSessionTime(session);
                LocalDateTime start = date.At(startTime);
                LocalDateTime end   = date.At(endTime);
                if (end < start)
                {
                    start = start.PlusDays(-1);                               //end = end.PlusDays(1); ??
                }
                if (list.Any() && (start <= list.Last().end || end <= start)) // ensure consecutive, non-overlapping periods
                {
                    throw new InvalidDataException("Invalid period.");
                }
                list.Add((start, end));
            }
        }
        return(list);
예제 #12
0
        public void TestDNO()
        {
            string description = "This is a fast rotation plan that uses 3 teams and two 12-hr shifts to provide 24/7 coverage. "
                                 + "Each team rotates through the following sequence every three days: 1 day shift, 1 night shift, and 1 day off.";

            schedule = new WorkSchedule("DNO Plan", description);

            // Day shift, starts at 07:00 for 12 hours
            Shift day = schedule.CreateShift("Day", "Day shift", new LocalTime(7, 0, 0), Duration.FromHours(12));

            // Night shift, starts at 19:00 for 12 hours
            Shift night = schedule.CreateShift("Night", "Night shift", new LocalTime(19, 0, 0), Duration.FromHours(12));

            // rotation
            Rotation rotation = schedule.CreateRotation("DNO", "DNO");

            rotation.AddSegment(day, 1, 0);
            rotation.AddSegment(night, 1, 1);

            schedule.CreateTeam("Team 1", "First team", rotation, referenceDate);
            schedule.CreateTeam("Team 2", "Second team", rotation, referenceDate.PlusDays(-1));
            schedule.CreateTeam("Team 3", "Third team", rotation, referenceDate.PlusDays(-2));

            // rotation working time
            LocalDateTime from     = referenceDate.PlusDays(rotation.GetDayCount()).At(new LocalTime(7, 0, 0));
            Duration      duration = schedule.CalculateWorkingTime(from, from.PlusDays(3));

            Assert.IsTrue(duration.Equals(Duration.FromHours(72)));

            RunBaseTest(schedule, Duration.FromHours(24), Duration.FromDays(3), referenceDate);
        }
예제 #13
0
        public void ShouldGetLocalDateTimeForPriorToPreviousWeek()
        {
            var start = localNow.LocalDateTimeForDateRangeType(DateRangeType.PriorToPreviousWeek, true, true);
            var end   = localNow.LocalDateTimeForDateRangeType(DateRangeType.PriorToPreviousWeek, false, true);

            Assert.Equal(startPreviousWeek.PlusDays(-7), start);
            Assert.Equal(endPreviousWeek.PlusDays(-7), end);
        }
예제 #14
0
 public static LocalDateTime WithDayOfMonth(this LocalDateTime instance, int day)
 {
     if (day < 1 || day > 31)
     {
         throw new ArgumentException(nameof(day));
     }
     return(instance.PlusDays(day - instance.Day));
 }
예제 #15
0
        public void ShouldGetLocalDateTimeForPriorToYesterday()
        {
            var start = localNow.LocalDateTimeForDateRangeType(DateRangeType.PriorToYesterday, true, true);
            var end   = localNow.LocalDateTimeForDateRangeType(DateRangeType.PriorToYesterday, false, true);

            Assert.Equal(startYesterday.PlusDays(-1), start);
            Assert.Equal(endYesterday.PlusDays(-1), end);
        }
        public LocalDateTime?ComputeNextExecutionTime(LocalDateTime lastExecutionTime)
        {
            var currentDayExecutionTime = new LocalDateTime(lastExecutionTime.Year, lastExecutionTime.Month, lastExecutionTime.Day, this._hourOfDay, this._minuteOfHour);

            if (lastExecutionTime < currentDayExecutionTime)
            {
                return(currentDayExecutionTime);
            }

            return(currentDayExecutionTime.PlusDays(1));
        }
예제 #17
0
        public static List <ForecastHourly> GetHourlyWeatherOverPeriod(SimpleTime start, SimpleTime end, double lat, double lng)
        {
            LocalDateTime begin  = new LocalDateTime(start.Year, start.Month, start.Day, 0, 0);
            LocalDateTime stop   = new LocalDateTime(end.Year, end.Month, end.Day, 0, 0);
            Period        period = Period.Between(begin, stop, PeriodUnits.Days);

            List <ForecastHourly> hourlyData = new List <ForecastHourly>();

            for (int i = 0; i <= period.Days; i++)
            {
                LocalDateTime localtime = begin.PlusDays(i);

                string       timezone = "America/Toronto";
                DateTimeZone tz       = DateTimeZoneProviders.Tzdb[timezone];

                ZonedDateTime zt        = tz.AtLeniently(localtime);
                var           tz_offset = zt.ToDateTimeOffset();

                Task.Run(async() =>
                {
                    var client      = new ForecastApi(API_KEY);
                    Forecast result = await client.GetTimeMachineWeatherAsync(lat, lng, tz_offset);
                    var hourly      = result.Hourly.Hours;
                    for (int h = 0; h < hourly.Count(); h++)
                    {
                        ForecastHourly store_hourly      = new ForecastHourly();
                        store_hourly.ApparentTemperature = hourly[h].ApparentTemperature;
                        store_hourly.CloudCover          = hourly[h].CloudCover;
                        store_hourly.DewPoint            = hourly[h].DewPoint;
                        store_hourly.Humidity            = hourly[h].Humidity;
                        store_hourly.Icon  = hourly[h].Icon;
                        store_hourly.Ozone = hourly[h].Ozone;
                        store_hourly.PrecipitationIntensity   = hourly[h].PrecipitationIntensity;
                        store_hourly.PrecipitationProbability = hourly[h].PrecipitationProbability;
                        store_hourly.Pressure    = hourly[h].Pressure;
                        store_hourly.Summary     = hourly[h].Summary;
                        store_hourly.Temperature = hourly[h].Temperature;
                        store_hourly.Time        = hourly[h].Time;
                        //Instant instant = Instant.FromDateTimeUtc(hourly[h].Time.UtcDateTime); //don't need this, already defined above
                        store_hourly.LocalTime   = zt.LocalDateTime;
                        store_hourly.Visibility  = hourly[h].Visibility;
                        store_hourly.WindBearing = hourly[h].WindBearing;
                        store_hourly.WindSpeed   = hourly[h].WindSpeed;
                        hourlyData.Add(store_hourly);
                    }
                }).Wait();
            }
            return(hourlyData);
        }
예제 #18
0
        public void TestTeamWorkingTime()
        {
            schedule = new WorkSchedule("Team Working Time", "Test team working time");
            Duration  shiftDuration = Duration.FromHours(12);
            Duration  halfShift     = Duration.FromHours(6);
            LocalTime shiftStart    = new LocalTime(7, 0, 0);

            Shift shift = schedule.CreateShift("Team Shift1", "Team shift 1", shiftStart, shiftDuration);

            Rotation rotation = new Rotation("Team", "Rotation");

            rotation.AddSegment(shift, 1, 1);

            LocalDate startRotation = new LocalDate(2017, 1, 1);
            Team      team          = schedule.CreateTeam("Team", "Team", rotation, startRotation);

            team.RotationStart = startRotation;

            // case #1
            LocalDateTime from = startRotation.PlusDays(rotation.GetDayCount()).At(shiftStart);
            LocalDateTime to   = from.PlusDays(1);
            Duration      time = team.CalculateWorkingTime(from, to);

            Assert.IsTrue(time.Equals(shiftDuration));

            // case #2
            to   = from.PlusDays(2);
            time = team.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration));

            // case #3
            to   = from.PlusDays(3);
            time = team.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(shiftDuration)));

            // case #4
            to   = from.PlusDays(4);
            time = team.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(shiftDuration)));

            // case #5
            from = startRotation.PlusDays(rotation.GetDayCount()).At(shiftStart.PlusHours(6));
            to   = from.PlusDays(1);
            time = team.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(halfShift));

            // case #6
            to   = from.PlusDays(2);
            time = team.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration));

            // case #7
            to   = from.PlusDays(3);
            time = team.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(halfShift)));

            // case #8
            to   = from.PlusDays(4);
            time = team.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(shiftDuration)));

            // now crossing midnight
            shiftStart = new LocalTime(18, 0, 0);
            Shift shift2 = schedule.CreateShift("Team Shift2", "Team shift 2", shiftStart, shiftDuration);

            Rotation rotation2 = new Rotation("Case 8", "Case 8");

            rotation2.AddSegment(shift2, 1, 1);

            Team team2 = schedule.CreateTeam("Team2", "Team 2", rotation2, startRotation);

            team2.RotationStart = startRotation;

            // case #1
            from = startRotation.PlusDays(rotation.GetDayCount()).At(shiftStart);
            to   = from.PlusDays(1);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration));

            // case #2
            to   = from.PlusDays(2);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration));

            // case #3
            to   = from.PlusDays(3);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(shiftDuration)));

            // case #4
            to   = from.PlusDays(4);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(shiftDuration)));

            // case #5
            from = startRotation.PlusDays(rotation.GetDayCount()).At(LocalTime.MaxValue);
            to   = from.PlusDays(1);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(halfShift));

            // case #6
            to   = from.PlusDays(2);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration));

            // case #7
            to   = from.PlusDays(3);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(halfShift)));

            // case #8
            to   = from.PlusDays(4);
            time = team2.CalculateWorkingTime(from, to);
            Assert.IsTrue(time.Equals(shiftDuration.Plus(shiftDuration)));
        }
 public LocalDateTime PlusDays()
 {
     return(Sample.PlusDays(3));
 }
        public void PlusDays_EndOfFebruary_NotInLeapYear()
        {
            LocalDateTime start = new LocalDateTime(2011, 2, 26, 12, 15, 8);
            LocalDateTime expected = new LocalDateTime(2011, 3, 6, 12, 15, 8);
            Assert.AreEqual(expected, start.PlusDays(8));

            // Round-trip back across the boundary
            Assert.AreEqual(start, start.PlusDays(8).PlusDays(-8));
        }
        /// <summary>
        /// Populate with values based on the specified array
        /// of value types, repeating the types in cycle.
        /// </summary>
        private void PopulateValues(VariantType[] valueTypes, VariantMatrix result)
        {
            // Initial values to populate the data
            int           stringValueAsInt   = 0;
            bool          boolValue          = false;
            int           intValue           = 0;
            long          longValue          = 0;
            double        doubleValue        = 0.5;
            LocalDate     localDateValue     = new LocalDate(2003, 5, 1);
            LocalTime     localTimeValue     = new LocalTime(10, 15, 30);
            LocalMinute   localMinuteValue   = new LocalMinute(10, 15);
            LocalDateTime localDateTimeValue = new LocalDateTime(2003, 5, 1, 10, 15, 0);
            Instant       instantValue       = new LocalDateTime(2003, 5, 1, 10, 15, 0).ToInstant(DateTimeZone.Utc);

            int valueTypeCount = valueTypes.Length;

            for (int rowIndex = 0; rowIndex < result.RowCount; rowIndex++)
            {
                for (int colIndex = 0; colIndex < result.ColCount; colIndex++)
                {
                    // Repeat value types in cycle
                    var valueType = valueTypes[colIndex % valueTypeCount];
                    switch (valueType)
                    {
                    case VariantType.String:
                        result[rowIndex, colIndex] = $"Str{stringValueAsInt++}";
                        break;

                    case VariantType.Double:
                        result[rowIndex, colIndex] = doubleValue++;
                        break;

                    case VariantType.Bool:
                        result[rowIndex, colIndex] = boolValue;
                        boolValue = !boolValue;
                        break;

                    case VariantType.Int:
                        result[rowIndex, colIndex] = intValue++;
                        break;

                    case VariantType.Long:
                        result[rowIndex, colIndex] = longValue++;
                        break;

                    case VariantType.LocalDate:
                        result[rowIndex, colIndex] = localDateValue;
                        localDateValue             = localDateValue.PlusDays(1);
                        break;

                    case VariantType.LocalTime:
                        result[rowIndex, colIndex] = localTimeValue;
                        localTimeValue             = localTimeValue.PlusHours(1);
                        break;

                    case VariantType.LocalMinute:
                        result[rowIndex, colIndex] = localMinuteValue;
                        localMinuteValue           = localMinuteValue.ToLocalTime().PlusHours(1).ToLocalMinute();
                        break;

                    case VariantType.LocalDateTime:
                        result[rowIndex, colIndex] = localDateTimeValue;
                        localDateTimeValue         = localDateTimeValue.PlusDays(2).PlusHours(2);
                        break;

                    case VariantType.Instant:
                        result[rowIndex, colIndex] = instantValue;
                        instantValue = instantValue;     // TODO Fix, uses previous value
                        break;

                    default: throw new Exception($"Value type {valueType} cannot be stored in VariantMatrix.");
                    }
                }
            }
        }
예제 #22
0
        private static async Task RunAsync(IServiceProvider serviceProvider, ApplicationSettings config)
        {
            // doesn't work for some reason
            var logger = serviceProvider.GetRequiredService <ILogger <ToshHttpApiClient> >();

            var currentTz = DateTimeZoneProviders.Tzdb["Europe/Simferopol"];

            var reportFromLocal = LocalDateTime.FromDateTime(DateTime.Now).With(DateAdjusters.StartOfMonth);
            var reportToLocal   = LocalDateTime.FromDateTime(DateTime.Now).With(DateAdjusters.EndOfMonth);

            reportFromLocal = reportFromLocal.Minus(Period.FromTicks(reportFromLocal.TimeOfDay.TickOfDay));
            reportToLocal   = reportToLocal.Plus(Period.FromHours(24) - Period.FromTicks(reportToLocal.TimeOfDay.TickOfDay));

            var toshHttpApiClient = serviceProvider.GetRequiredService <ToshHttpApiClient>();

            //// Current month report
            //var monthReport = await BuildReportForAPeriodAsync(
            //    serviceProvider, config, toshHttpApiClient,
            //    reportFromLocal,
            //    reportToLocal,
            //    currentTz
            //);

            //Log.Information($"Month report: {reportFrom} - {reportTo}");
            //Log.Information($"TotalExpenes: {monthReport.TotalExpenes}.");
            //Log.Information($"TotalRegularExpenes: {monthReport.TotalRegularExpenes}.");
            //Log.Information($"TotalUnregularExpenes: {monthReport.TotalUnregularExpenes}.");
            //Log.Information($"TotalIncome: {monthReport.TotalIncome}.");
            //Log.Information($"TotalRegularIncome: {monthReport.TotalRegularIncome}.");
            //Log.Information($"TotalUnregularIncome: {monthReport.TotalUnregularIncome}.");
            //Log.Information($"");

            // All time report
            var allReportFromLocal = LocalDateTime.FromDateTime(new DateTime(2017, 01, 01)).With(DateAdjusters.StartOfMonth);
            // var allReportFromLocal = LocalDateTime.FromDateTime(new DateTime(2019, 12, 01)).With(DateAdjusters.StartOfMonth);
            var allReportToLocal = LocalDateTime.FromDateTime(DateTime.Now).With(DateAdjusters.EndOfMonth);
            var allReports       = new List <FinancialMonthReportModel>();

            for (LocalDateTime fromLocal = allReportFromLocal; fromLocal < allReportToLocal;)
            {
                var           month   = Period.FromMonths(1);
                LocalDateTime toLocal = LocalDateTime.FromDateTime(fromLocal.ToDateTimeUnspecified()).With(DateAdjusters.EndOfMonth);
                ZonedDateTime fromUtc = fromLocal.InZoneLeniently(currentTz).ToInstant().InUtc();
                ZonedDateTime toUtc   = toLocal.InZoneLeniently(currentTz).ToInstant().InUtc();

                Log.Information($"Querying {fromLocal} - {toLocal}...");
                var report = await BuildReportForAPeriodAsync(
                    serviceProvider, config, toshHttpApiClient,
                    fromLocal,
                    toLocal,
                    currentTz
                    );

                allReports.Add(report);

                // increment by month
                LocalDateTime nextMonthDayLocal = toLocal.PlusDays(1);
                fromLocal = nextMonthDayLocal.With(DateAdjusters.StartOfMonth);
            }

            // calc grand totals
            allReports = allReports.Select((x, i) =>
            {
                //var prevReports = allReports.GetRange(0, i);
                //x.GrandTotalTradingExpenes = prevReports.Aggregate((decimal)0 , (accum, curr) =>
                //{
                //    accum += curr.GrandTotalTradingExpenes;
                //    return accum;
                //});

                var prevReport = (i == 0 ? null : allReports[i - 1]);

                x.GrandTotalTradingExpenes += (prevReport == null ? 0 + x.TotalTradingExpenes : prevReport.GrandTotalTradingExpenes + x.TotalTradingExpenes);
                x.GrandTotalTradingIncome  += (prevReport == null ? 0 + x.TotalTradingIncome : prevReport.GrandTotalTradingIncome + x.TotalTradingIncome);

                return(x);
            }).ToList();

            // save into CSV
            var csvModels = allReports.Select(x => new FinancialMonthReportCsvModel()
            {
                From                  = x.From.ToString("yyyy-MM-dd"),
                To                    = x.To.ToString("yyyy-MM-dd"),
                PeriodName            = x.PeriodName,
                TotalExpenes          = x.TotalExpenes,
                TotalRegularExpenes   = x.TotalRegularExpenes,
                TotalUnregularExpenes = x.TotalUnregularExpenes,
                TotalIncome           = x.TotalIncome,
                TotalRegularIncome    = x.TotalRegularIncome,
                TotalUnregularIncome  = x.TotalUnregularIncome,

                TotalTradingExpenes = x.TotalTradingExpenes,
                TotalTradingIncome  = x.TotalTradingIncome,

                GrandTotalTradingExpenes = x.GrandTotalTradingExpenes,
                GrandTotalTradingIncome  = x.GrandTotalTradingIncome,
            });

            string exportPath = "./data-reports";

            Directory.CreateDirectory(exportPath);
            using (var streamWriter = new StreamWriter(Path.Combine(exportPath, $"full-history-report-{allReportFromLocal.ToDateTimeUnspecified().ToString("yyyy-MM-dd")}--{allReportToLocal.ToDateTimeUnspecified().ToString("yyyy-MM-dd")}.csv")))
            {
                using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture))
                {
                    csvWriter.WriteHeader <FinancialMonthReportCsvModel>();
                    await csvWriter.NextRecordAsync();

                    await csvWriter.WriteRecordsAsync(csvModels);

                    await csvWriter.FlushAsync();
                }
            }
            Log.Information($"");
        }
예제 #23
0
 public LocalDateTime PlusDays() => Sample.PlusDays(3);
예제 #24
0
        private void DrawBar(long originSeconds, Location location, LocalDateTime start, LocalDateTime end, BarSize barHeight, string label, int top)
        {
            if (start >= end)
            {
                end = end.PlusDays(1);
            }
            if (start >= end)
            {
                return;
            }

            int x1 = DateToPixels(originSeconds, start.InZoneLeniently(location.TimeZone));
            int x2 = DateToPixels(originSeconds, end.InZoneLeniently(location.TimeZone));

            if (x1 <= 0)
            {
                x1 = 0;
            }
            else if (x1 >= width)
            {
                return;
            }
            if (x2 >= width)
            {
                x2 = width - 1;
            }
            if (x2 < 0)
            {
                return;
            }

            var tb = new TextBlock
            {
                Foreground           = MyBrushes.Gray224,
                Background           = location.Brush,
                Opacity              = .95,
                TextAlignment        = TextAlignment.Center,
                LineHeight           = 11,
                LineStackingStrategy = LineStackingStrategy.BlockLineHeight,
                Width = x2 - x1 + 1
            };

            var y1 = top;

            switch (barHeight)
            {
            case BarSize.Holiday:
            case BarSize.Weekend:
                tb.Background         = location.Brush.Clone();
                tb.Background.Opacity = .5;
                tb.Foreground         = MyBrushes.Gray224;
                tb.Height             = 11;
                tb.Text = label;
                tb.FitText();
                break;

            case BarSize.L:
                tb.Height = 11;
                if (zoomFormats.SecondsPerPixel < 1800)
                {
                    tb.Text = label;
                    tb.FitText();
                }
                break;

            case BarSize.M:
                tb.Height = 5;
                y1       += 3;
                break;

            case BarSize.S:
                tb.Height = 1;
                y1       += 5;
                break;
            }
            Canvas.SetTop(tb, y1);
            Canvas.SetLeft(tb, x1);
            canvas.Children.Add(tb);
        }
 public void PlusDays()
 {
     Sample.PlusDays(3).Consume();
 }
예제 #26
0
 public IDateTime PlusDays(int days)
 {
     return(new DateTime(_localDateTime.PlusDays(days)));
 }
예제 #27
0
        public void TestGenericShift()
        {
            // regular work week with holidays and breaks
            schedule = new WorkSchedule("Regular 40 hour work week", "9 to 5");

            // holidays
            NonWorkingPeriod memorialDay = schedule.CreateNonWorkingPeriod("MEMORIAL DAY", "Memorial day", new LocalDateTime(2016, 5, 30, 0, 0, 0),
                                                                           Duration.FromHours(24));

            schedule.CreateNonWorkingPeriod("INDEPENDENCE DAY", "Independence day", new LocalDateTime(2016, 7, 4, 0, 0, 0),
                                            Duration.FromHours(24));
            schedule.CreateNonWorkingPeriod("LABOR DAY", "Labor day", new LocalDateTime(2016, 9, 5, 0, 0, 0),
                                            Duration.FromHours(24));
            schedule.CreateNonWorkingPeriod("THANKSGIVING", "Thanksgiving day and day after",
                                            new LocalDateTime(2016, 11, 24, 0, 0, 0), Duration.FromHours(48));
            schedule.CreateNonWorkingPeriod("CHRISTMAS SHUTDOWN", "Christmas week scheduled maintenance",
                                            new LocalDateTime(2016, 12, 25, 0, 30, 0), Duration.FromHours(168));

            // each shift duration
            Duration  shiftDuration = Duration.FromHours(8);
            LocalTime shift1Start   = new LocalTime(7, 0, 0);
            LocalTime shift2Start   = new LocalTime(15, 0, 0);

            // shift 1
            Shift shift1 = schedule.CreateShift("Shift1", "Shift #1", shift1Start, shiftDuration);

            // breaks
            shift1.CreateBreak("10AM", "10 am break", new LocalTime(10, 0, 0), Duration.FromMinutes(15));
            shift1.CreateBreak("LUNCH", "lunch", new LocalTime(12, 0, 0), Duration.FromHours(1));
            shift1.CreateBreak("2PM", "2 pm break", new LocalTime(14, 0, 0), Duration.FromMinutes(15));

            // shift 2
            Shift shift2 = schedule.CreateShift("Shift2", "Shift #2", shift2Start, shiftDuration);

            // shift 1, 5 days ON, 2 OFF
            Rotation rotation1 = new Rotation("Shift1", "Shift1");

            rotation1.AddSegment(shift1, 5, 2);

            // shift 2, 5 days ON, 2 OFF
            Rotation rotation2 = new Rotation("Shift2", "Shift2");

            rotation2.AddSegment(shift2, 5, 2);

            LocalDate startRotation = new LocalDate(2016, 1, 1);
            Team      team1         = schedule.CreateTeam("Team1", "Team #1", rotation1, startRotation);
            Team      team2         = schedule.CreateTeam("Team2", "Team #2", rotation2, startRotation);

            // same day
            LocalDateTime from = startRotation.PlusDays(7).At(shift1Start);
            LocalDateTime to;

            Duration totalWorking = Duration.Zero;

            // 21 days, team1
            Duration d = Duration.Zero;

            for (int i = 0; i < 21; i++)
            {
                to           = from.PlusDays(i);
                totalWorking = team1.CalculateWorkingTime(from, to);
                int dir = team1.GetDayInRotation(to.Date);

                Assert.IsTrue(totalWorking.Equals(d));

                TimePeriod period = rotation1.GetPeriods()[dir - 1];
                if (period is Shift)
                {
                    d = d.Plus(shiftDuration);
                }
            }
            Duration totalSchedule = totalWorking;

            // 21 days, team2
            from = startRotation.PlusDays(7).At(shift2Start);
            d    = Duration.Zero;

            for (int i = 0; i < 21; i++)
            {
                to           = from.PlusDays(i);
                totalWorking = team2.CalculateWorkingTime(from, to);
                int dir = team2.GetDayInRotation(to.Date);

                Assert.IsTrue(totalWorking.Equals(d));

                if (rotation1.GetPeriods()[dir - 1] is Shift)
                {
                    d = d.Plus(shiftDuration);
                }
            }
            totalSchedule = totalSchedule.Plus(totalWorking);

            Duration scheduleDuration   = schedule.CalculateWorkingTime(from, from.PlusDays(21));
            Duration nonWorkingDuration = schedule.CalculateNonWorkingTime(from, from.PlusDays(21));

            Assert.IsTrue(scheduleDuration.Plus(nonWorkingDuration).Equals(totalSchedule));

            // breaks
            Duration allBreaks = Duration.FromMinutes(90);

            Assert.IsTrue(shift1.CalculateBreakTime().Equals(allBreaks));

            // misc
            WorkSchedule schedule2 = new WorkSchedule();

            Shift shift3 = new Shift();

            shift3.Name = "Shift3";
            Assert.IsTrue(shift3.WorkSchedule == null);
            Assert.IsTrue(shift3.CompareTo(shift3) == 0);

            Team team3 = new Team();

            Assert.IsTrue(team3.WorkSchedule == null);

            RotationSegment segment = new RotationSegment();

            segment.Sequence      = 1;
            segment.StartingShift = shift2;
            segment.DaysOn        = 5;
            segment.DaysOff       = 2;
            Assert.IsTrue(segment.Rotation == null);

            Rotation rotation3 = new Rotation();

            rotation3.Name = "Rotation3";
            Assert.IsTrue(rotation3.CompareTo(rotation3) == 0);
            Assert.IsTrue(rotation3.RotationSegments.Count == 0);

            NonWorkingPeriod nwp = new NonWorkingPeriod();

            Assert.IsTrue(nwp.WorkSchedule == null);


            Assert.IsTrue(team1.WorkSchedule.Equals(schedule));


            Assert.IsTrue(!team1.IsDayOff(startRotation));


            Assert.IsTrue(team1.CompareTo(team1) == 0);
            team3.Rotation = rotation1;


            Assert.IsTrue(!memorialDay.IsInPeriod(new LocalDate(2016, 1, 1)));

            runBaseTest(schedule, Duration.FromHours(40), Duration.FromDays(7), new LocalDate(2016, 1, 1));
        }
예제 #28
0
 public void PlusDays()
 {
     SampleStartDateTime.PlusDays(3);
 }
 /// <summary>
 /// Add days
 /// </summary>
 /// <param name="ld"></param>
 /// <param name="days"></param>
 /// <returns></returns>
 public static LocalDateTime AddDays(this LocalDateTime ld, int days) => ld.PlusDays(days);