public async Task<bool> UpdateWorkDay(WorkDay workDay)
        {
            var request = new RestRequest(string.Format("/Update?Id={0}&StartDate={1}&EndDate={2}&BreakTime={3}", workDay.Id, workDay.StartDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ"), workDay.EndDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ"), workDay.BreakTime), Method.PUT);
            var success = await this.restClient.ExecuteTaskAsync(request);

            if (success.StatusCode == HttpStatusCode.OK)
                return true;

            return false;
        }
        public async Task<bool> DeleteWorkDay(WorkDay workDay)
        {
            var request = new RestRequest(string.Format("/Delete?Id={0}", workDay.Id), Method.DELETE);
            var success = await this.restClient.ExecuteTaskAsync(request);

            if (success.StatusCode == HttpStatusCode.OK)
                return true;

            return false;
        }
Beispiel #3
0
        public ActionResult DeleteConfirmed(int id)
        {
            // This deletes the specific event that is connected to the day.
            WorkDay deleteDay   = db.WorkDays.Include(w => w.Day).Include(s => s.Shifts).Where(x => x.ID == id).First();
            Event   deleteEvent = db.Events.Where(x => x.start_date == deleteDay.Day.Date).First();

            db.Events.Remove(deleteEvent);
            WorkDay workDay = db.WorkDays.Find(id);

            db.WorkDays.Remove(workDay);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #4
0
 public Charge(WorkDay day)
 {
     this.Key = day.WorkDayKey;
     this.Type = ChargeType.WorkDay;
     this.Include = day.Printed == null;
     this.Date = day.Date;
     this.Description = "Materials/yardage charges";
     this.Total = Math.Round((day.PoundsDistillers * day.PricePerTonDistillers
                                 + day.PoundsCorn * day.PricePerTonCorn
                                 + day.PoundsHay * day.PricePerTonHay
                                 + day.PoundsMinerals * day.PricePerTonMinerals) / 2000
                                 + day.NumberOfHeadYardage * day.PricePerHeadYardage, 2);
 }
 public ActionResult Create(WorkDay newWorkDay, FormCollection collection)
 {
     try
     {
         // TODO: Add insert logic here
         _workHistory.AddDay(newWorkDay);
         return(RedirectToAction("Index"));
     }
     catch
     {
         return(View());
     }
 }
 public ActionResult Edit(int id, WorkDay dayEdit, FormCollection collection)
 {
     try
     {
         // TODO: Add update logic here
         _workHistory.EditWorkDay(dayEdit);
         return(RedirectToAction("Index"));
     }
     catch (Exception ex)
     {
         return(View());
     }
 }
Beispiel #7
0
        public void WDParser_WhiteSpace_StillWork()
        {
            WorkDay       wd  = new WorkDay(1, 1, 1, null);
            WorkDayParser wdp = new WorkDayParser(new WorkDayParserSettings {
                InsertDayBreak = true, DayBreakTime = new TimeItem(12, 00), DayBreakDurationInMinutes = 30
            });
            var workItemParserResult = wdp.Parse("9 : 00 , 2; 11111   -111 , 3;   22222-222", ref wd);

            Assert.IsTrue(workItemParserResult.Success, workItemParserResult.Error);
            CollectionAssert.IsNotEmpty(wd.Items);
            CollectionAssert.AreEqual(new[] { new WorkItem(new TimeItem(9, 0), new TimeItem(11, 0), "11111", "111"), new WorkItem(new TimeItem(11, 0), new TimeItem(12, 00), "22222", "222"), new WorkItem(new TimeItem(12, 30), new TimeItem(14, 30), "22222", "222") }, wd.Items);
            Assert.IsEmpty(workItemParserResult.Error);
        }
Beispiel #8
0
        public void WDParser_ParseHourFragment2_MultiplyBy60()
        {
            WorkDay       wd  = new WorkDay(1, 1, 1, null);
            WorkDayParser wdp = new WorkDayParser();
            var           workItemParserResult = wdp.Parse("9:15,7.25;11111-111", ref wd);

            Assert.IsTrue(workItemParserResult.Success, workItemParserResult.Error);
            CollectionAssert.IsNotEmpty(wd.Items);
            CollectionAssert.AreEqual(new[] {
                new WorkItem(new TimeItem(9, 15), new TimeItem(16, 30), "11111", "111")
            }, wd.Items);
            Assert.IsEmpty(workItemParserResult.Error);
        }
Beispiel #9
0
        public void WDParser_ParseDescriptionWithItemSeparator_GetDesc()
        {
            WorkDay       wd  = new WorkDay(1, 1, 1, null);
            WorkDayParser wdp = new WorkDayParser();
            var           workItemParserResult = wdp.Parse("9:15,7.25;11111-111(lal,ala)", ref wd);

            Assert.IsTrue(workItemParserResult.Success, workItemParserResult.Error);
            CollectionAssert.IsNotEmpty(wd.Items);
            CollectionAssert.AreEqual(new[] {
                new WorkItem(new TimeItem(9, 15), new TimeItem(16, 30), "11111", "111", "lal,ala", null, string.Empty)
            }, wd.Items);
            Assert.IsEmpty(workItemParserResult.Error);
        }
Beispiel #10
0
    public void ParseRows()
    {
        for (int i = 0; i < 3; i++)
        {
            Row dateRow          = Rows[1 + (i * 8)]; // First row is empty, then adds a week each iteration.
            Row scheduleHoursRow = Rows[2 + (i * 8)];
            Row activityRow      = Rows[3 + (i * 8)];
            Row locationRow      = Rows[4 + (i * 8)];
            Row scheduleTimesRow = Rows[5 + (i * 8)];
            Row commentsRow      = Rows[6 + (i * 8)];

            int dayIndex = 1; // 0 is column names
            while (true)
            {
                var    workDay    = new WorkDay();
                String dateString = dateRow.cells[dayIndex].value;

                // Get the day of the week
                workDay.Day = workDay.enumDay(dateString);
                if (workDay.Day == WorkDay.DayEnum.INVALID)
                {
                    break;
                }

                // split the string "Tue 6/23"
                // and use the second part ['Tue', '6/23']
                String datePart = dateString.Split(' ')[1];
                workDay.Date = DateTime.Parse(datePart);

                workDay.Hours    = float.Parse(scheduleHoursRow.cells[dayIndex].value.Replace(":", "."));
                workDay.Activity = activityRow.cells[dayIndex].value;
                workDay.Comments = commentsRow.cells[dayIndex].value;
                workDay.Location = workDay.ConvertLocation(locationRow.cells[dayIndex].value);


                String   timeSpanPart = scheduleTimesRow.cells[dayIndex].value;
                String[] times        = timeSpanPart.Split('-'); // split '2:00 AM-8:00 PM' on the '-'

                workDay.StartTime = times[0];
                workDay.EndTime   = times.Length == 1 ? times[0] : times[1];

                if (workDay.Hours > 0)
                {
                    workDay.StartDateTime = DateTime.Parse(workDay.Date.ToShortDateString() + " " + workDay.StartTime);
                    workDay.EndDateTime   = DateTime.Parse(workDay.Date.ToShortDateString() + " " + workDay.EndTime);
                }
                Schedule.Add(workDay);
                dayIndex++;
            }
        }
    }
Beispiel #11
0
        // GET: WorkDay/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            WorkDay workDay = db.WorkDays.Find(id);

            if (workDay == null)
            {
                return(HttpNotFound());
            }
            return(View(workDay));
        }
        public void WDParser_InsertEndTimePauseItemWithComment_LeavePause()
        {
            WorkDay       wd  = new WorkDay(1, 1, 1, null);
            WorkDayParser wdp = new WorkDayParser();
            var           workItemParserResult = wdp.Parse("7,1;11111-111,-10:30(massage)!,2;11111-111", ref wd);

            Assert.IsTrue(workItemParserResult.Success, workItemParserResult.Error);
            CollectionAssert.IsNotEmpty(wd.Items);
            CollectionAssert.AreEqual(new[] {
                new WorkItem(new TimeItem(7, 0), new TimeItem(8, 0), "11111", "111"),
                new WorkItem(new TimeItem(10, 30), new TimeItem(12, 30), "11111", "111")
            }, wd.Items);
            Assert.IsEmpty(workItemParserResult.Error);
        }
        public void WDParser_SetEmptyStringAfterSuccessfulParsing_DeleteItems()
        {
            WorkDay       wd  = new WorkDay(1, 1, 1, null);
            WorkDayParser wdp = new WorkDayParser();
            var           workItemParserResult = wdp.Parse("7,2;11111", ref wd);

            Assert.IsTrue(workItemParserResult.Success, workItemParserResult.Error);
            CollectionAssert.IsNotEmpty(wd.Items);
            CollectionAssert.AreEqual(new[] { new WorkItem(new TimeItem(7, 0), new TimeItem(9, 0), "11111", string.Empty) }, wd.Items);
            Assert.IsEmpty(workItemParserResult.Error);
            wd.OriginalString = string.Empty;
            CollectionAssert.IsEmpty(wd.Items);
            Assert.AreEqual(null, wd.HoursDuration);
        }
Beispiel #14
0
        private void TextBox_Loaded(object sender, RoutedEventArgs e)
        {
            var textBox = sender as TextBox;

            if (textBox != null)
            {
                WorkDay workDay = textBox.Tag as WorkDay;
                if (workDay != null && workDay.FocusMe)
                {
                    textBox.Focus();
                    textBox.Select(textBox.Text.Length, 0);
                }
            }
        }
Beispiel #15
0
        // GET: WorkDays/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            WorkDay workDay = await db.WorkDays.FindAsync(id);

            if (workDay == null)
            {
                return(HttpNotFound());
            }
            return(View(workDay));
        }
        public IHttpActionResult DeleteWorkDay(int id)
        {
            WorkDay workDay = db.WorkDays.Find(id);

            if (workDay == null)
            {
                return(NotFound());
            }

            db.WorkDays.Remove(workDay);
            db.SaveChanges();

            return(Ok(workDay));
        }
Beispiel #17
0
        private WorkDay CreateWorkday(Contract currentContract)
        {
            if (currentContract == null)
            {
                throw new ArgumentNullException(nameof(Contract));
            }

            _workDayToday = new WorkDay {
                ContractId = currentContract.Id, Date = _now.Now.Date, WorkDayType = _now.Now.ToWorkDayType(), WorkingPeriods = new List <WorkingPeriod>()
            };
            _workDayToday.RequiredHours = _workDayToday.GetRequiredHoursForDay(currentContract.HoursPerWeek);
            _context.WorkDays.Add(_workDayToday);

            return(_workDayToday);
        }
Beispiel #18
0
        private void AddWorkDay(DayOfWeek dow)
        {
            var wDay = new WorkDay();

            wDay.WorkTime.DateOfWork = CalcDayOfWeek(currentTimeFrame, dow);

            var dayToAdd = dataManager.CurrentUser.AssignedWorkDays.FirstOrDefault(d => d.WorkTime.DateOfWork.Date.Equals(wDay.WorkTime.DateOfWork.Date)) ?? wDay;

            CurrentWorkWeek.Add(dayToAdd);

            if (dayToAdd.WorkTime.DateOfWork.Date.Equals(DateTime.Now.Date))
            {
                CurrentWorkDay = dayToAdd;
            }
        }
        public void WDParser_BrokenHours_CalculateCorrectly()
        {
            WorkDay       wd  = new WorkDay(1, 1, 1, null);
            WorkDayParser wdp = new WorkDayParser();
            var           workItemParserResult = wdp.Parse("8:15,-15:30;11111-111,1;11111-111", ref wd);

            Assert.IsTrue(workItemParserResult.Success, workItemParserResult.Error);
            CollectionAssert.IsNotEmpty(wd.Items);
            CollectionAssert.AreEqual(new[] {
                new WorkItem(new TimeItem(8, 15), new TimeItem(15, 30), "11111", "111"),
                new WorkItem(new TimeItem(15, 30), new TimeItem(16, 30), "11111", "111")
            }, wd.Items);
            Assert.IsEmpty(workItemParserResult.Error);
            Assert.AreEqual(8.25, wd.HoursDuration);
        }
Beispiel #20
0
        public IActionResult OnGet(string title, string year, string month, string day)
        {
            if (title == null || year == null || month == null || day == null)
            {
                return(RedirectToPage("OnlineRecords"));
            }

            if (!CheckAll(title, year, month, day))
            {
                return(RedirectToPage("OnlineRecords"));
            }

            WorkDay = new WorkDay(_context.Records.ToList(), DateTime);
            return(Page());
        }
Beispiel #21
0
        //TODO - Bug whit EDIT WORKDAY - when you change a workday the corrensponding event doesn't change- You can't choose the option on the site
        // GET: WorkDay/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            WorkDay workDay = db.WorkDays.Find(id);

            if (workDay == null)
            {
                return(HttpNotFound());
            }
            ViewBag.DayID   = new SelectList(db.Days, "ID", "Date", workDay.DayID);
            ViewBag.ShiftID = new SelectList(db.Shifts, "ID", "ShiftName", workDay.ShiftID);
            return(View(workDay));
        }
Beispiel #22
0
 public static int Insert(WorkDay workDay)
 {
     try
     {
         using (var db = new Context())
         {
             db.WorkDays.Add(workDay);
             db.SaveChanges();
             return(workDay.WorkDayId);
         }
     }
     catch (Exception e)
     {
         return(0);
     }
 }
Beispiel #23
0
        public async Task <object> Create(WorkDay newWorkDay)
        {
            ObjectResponse response;

            try
            {
                IQueryable <WorkDay> workDays = Context.WorkDays
                                                .Where(wd => wd.PositionId == newWorkDay.PositionId);

                if (workDays.Count() < 1)
                {
                    WorkDay workDay = new WorkDay
                    {
                        Day         = newWorkDay.Day,
                        CreatedById = newWorkDay.CreatedById,
                        Date        = newWorkDay.Date == null ? DateTime.Now : default,
Beispiel #24
0
 public IActionResult GetWorkDayById(string id)
 {
     try
     {
         WorkDay w = _workDaysService.GetWorkDay(id);
         if (w == null)
         {
             return(NotFound("Work day with id not found"));
         }
         return(Ok(_mapper.Map <WorkDayDto>(w)));
     }
     catch (Exception ex)
     {
         return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
     }
 }
Beispiel #25
0
        public async Task <bool> UpdateWorkDayAsync(WorkDay item)
        {
            if (item == null || item.Id == null || !IsConnected)
            {
                return(false);
            }

            var serializedItem = JsonConvert.SerializeObject(item);
            var buffer         = Encoding.UTF8.GetBytes(serializedItem);
            var byteContent    = new ByteArrayContent(buffer);

            var parsedId = item.Id.ToString();
            var response = await client.PutAsync(new Uri($"api/workday/{parsedId}"), byteContent);

            return(response.IsSuccessStatusCode);
        }
        private decimal GetHours(WorkDay x)
        {
            var startHour    = x.StartTime.Hour;
            var startMinutes = x.StartTime.Minute;
            var endHour      = x.EndTime.Hour;
            var endMinutes   = x.EndTime.Minute;
            var breakHours   = x.BreakTime.Hour;
            var breakMinutes = x.BreakTime.Minute;

            decimal breakTotal = breakHours + (breakMinutes / 60);
            decimal houres     = endHour - startHour;
            decimal minutes    = endMinutes - startMinutes;
            decimal total      = houres + (minutes / 60);

            return(Math.Round(total - breakTotal));
        }
        public WorkDay CreateCustomWorkDay(CreateCustomWorkDay createCustomWorkDay)
        {
            WorkDay newWorkDay = new WorkDay()
            {
                Id       = 99,
                BarberId = createCustomWorkDay.BarberId,
                Day      = null,
                Custom   = 1,
                Date     = createCustomWorkDay.Date,
                OffDay   = createCustomWorkDay.OffDay
            };

            _workDays.Add(newWorkDay);

            return(newWorkDay);
        }
Beispiel #28
0
        public async Task <IActionResult> Create(WorkDay workDay)
        {
            if (ModelState.IsValid)
            {
                workDay.Id           = _context.WorkDays.Max(w => w.Id) + 1;
                workDay.CreatedDate  = DateTime.Now;
                workDay.ModifiedDate = DateTime.Now;

                _context.Add(workDay);
                await _context.SaveChangesAsync();

                TempData["Toast"] = Toasts.Created;
                return(RedirectToAction(nameof(Index)));
            }
            return(View(workDay));
        }
Beispiel #29
0
        public void HoursDuration_OnAMonth_ShouldSumCorrect()
        {
            WorkMonth wm = new WorkMonth(2011, 1, null, new WorkDayParserSettings(), 1);
            WorkDay   wd = wm.Days.First();

            wd.AddWorkItem(new WorkItem(new TimeItem(10), new TimeItem(11)));
            Assert.AreEqual(1, wd.HoursDuration);
            wd.AddWorkItem(new WorkItem(new TimeItem(11), new TimeItem(12)));
            Assert.AreEqual(2, wd.HoursDuration);
            wd.AddWorkItem(new WorkItem(new TimeItem(12), new TimeItem(12, 15)));
            Assert.AreEqual(2.25, wd.HoursDuration);
            wd.AddWorkItem(new WorkItem(new TimeItem(12, 15), new TimeItem(13)));
            Assert.AreEqual(3, wd.HoursDuration);

            Assert.AreEqual(3, wm.HoursDuration);
        }
Beispiel #30
0
        public async Task <WorkDay> CheckIfWorkDayIsStarted()
        {
            var response = await client.GetAsync($"api/workday/currentday");

            var responseConent = await response.Content.ReadAsStringAsync();

            var workDay = JsonConvert.DeserializeObject <WorkDay>(responseConent);

            if (response.IsSuccessStatusCode)
            {
                return(workDay);
            }

            var emptyWorkDay = new WorkDay();

            return(emptyWorkDay);
        }
        //creates a work day if it doesn't already exist and assigns engineers
        private void CreateWorkDayByTask(LeafTask task)
        {
            bool addDay = false;
            WorkDay day;
            day = schedule.WorkDays.Where(wd => wd.Day == currentDay).SingleOrDefault();

            if (day == null)
            {
                day = new WorkDay(currentDay);
                addDay = true;
            }

            PopulateWorkDayWithEngineers(task, day);

            if (addDay)
                schedule.WorkDays.Add(day);
        }
        public bool Validate(WorkDay context)
        {
            var events = context.AllAccessEvents.OrderBy(x => x.EventTime).ToList();

            if (events.Count < 2)
            {
                return(false);
            }
            var first = events[0];
            var last  = events[events.Count - 1];

            var d                 = context.Date;
            var idealDayStart     = new DateTime(d.Year, d.Month, d.Day, 9, 0, 0);
            var idealDayEnd       = new DateTime(d.Year, d.Month, d.Day, 18, 0, 0);
            var allowedLateTiming = new DateTime(d.Year, d.Month, d.Day, 19, 30, 0);
            var lateMostTiming    = new DateTime(d.Year, d.Month, d.Day, 20, 30, 0);

            var validationStatus = true;

            if (first.EventTime > (idealDayStart + TimeSpan.FromMinutes(15.0)))
            {
                context.Violations.Add(WorkTimeViolation.GetViolation(WorkTimeViolationType.LateEntry));
                validationStatus = false;
            }
            if (last.EventTime < (idealDayEnd - TimeSpan.FromMinutes(15.0)))
            {
                context.Violations.Add(WorkTimeViolation.GetViolation(WorkTimeViolationType.EarlyLeaving));
                validationStatus = false;
            }
            if (context.WorkTime < TimeSpan.FromHours(8.5))
            {
                context.Violations.Add(WorkTimeViolation.GetViolation(WorkTimeViolationType.TimeDurationViolation_TotalDurationLessThan9Hours));
                validationStatus = false;
            }
            if (last.EventTime > allowedLateTiming)
            {
                context.Violations.Add(WorkTimeViolation.GetViolation(WorkTimeViolationType.StayingLate));
                validationStatus = false;
            }
            if (last.EventTime > lateMostTiming)
            {
                context.Violations.Add(WorkTimeViolation.GetViolation(WorkTimeViolationType.StayingVeryLate));
                validationStatus = false;
            }
            return(validationStatus);
        }
        public async Task Handler_Ignores_Incomplete_Periods()
        {
            using (var context = new AppDbContext(_options))
            {
                var incompleteWorkday = new WorkDay()
                {
                    Id             = 3,
                    ContractId     = 1,
                    Date           = new DateTime(2021, 02, 03),
                    WorkDayType    = WorkDayType.Workday,
                    TotalHours     = 4.5,
                    WorkingPeriods = new List <WorkingPeriod>()
                    {
                        new WorkingPeriod {
                            Id = 6, StartTime = new DateTime(2021, 02, 03, 8, 20, 0), EndTime = new DateTime(2021, 02, 03, 12, 50, 0)
                        },
                        new WorkingPeriod {
                            Id = 7, StartTime = new DateTime(2021, 02, 03, 15, 40, 0)
                        },
                    }
                };
                context.WorkDays.Add(incompleteWorkday);
                context.SaveChanges();
            }

            var request = new IndexRequest()
            {
                User = new AppUser {
                    Id = 1
                }, CurrentContract = new() { HoursPerWeek = 40, TotalOverhours = TimeSpan.FromHours(-0.0832999) }
            };

            var response = await _testObject.Handle(request, CancellationToken.None);

            response.TotalOverHours.TotalHours.Should().BeApproximately(-0.0832999, 0.000002);
            response.WorkDays.Count.Should().Be(5);
            response.WorkDays.Items.FirstOrDefault(x => x.Id == 1).Overhours.TotalHours.Should().Be(-0.5);
            response.WorkDays.Items.FirstOrDefault(x => x.Id == 2).Overhours.TotalHours.Should().BeApproximately(0.4166999, 0.000002);
            response.WorkDays.Items.FirstOrDefault(x => x.Id == 3).Overhours.TotalHours.Should().Be(-3.5);
            response.WorkDays.Items.FirstOrDefault(x => x.Id == 1).WorkHours.TotalHours.Should().Be(7.5);
            response.WorkDays.Items.FirstOrDefault(x => x.Id == 2).WorkHours.TotalHours.Should().Be(8.4167);
            response.WorkDays.Items.FirstOrDefault(x => x.Id == 3).WorkHours.TotalHours.Should().Be(4.5);
            response.MostRecentWorkPeriods.Count.Should().Be(5);
            response.HasOngoingWorkPeriod.Should().BeTrue();
        }
        public void WDParser_PartEndsAtBreakTimeWithAbsolutEnd_AddBreakCorrectly()
        {
            WorkDay wd = new WorkDay(1, 1, 1, null);
            WorkDayParserSettings workDayParserSettings = new WorkDayParserSettings {
                DayBreakDurationInMinutes = 30, InsertDayBreak = true, DayBreakTime = new TimeItem(12)
            };
            WorkDayParser wdp = new WorkDayParser(workDayParserSettings);
            var           workItemParserResult = wdp.Parse("8,4;11111-111,-17:00;11111-111", ref wd);

            Assert.IsTrue(workItemParserResult.Success, workItemParserResult.Error);
            CollectionAssert.IsNotEmpty(wd.Items);
            CollectionAssert.AreEqual(new[] {
                new WorkItem(new TimeItem(8), new TimeItem(12, 00), "11111", "111"),
                new WorkItem(new TimeItem(12, 30), new TimeItem(17), "11111", "111")
            }, wd.Items);
            Assert.IsEmpty(workItemParserResult.Error);
            Assert.AreEqual(8.5, wd.HoursDuration);
        }
        /// <summary>
        ///     The Analyze by day.
        /// </summary>
        /// <returns>
        ///     The <see>
        ///         <cref>List</cref>
        ///     </see>
        ///     .
        /// </returns>
        public List<WorkDay> AnalyzeByDay()
        {
            IEnumerable<IGrouping<DateTime, TaskEntry>> groupedByDate = this.taskEntries.GroupBy(t => t.Date);

            List<WorkDay> tasksPerDay = new List<WorkDay>();

            foreach (IGrouping<DateTime, TaskEntry> taskGroup in groupedByDate)
            {
                WorkDay workDay = new WorkDay(taskGroup.Key)
                                      {
                                          TotalDuration =
                                              taskGroup.Aggregate(
                                                  new TimeSpan(),
                                                  (current, taskEntry) =>
                                                  current + taskEntry.Duration)
                                      };
                tasksPerDay.Add(workDay);
            }

            return tasksPerDay;
        }
        public async Task<bool> AddWorkDay(WorkDay newWorkDay)
        {
            // add new week?
            var weekItem = Weeks.FirstOrDefault(x => x.WeekNumber == newWorkDay.StartDateTime.GetIso8601WeekOfYear());
            if (weekItem == null)
            {
                weekItem = new Week();
                weekItem.WorkDays.Add(newWorkDay);
                weekItem.WorkDays.BubbleSort();
                Weeks.Add(weekItem);
                Weeks.BubbleSort();
            }
            else
            {
                var workdayItem = weekItem.WorkDays.FirstOrDefault(x => x.StartDateTime.Date == newWorkDay.StartDateTime.Date);
                if (workdayItem != null)
                    return false;

                weekItem.WorkDays.Add(newWorkDay);
                weekItem.WorkDays.BubbleSort();
                Weeks.Add(weekItem);
                Weeks.BubbleSort();
            }

            Insights.Track("AddWorkDay call to OutSystems");
            return await this.dataLayer.AddWorkDay(newWorkDay);
        }
 private void RemoveWorkDayFromWeeks(WorkDay workDay)
 {
     var week = Weeks.SingleOrDefault(x => x.WeekNumber == workDay.WeekNumber);
     if (week != null)
     {
         var day = week.WorkDays.FirstOrDefault(x => x.StartDateTime.Date == workDay.StartDateTime.Date);
         if (day != null)
         {
             if (week.WorkDays.Any() && week.WorkDays.Count > 1)
             {
                 Weeks.Remove(week);
                 week.WorkDays.Remove(day);
                 Weeks.Add(week);
                 Weeks.BubbleSort();
             }
             else
             {
                 Weeks.Remove(week);
                 Weeks.BubbleSort();
             }
         }
     }
 }
 partial void DeleteWorkDay(WorkDay instance);
 partial void InsertWorkDay(WorkDay instance);
	private void attach_WorkDays(WorkDay entity)
	{
		this.SendPropertyChanging();
		entity.Worker = this;
	}
Beispiel #41
0
        public static WorkDay Clone(WorkDay oldDay, WorkDay newDay)
        {
            newDay.WorkDayKey = oldDay.WorkDayKey;
            newDay.CustomerID = oldDay.CustomerID;
            newDay.Date = oldDay.Date;
            newDay.PoundsDistillers = oldDay.PoundsDistillers;
            newDay.PricePerTonDistillers = oldDay.PricePerTonDistillers;
            newDay.PoundsHay = oldDay.PoundsHay;
            newDay.PricePerTonHay = oldDay.PricePerTonHay;
            newDay.PoundsCorn = oldDay.PoundsCorn;
            newDay.PricePerTonCorn = oldDay.PricePerTonCorn;
            newDay.PoundsMinerals = oldDay.PoundsMinerals;
            newDay.PricePerTonMinerals = oldDay.PricePerTonMinerals;
            newDay.NumberOfHeadYardage = oldDay.NumberOfHeadYardage;
            newDay.PricePerHeadYardage = oldDay.PricePerHeadYardage;
            newDay.Printed = oldDay.Printed;

            return newDay;
        }
Beispiel #42
0
    protected void ButtSend_Click(object sender, EventArgs e)
    {
        DataClassesDataContext dbo = new DataClassesDataContext();
        DateTime date = new DateTime();
        DateTime enter = new DateTime();
        DateTime exit = new DateTime();
        WorkDay wd = new WorkDay();
         string tryc = TextBox1.Text;
         string[] buf = tryc.Split('@');
         foreach (string l in buf)
         {
             if (l != "")
             {
                 string[] temp = l.Split('|');
                 string[] dates = temp[0].Split('/');
                 string[] enterT = temp[1].Split(':');
                 string[] exitT = temp[2].Split(':');
                 string mm = dates[0];
                 string dd = dates[1];
                 string yy = dates[2];
                 date = new DateTime(int.Parse(yy), int.Parse(mm), int.Parse(dd));
                 enter = date;
               enter=  enter.AddMinutes(Convert.ToDouble(enterT[1]));
               enter=  enter.AddHours(Convert.ToDouble(enterT[0]));
                 exit = date;
               exit =  exit.AddMinutes(Convert.ToDouble(exitT[1]));
               exit =  exit.AddHours(Convert.ToDouble(exitT[0]));
               wd = new WorkDay() { Enter = enter, ExitT = exit,Id=31 };
               // var pd = dbo.Workers.Single(p => p.Id == 31);
                dbo.WorkDays.InsertOnSubmit(wd);
                dbo.SubmitChanges();

             }
         }
    }
        private void DuplicateButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.SelectedCustomer == null)
            {
                MessageBox.Show("No customer selected. Please select one before adding charge information.");
                return;
            }

            WorkDay previousWorkDay = this._DB.WorkDay.Where(o => o.CustomerID == this.SelectedCustomer.CustomerID).OrderByDescending(o => o.Date).First();
            if (previousWorkDay == null) { previousWorkDay = new WorkDay(); }

            this.WorkDayTab.IsSelected = true;
            this.SelectedWorkDay = Charge.Clone(previousWorkDay);
        }
        public async Task<bool> UpdateWorkDay(WorkDay updateItem)
        {
            var weekItem = Weeks.FirstOrDefault(x => x.WeekNumber == updateItem.StartDateTime.GetIso8601WeekOfYear());
            if (weekItem == null)
                return false;

            var workdayItem = weekItem.WorkDays.FirstOrDefault(x => x.Id == updateItem.Id);
            if (workdayItem == null)
                return false;

            Weeks.Remove(weekItem);
            weekItem.WorkDays.Remove(workdayItem);
            weekItem.WorkDays.Add(updateItem);
            weekItem.WorkDays.BubbleSort();
            Weeks.Add(weekItem);
            Weeks.BubbleSort();

            Logging.LogInfo("UpdateWorkDay call to OutSystems");
            return await this.dataLayer.UpdateWorkDay(updateItem);
        }
        public async Task<bool> DeleteWorkDay(WorkDay workDay)
        {
            var weekItem = Weeks.FirstOrDefault(x => x.WeekNumber == workDay.StartDateTime.GetIso8601WeekOfYear());
            if (weekItem == null)
                return false;

            var workdayItem = weekItem.WorkDays.FirstOrDefault(x => x.Id == workDay.Id);
            if (workdayItem == null)
                return false;

            Weeks.Remove(weekItem);
            weekItem.WorkDays.Remove(workdayItem);
            if(weekItem.WorkDays.Any())
                Weeks.Add(weekItem);

            Insights.Track("DeleteWorkDay call to OutSystems");
            return await this.dataLayer.DeleteWorkDay(workDay);
        }
		private void AddOrUpdateWorkDayInWeeks(WorkDay workDay)
		{
			var week = Weeks.SingleOrDefault(x => x.WeekNumber == workDay.WeekNumber);
			if (week != null) {
				Weeks.Remove (week);
				var day = week.WorkDays.FirstOrDefault (x => x.StartDateTime.Date == workDay.StartDateTime.Date);
				if (day != null) {					
					week.WorkDays.Remove (day);		
				}

				week.WorkDays.Add (workDay);
			} else {
				week = new Week ();
				week.WorkDays.Add (workDay);
			}

			week.WorkDays.BubbleSort ();
			Weeks.Add (week);
			Weeks.BubbleSort ();
		}
 public InsertViewViewModel(WorkDay workDay, bool isUpdate)
 {
     this.IsUpdate = isUpdate;
     this.WorkDay = workDay;
     this.validateForm();
 }
Beispiel #48
0
 private void enter(string Unum, DateTime dateTime)
 {
     DataClassesDataContext dbo = new DataClassesDataContext();
         var u = dbo.Workers.Select(p => p.Id == int.Parse(Unum));
         if (Unum != null)
         {
             WorkDay wd = new WorkDay() { Enter = dateTime, ExitT = MinDate, Id = int.Parse(Unum) };
             dbo.WorkDays.InsertOnSubmit(wd);
         }
         else
         {
             Worker wr = new Worker() {  Salary = 28, Name = "anon" };
         }
         dbo.SubmitChanges();
         GridView1.DataBind();
 }
Beispiel #49
0
        public static WorkDay Clone(WorkDay day)
        {
            WorkDay newDay = new WorkDay();

            return Clone(day, newDay);
        }
 private DateTime GetTaskStartTime(TimeSpan actualWorkHours, WorkDay day)
 {
     var dayStartTime = new TimeSpan(_dayStart.Ticks + actualWorkHours.Ticks);
     var date = day.Date;
     return new DateTime(date.Ticks + dayStartTime.Ticks);
 }
        private PersonTask GetNextCustomTask(List<PersonTask> tasksWithTimeData, WorkDay day, TimeSpan actualWorkHours, PersonTask task)
        {
            var todayRemainingTime = day.WorkingHours.Subtract(actualWorkHours);
            var hoursForTask = task.Hours.Value;

            if (hoursForTask > todayRemainingTime)
            {
                var tomorrowTask = CloneTask(task);
                tomorrowTask.Hours = hoursForTask.Subtract(todayRemainingTime);
                tomorrowTask.StartTime = task.StartTime.Value.AddDays(1);
                tasksWithTimeData.Add(tomorrowTask);
                hoursForTask = todayRemainingTime;
                task.MultipleDays = true;
            }

            task.Hours = hoursForTask;
            task.StartTime = GetTaskStartTime(actualWorkHours, day);

            return task;
        }
 public void UpdateItem(WorkDay updateItem)
 {
     Weeks.FirstOrDefault(x => x.WeekNumber == updateItem.StartDateTime.GetIso8601WeekOfYear()).WorkDays.FirstOrDefault(y => y.StartDateTime == updateItem.StartDateTime).BreakTime = TimeSpan.FromHours(1);
 }
	private void detach_WorkDays(WorkDay entity)
	{
		this.SendPropertyChanging();
		entity.Worker = null;
	}
 //assigns task to an engineer in the given work day
 private void PopulateWorkDayWithEngineers(LeafTask task, WorkDay day)
 {
     foreach (Engineer e in task.AssignedEngineers)
     {
         if (!day.AssignedTasks.ContainsKey(e))
         {
             List<Task> tasks = new List<Task>();
             tasks.Add(task);
             day.AssignedTasks.Add(e, tasks);
         }
         else
         {
             day.AssignedTasks[e].Add(task);
         }
     }
 }
 partial void UpdateWorkDay(WorkDay instance);
        public async Task DeleteWorkDay(WorkDay workDay)
        {
            if (isOnline)
            {
                if (await data.DeleteWorkDay(workDay))
                {
                    await cache.DeleteWorkDay(workDay);
                    RemoveWorkDayFromWeeks(workDay);
                    //var unsyncedWorkDay = new UnsyncedWorkDay { WorkDay = workDay, Type = "delete" };
                    //await cache.StoreUnsyncedWorkDay(unsyncedWorkDay);
                }

                //return false, fail
            }
        }
Beispiel #57
0
    public void ParseRows()
    {
        for (int i = 0; i < 3; i++)
        {
            Row dateRow = Rows[1 + (i * 8)]; // First row is empty, then adds a week each iteration.
            Row scheduleHoursRow = Rows[2 + (i * 8)];
            Row activityRow = Rows[3 + (i * 8)];
            Row locationRow = Rows[4 + (i * 8)];
            Row scheduleTimesRow = Rows[5 + (i * 8)];
            Row commentsRow = Rows[6 + (i * 8)];

            int dayIndex = 1; // 0 is column names
            while (true)
            {
                var workDay = new WorkDay();
                String dateString = dateRow.cells[dayIndex].value;

                // Get the day of the week
                workDay.Day = workDay.enumDay(dateString);
                if (workDay.Day == WorkDay.DayEnum.INVALID)
                {
                    break;
                }

                // split the string "Tue 6/23"
                // and use the second part ['Tue', '6/23']
                String datePart = dateString.Split(' ')[1];
                workDay.Date = DateTime.Parse(datePart);

                workDay.Hours = float.Parse(scheduleHoursRow.cells[dayIndex].value.Replace(":", "."));
                workDay.Activity = activityRow.cells[dayIndex].value;
                workDay.Comments = commentsRow.cells[dayIndex].value;
                workDay.Location = workDay.ConvertLocation(locationRow.cells[dayIndex].value);


                String timeSpanPart = scheduleTimesRow.cells[dayIndex].value;
                String[] times = timeSpanPart.Split('-'); // split '2:00 AM-8:00 PM' on the '-'

                workDay.StartTime = times[0];
                workDay.EndTime = times.Length == 1 ? times[0] : times[1];

                if (workDay.Hours > 0)
                {
                    workDay.StartDateTime = DateTime.Parse(workDay.Date.ToShortDateString() + " " + workDay.StartTime);
                    workDay.EndDateTime = DateTime.Parse(workDay.Date.ToShortDateString() + " " + workDay.EndTime);
                }
                Schedule.Add(workDay);
                dayIndex++;
            }
        }
    }
        public async Task UpdateWorkDay(WorkDay workDay)
        {
            if (isOnline)
            {
                if (await data.UpdateWorkDay(workDay))
                {
                    await cache.StoreWorkDay(workDay);
					AddOrUpdateWorkDayInWeeks (workDay);
                    //var unsyncedWorkDay = new UnsyncedWorkDay { WorkDay = workDay, Type = "update" };
                    //await cache.StoreUnsyncedWorkDay(unsyncedWorkDay);
                }

                //return false, fail
            }
        }
        private PersonTask GetNextJiraTask(Queue<PersonTask> freeTasks, WorkDay day, TimeSpan actualWorkHours, TimeSpan remainingTime)
        {
            var task = freeTasks.Dequeue();
            var todayRemainingTime = day.WorkingHours.Subtract(actualWorkHours);
            var hoursForTask = GetTaskHours(remainingTime, freeTasks.Count);

            //if (task.Hours.HasValue)
            //    hoursForTask = task.Hours.Value;

            if (hoursForTask > todayRemainingTime)
            {
                var tomorrowTask = CloneTask(task);
                tomorrowTask.Hours = hoursForTask.Subtract(todayRemainingTime);
                hoursForTask = todayRemainingTime;
                freeTasks.Enqueue(tomorrowTask);
                task.MultipleDays = true;
            }

            task.Hours = hoursForTask;
            task.StartTime = GetTaskStartTime(actualWorkHours, day);

            return task;
        }
        //TODO Либо находить нужные клетки из таблицы, либо рассмотреть все варианты таблиц
        /// <summary>
        /// Парсит расписание из таблицы и возвращает список из рабочих дней с расписанием.
        /// ВАЖНО!!! Здесь индексы подобраны из тестового образца, так что могут не совпадать с реальными данными.
        /// </summary>
        /// <param name="filePath">Путь к таблице с расписанием.</param>
        public static List<WorkDay> Parse(string filePath)
        {
            // Список будней, куда будем сохранять расписание
            List<WorkDay> schedule = new List<WorkDay>();

            // Создаем файловый поток из нашего файла.
            FileStream scheduleDoc = new FileStream(filePath, FileMode.Open);

            // "Распаковываем" таблицу.
            using (ExcelPackage package = new ExcelPackage(scheduleDoc))
            {
                // Извлекаем оттуда рабочую книгу и рабочую таблицу.
                ExcelWorkbook scheduleWorkbook = package.Workbook;
                ExcelWorksheets scheduleWorksheets = scheduleWorkbook.Worksheets;
                ExcelWorksheet sheet = scheduleWorksheets[1];

                // Разбиваем объединённые клетки, чтобы было проще обрабатывать их.
                BreakMergedCells(sheet);

                // Флаг, который сохраняет номер текущего дня
                int presentDay = -1;

                // Пробегаемся в цикле по всем строчкам
                // и сохраняем элементы таблицы в список рабочих дней.
                for (int i = 1; i < sheet.Dimension.Rows; i++)
                {
                    // Если есть название дня, если есть пара и это не "Самостоятельная работа",
                    // тогда обрабатываем это занятие.
                    if (GetIntNumberFromDayWeek(sheet.Cells[i,1].Text) != 0 &&
                        sheet.Cells[i,3].Text != "Самостоятельная работа" &&
                        !(string.IsNullOrWhiteSpace(sheet.Cells[i,3].Text)))
                    {
                        WorkDay tmp = new WorkDay();

                        // Если мы сменили день, значит это первая пара за этот день.
                        if (GetIntNumberFromDayWeek(sheet.Cells[i,1].Text) != presentDay
                            || (i != 1 && sheet.Cells[i,2].Text == sheet.Cells[i - 1,2].Text))
                        {
                            presentDay = GetIntNumberFromDayWeek(sheet.Cells[i,1].Text);
                            tmp.isFirstClassesOfADay = true;
                        }

                        // Сохраняем номер дня неделя
                        tmp.dayNumber = GetIntNumberFromDayWeek(sheet.Cells[i,1].Text);

                        // Разбиваем время на две строки (начало и конец пары),
                        // чтобы в дальнейшем было удобней использовать.
                        tmp.timeClassStart = TimeSpan.Parse(sheet.Cells[i,2].Text.Split('-')[0].Replace('.', ':'));
                        tmp.timeClassEnd = TimeSpan.Parse(sheet.Cells[i,2].Text.Split('-')[1].Replace('.', ':'));

                        // Выделяем из столбца названия предмета ТОЛЬКО название,
                        // отсекая цифру 2 (для предметов, идущих второй семестр),
                        // и отсекая имя преподавателя.
                        if (Regex.IsMatch(sheet.Cells[i,3].Text, @"\("))
                            tmp.nameSubject = sheet.Cells[i,3].Text.
                                Substring(0, Regex.Match(sheet.Cells[i,3].Text, @"\(").Index);
                        else
                            tmp.nameSubject = sheet.Cells[i,3].Text;

                        //Находим в названии предмета имя преподавателя и убираем оттуда скобки
                        tmp.nameLecturer = Regex.Match(sheet.Cells[i,3].Text, @"\([^0-9]+\)").
                            ToString().Replace("(", "").Replace(")", "");
                        tmp.typeClass = (sheet.Cells[i,8].Text == "л") ? "Лекция" : "Семинар";

                        // Разбиваем строку на целые значения - номера недель.
                        string repeatAt = sheet.Cells[i,9].Text;
                        foreach (string weekNumber in repeatAt.Split(','))
                        {
                            if (weekNumber.Contains("-"))
                            {
                                // Обрабатываем период недель С какой-то ПО какую-то.
                                string[] numberPeriod = weekNumber.Split('-');
                                for (int j = int.Parse(numberPeriod[0]); j <= int.Parse(numberPeriod[1]); j++)
                                {
                                    tmp.repeatAt.Add(j);
                                }
                            }
                            else
                            {
                                // Обрабатываем единичные недели.
                                tmp.repeatAt.Add(int.Parse(weekNumber));
                            }
                        }

                        tmp.place = sheet.Cells[i,10].Text;

                        schedule.Add(tmp);
                    }
                }
            }

            return schedule;
        }