private async Task <List <Workplace> > GetWorkplacesAsync() { using (var ctx = new DatabaseDir.Database()) { var lst = await Task.Run(() => ctx.Workplaces.Where(x => x.Archived == false).ToList()); return(lst); } }
public void BtnSaveEmployeeChanges() { using (var ctx = new DatabaseDir.Database()) { ctx.Employees.Attach(SelectedEmployee); ctx.Entry(SelectedEmployee).State = EntityState.Modified; ctx.SaveChanges(); new Notification(Notification.NotificationType.Edited, $"{SelectedEmployee.Fullname} er blevet opdateret i databasen."); } }
private async Task <List <Employee> > GetEmployeesAsync() { using (var ctx = new DatabaseDir.Database()) { List <Employee> employees = await Task.Run(() => ctx.Employees.Include(x => x.Routes.Select(k => k.LinkedWorkplace)).ToList()); employees = employees.OrderBy(p => p.IsFired).ToList(); return(employees); } }
public void BtnDeleteSelectedRoute() { Task.Run(() => { using (var ctx = new DatabaseDir.Database()) { ctx.Routes.Attach(SelectedRoute); ctx.Entry(SelectedRoute).State = EntityState.Deleted; ctx.SaveChanges(); new Notification(Notification.NotificationType.Removed, "Den valgte rute er blevet fjernet fra databasen."); SelectedEmployee.Routes.Remove(SelectedRoute); SelectedRoute = null; NotifyOfPropertyChange(() => RouteCollection); } }); }
public void BtnFireSelectedEmployee() { Task.Run(() => { using (var ctx = new DatabaseDir.Database()) { // Flip the fired status of the employee and update the database SelectedEmployee.IsFired = !SelectedEmployee.IsFired; ctx.Employees.Attach(SelectedEmployee); ctx.Entry(SelectedEmployee).State = EntityState.Modified; ctx.SaveChanges(); NotifyOfPropertyChange(() => TitleInformation); new Notification(Notification.NotificationType.Edited, $"{SelectedEmployee.Fullname} er blevet opdateret i databasen."); } }); }
public async Task BtnAddNewEmployee() { DialogResult employeeIdCheck = MessageBox.Show($"Kan det passe at løn nummeret er {NewEmployee.Id}?", "Bekræft løn nummer", MessageBoxButtons.YesNo); if (employeeIdCheck == DialogResult.No) { return; } using (var ctx = new DatabaseDir.Database()) { CanBtnAddNewEmployee = false; Cursor.Current = Cursors.WaitCursor; bool success = await Task <bool> .Run(() => { try { ctx.Employees.Add(NewEmployee); ctx.SaveChanges(); return(true); } catch (DbUpdateException ex) { // Should we log exceptions? return(false); } }); if (success) { new Notification(Notification.NotificationType.Added, $"{NewEmployee.Fullname} er blevet tilføjet til databasen."); NewEmployee = new Employee(); AllEmployees = await GetEmployeesAsync(); EmployeeCollection = new BindableCollection <Employee>(AllEmployees); } else { new Notification(Notification.NotificationType.Error, "Der skete en fejl. Tjek de indtastede informationer og prøv igen.", 7.5f); } CanBtnAddNewEmployee = true; Cursor.Current = Cursors.Default; } }
private void PrepareStatisticsBox() { Task.Run(() => { using (var ctx = new DatabaseDir.Database()) { List <TimesheetEntry> timesheetEntries = ctx.TimesheetEntries. Include(x => x.vismaEntries.Select(p => p.LinkedRate)).ToList(). Where(x => x.Date.Year == DateTime.Now.Year && x.EmployeeID == SelectedEmployee.Id). ToList(); TotalHoursForThisYear = timesheetEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "Normal").Sum(k => k.Value)); double averageHours = TotalHoursForThisYear / DateHelper.GetWeekNumber(DateTime.Now); AverageHoursPerWeek = Math.Round(averageHours, 2, MidpointRounding.AwayFromZero); NumberOfSickHours = timesheetEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "Sygdom").Sum(k => k.Value)); } }); }
public void BtnAddNewRoute() { if (NewRoute.Distance < 1) { new Notification(Notification.NotificationType.Error, "Distancen kan ikke være mindre end 1"); return; } Task.Run(() => { // Make sure the entered rate value is valid compared to the distance double calculatedRate = (NewRoute.LinkedWorkplace.MaxPayout / NewRoute.Distance); bool isValid = (calculatedRate <= StateRouteRate); if (!isValid) { new Notification(Notification.NotificationType.Error, $"Satsen {calculatedRate},- DKK/km overskrider statens takst {StateRouteRate},- DDK/km"); NewRoute.RateValue = StateRouteRate; } else { NewRoute.RateValue = calculatedRate; } using (var ctx = new DatabaseDir.Database()) { ctx.Routes.Add(NewRoute); ctx.Entry(NewRoute.LinkedWorkplace).State = EntityState.Detached; ctx.SaveChanges(); // Reload the virtual property again. ctx.Entry(NewRoute).Reference(c => c.LinkedWorkplace).Load(); SelectedEmployee.Routes.Add(NewRoute); NewRoute = new Route(); NewRoute.EmployeeID = SelectedEmployee.Id; new Notification(Notification.NotificationType.Added, $"Ruten er blevet tilføjet i databasen."); SelectedWorkplace = null; NotifyOfPropertyChange(() => RouteCollection); } }); }
public void BtnDeleteSelectedEntry() { //Check if found if (EntriesCollection.Where(x => x.ID == SelectedEntry.ID).Count() == 0) { return; } //Find the entryrow EntryRow entryRow = EntriesCollection.FirstOrDefault(x => x.ID == SelectedEntry.ID); //Delete from datagrid EntriesCollection.Remove(entryRow); NotifyOfPropertyChange(() => EntriesCollection); VismaEntry vismaEntry; //Delete vismaentry from database and its timesheetentry if it was the last vismaentry. using (var ctx = new DatabaseDir.Database()) { //Find the object in th database and delete vismaEntry = ctx.VismaEntries.Where(v => v.Id == SelectedEntry.ID).First(); ctx.VismaEntries.Remove(vismaEntry); ctx.SaveChanges(); } //Check and delete timesheetEntry if it no longer contains any vismaEntries using (var ctx = new DatabaseDir.Database()) { //Search for other vismaentries with the same timesheet id List <VismaEntry> list = new List <VismaEntry>(ctx.VismaEntries.Where(x => x.TimesheetEntryID == vismaEntry.TimesheetEntryID)); if (list.Count() == 0) { TimesheetEntry timesheetEntry = ctx.TimesheetEntries.FirstOrDefault(x => x.Id == vismaEntry.TimesheetEntryID); //If none, then delete ctx.TimesheetEntries.Remove(timesheetEntry); ctx.SaveChanges(); } } }
public async Task BtnAddNewWorkplace() { if (NewWorkplace.MaxPayout <= 0) { new Notification(Notification.NotificationType.Error, "Max beløb kan ikke være lig 0"); return; } using (var ctx = new DatabaseDir.Database()) { CanAddNewWorkplace = false; bool success = await Task <bool> .Run(() => { try { ctx.Workplaces.Add(NewWorkplace); ctx.SaveChanges(); return(true); } catch (Exception ex) { // Should we log exceptions? return(false); } }); if (success) { new Notification(Notification.NotificationType.Added, $"{NewWorkplace.Name} er blevet tilføjet til databasen."); NewWorkplace = new Workplace(); AllWorkplaces = await GetWorkplacesAsync(); WorkplaceCollection = new BindableCollection <Workplace>(AllWorkplaces); } CanAddNewWorkplace = true; } }
public void BtnExport() { List <TimesheetEntry> TimesheetEntries = new List <TimesheetEntry>(); //Convert input to DateTime for comparison with Entry DateTime fromValue = DateHelper.WeekNumToDateTime(SelectedFromWeek, SelectedFromYear, 0); DateTime toValue = DateHelper.WeekNumToDateTime(SelectedToWeek, SelectedToYear, 6); //Rows for normal and sick List <Row> normalRows = new List <Row>(); List <Row> sickRows = new List <Row>(); //Find the timesheet entries and their vismaentries and their linked rates using (var ctx = new DatabaseDir.Database()) TimesheetEntries = ctx.TimesheetEntries.Include(p => p.vismaEntries.Select(k => k.LinkedRate)).Where(ts => ts.Date >= fromValue && ts.Date <= toValue).ToList(); //Split and convert every vismaentry to a row by type. foreach (TimesheetEntry tse in TimesheetEntries) { foreach (VismaEntry ve in tse.vismaEntries) { if (!(ve.LinkedRate.Type == "Feriefri")) { if (SelectedTypes.Contains(ve.LinkedRate.Type)) { sickRows.Add(new Row(tse, ve, true)); } else { normalRows.Add(new Row(tse, ve, false)); } } } } //Export and check for error Export(normalRows, FileName, FilePath); Export(sickRows, FileName + "Syg", FilePath); }
public void BtnDeleteSelectedWorkplace() { //If not found if (WorkplaceCollection.Where(x => x == SelectedWorkplace).Count() == 0) { return; } //Find the entryrow Workplace workplace = WorkplaceCollection.FirstOrDefault(x => x == SelectedWorkplace); //Delete from datagrid WorkplaceCollection.Remove(workplace); NotifyOfPropertyChange(() => WorkplaceCollection); // Archives the selected workplace using (var ctx = new DatabaseDir.Database()) { ctx.Workplaces.First(x => x.Id == workplace.Id).Archived = true; ctx.SaveChanges(); } }
public void BtnSearchForEntries() { // 1: Get all TimesheetEntries based on selected week, year and employee // 2: Query for all VismaEntries linked to the TimesheetEntries // 3: Query for all Rates linked to the VismaEntries // 4: Format all the data into a new bindablecollection to display on the table System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; using (var ctx = new DatabaseDir.Database()) { List <TimesheetEntry> entries = ctx.TimesheetEntries.Include(k => k.vismaEntries.Select(p => p.LinkedRate)).ToList().Where(x => DateHelper.GetWeekNumber(x.Date) == SelectedWeek && x.Date.Year == SelectedYear).ToList(); List <EntryRow> entriesFormatted = new List <EntryRow>(); foreach (TimesheetEntry ts in entries) { foreach (VismaEntry visma in ts.vismaEntries) { entriesFormatted.Add(new EntryRow( ts.Date.ToString("dd/MM/yyyy"), ts.StartTime.ToString("HH:mm"), ts.EndTime.ToString("HH:mm"), visma.Value, visma.LinkedRate.Name, visma.LinkedRate.VismaID, visma.Comment, visma.LinkedRate.SaveAsMoney, visma.LinkedRate.StartTime == visma.LinkedRate.EndTime, visma.Id )); } } entriesFormatted = entriesFormatted.OrderBy(x => x.AsMoney).ThenBy(x => x.Date).ToList(); EntriesCollection = new BindableCollection <EntryRow>(entriesFormatted); } System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; }
private async Task <List <SixtyDayRow> > GetSixtyDayDataAsync() { List <SixtyDayRow> lst = new List <SixtyDayRow>(); await Task.Run(() => { using (var ctx = new DatabaseDir.Database()) { // Query the database for all the timesheet entries belonging to this year. var data = ctx.TimesheetEntries.Include(p => p.LinkedWorkplace).Where(x => x.EmployeeID == SelectedEmployee.Id).ToList(); // Loop through the timesheet entries and figure out which row and column it belongs to. foreach (var ent in data) { bool droveToWorkplace = ent.vismaEntries.FirstOrDefault(x => x.LinkedRate.Name == "Kørsel") != null; if (!droveToWorkplace) { continue; } // Check the rows for any existing workplace. SixtyDayRow sixHolder = lst.FirstOrDefault(x => x.WorkplaceID == ent.LinkedWorkplace.Id && x.Year == ent.Date.Year); // If there's no workplace added for this year, instantiate a new row. if (sixHolder == null) { sixHolder = new SixtyDayRow(ent.LinkedWorkplace.Name, (int)ent.WorkplaceID, ent.Date.Year); } // Calculate the index for the timesheet entry. int index; int week = DateHelper.GetWeekNumber(ent.Date); if (week % 2 == 0) { index = (week / 2); } else { index = (week - 1) / 2; } // In case the month is january, and week is either 52 or 53, // we'll manually set the index to the first column. if (ent.Date.Month == 1 && (week == 52 || week == 53)) { index = 0; } // Increment the value for the column at the calculated index. sixHolder.WeekValues[index] += 1; // Add the row to the list if it doesn't if (!lst.Contains(sixHolder)) { lst.Add(sixHolder); } // Increment the sum for the year sixHolder.TotalForTheYear += 1; // If it exceeds the 60 days, the columns color will become red. if (sixHolder.TotalForTheYear > CommonValuesRepository.SixtyDayThreshold) { new Notification(Notification.NotificationType.Warning, $"60-dags reglen er overskredet på arbejdsplads {sixHolder.Title} for {SelectedEmployee.Fullname}.", 60); } } } }); return(lst); }
public EmployeeProfileViewModel(Employee emp) { SelectedEmployee = emp; // Instantiate the new route and set the foreignkey value to the, // currently selected employee. NewRoute = new Route(); NewRoute.EmployeeID = SelectedEmployee.Id; // Get all the workplaces from the database and store them. Task.Run(async() => { var workplaces = await GetWorkplacesAsync(); Workplaces = new BindableCollection <Workplace>(workplaces); }); // Find the active collective agreement from the database, // and pull the rate containing the rate for routes determined by the state. using (var ctx = new DatabaseDir.Database()) { var routeRate = ctx.CollectiveAgreements.Include(r => r.Rates).FirstOrDefault(x => x.IsActive).Rates.FirstOrDefault(k => k.Type.Equals("Kørsel")); if (routeRate != null) { NewRoute.RateValue = StateRouteRate = routeRate.RateValue; } } Task.Run(async() => { _sixtyDayHolders = await GetSixtyDayDataAsync(); NotifyOfPropertyChange(() => SixtyDayCollection); }); // 1: Get all TimesheetEntries and the projectID // 2: Query for all VismaEntries linked to the TimesheetEntries // 3: Format all the data into a new bindablecollection to display on the table using (var ctx = new DatabaseDir.Database()) { List <TimesheetEntry> entries = ctx.TimesheetEntries.Include(k => k.vismaEntries.Select(p => p.LinkedRate)).Where(x => x.EmployeeID == SelectedEmployee.Id).ToList(); foreach (TimesheetEntry ts in entries) { VismaEntry visma = ts.vismaEntries.FirstOrDefault(x => x.LinkedRate.Name == "Normal"); if (visma != null) { ProjectFormat pf = _allProjects.FirstOrDefault(k => k.ProjectID == ts.ProjectID); if (pf == null) { pf = new ProjectFormat(ts.ProjectID); } pf.Hours += visma.Value; if (!_allProjects.Contains(pf)) { _allProjects.Add(pf); } } } ProjectCollection = new BindableCollection <ProjectFormat>(_allProjects); } // Calculate the current week, deduct one from it and afterwards get the current year. // Set the boxes for timesheets searching to automatically use these when the page starts. DateTime currentDate = DateTime.Now; SelectedWeek = DateHelper.GetWeekNumber(currentDate) - 1; SelectedYear = currentDate.Year; // Then do a search for entries. BtnSearchForEntries(); using (var ctx = new DatabaseDir.Database()) { // Get all timesheets for this year including the vismaentries. List <TimesheetEntry> allEntries = ctx.TimesheetEntries.Include(k => k.vismaEntries.Select(p => p.LinkedRate)). Where(x => x.EmployeeID == SelectedEmployee.Id && x.Date.Year == DateTime.Now.Year).ToList(); OverviewRow totalRow = new OverviewRow("SALDO"); // Loop through all the rows in the datagrid. for (int i = 0; i < 27; i++) { // Find the name of the row. string rowName = ""; if (i > 0) { string prefix = ((i * 2) < 10) ? "0" : ""; rowName = $"{prefix}{i * 2}-{prefix}{(i * 2) + 1}"; } else { rowName = "52/53-01"; } OverviewRow row = new OverviewRow(rowName); OverviewRow previousRow = null; if (i > 0) { previousRow = _overviewCollection[i - 1]; } // Get the timesheet entries belonging to this row. List <TimesheetEntry> tempEntries = allEntries.Where(x => DateHelper.GetWeekNumber(x.Date) == i * 2 || DateHelper.GetWeekNumber(x.Date) == (i * 2) + 1).ToList(); // Column "Afspadsering IND" row.ColumnValues[0] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "Afspadsering (ind)").ToList().Sum(k => k.Value)); totalRow.ColumnValues[0] += row.ColumnValues[0]; // Column "Afspadsering UD" row.ColumnValues[1] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "Afspadsering (ud)").ToList().Sum(k => k.Value)); totalRow.ColumnValues[1] += row.ColumnValues[1]; // Column "Afspadsering SALDO" // Row 0 needs to get the value from the previous year row.ColumnValues[2] = (previousRow == null ? 0 : (previousRow.ColumnValues[2] + row.ColumnValues[0] - row.ColumnValues[1])); totalRow.ColumnValues[2] += row.ColumnValues[2]; // Column "Feriefri UD" row.ColumnValues[3] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Type == "Feriefri").ToList().Sum(k => k.Value)); totalRow.ColumnValues[3] += row.ColumnValues[3]; // Column "Feriefri SALDO" row.ColumnValues[4] = (previousRow == null ? 37 - row.ColumnValues[3] : previousRow.ColumnValues[4] - row.ColumnValues[3]); totalRow.ColumnValues[4] = row.ColumnValues[4]; // Column "Ferie UD" row.ColumnValues[5] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Type == "Ferie").ToList().Sum(k => k.Value)); totalRow.ColumnValues[5] += row.ColumnValues[5]; // Ferie SALDO // Row 0 needs to get value from the previous year row.ColumnValues[6] = (previousRow == null ? 0 : previousRow.ColumnValues[6] - row.ColumnValues[5]); totalRow.ColumnValues[6] += row.ColumnValues[6]; // Column "Sygdom" row.ColumnValues[7] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "Sygdom").ToList().Sum(k => k.Value)); totalRow.ColumnValues[7] += row.ColumnValues[7]; // Column "Timer" row.ColumnValues[8] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "Normal").ToList().Sum(k => k.Value)); totalRow.ColumnValues[8] += row.ColumnValues[8]; // Column "Tillæg 1. og 2. time" row.ColumnValues[9] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "1. + 2.timers overarbejde").ToList().Sum(k => k.Value)); totalRow.ColumnValues[9] += row.ColumnValues[9]; // Column "Tillæg 3. og 4. time" row.ColumnValues[10] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Name == "3 + 4. times overarbejde").ToList().Sum(k => k.Value)); totalRow.ColumnValues[10] += row.ColumnValues[10]; // Column "Diæt" row.ColumnValues[11] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Type == "Diæt").ToList().Sum(k => k.Value)); totalRow.ColumnValues[11] += row.ColumnValues[11]; // Column "Skattefri 1 KM" row.ColumnValues[12] = (float)tempEntries.Sum(x => x.vismaEntries.Where(p => p.LinkedRate.Type == "Kørsel").ToList().Sum(k => (k.Value / k.RateValue))); totalRow.ColumnValues[12] += row.ColumnValues[12]; _overviewCollection.Add(row); } _overviewCollection.Add(totalRow); if (totalRow.ColumnValues[12] > CommonValuesRepository.TwentyThousindThreshold) { new Notification(Notification.NotificationType.Warning, $"20 tusind kilometer reglen er overskredet for {SelectedEmployee.Fullname}.", 60); } } NotifyOfPropertyChange(() => OverviewCollection); // Prepare data for the statistics box PrepareStatisticsBox(); }
private async Task GetProjectsAsync() { List <TimesheetEntry> timesheetEntries; ShownProjectsCollection.Clear(); AllProjects.Clear(); //Get all entries with a project ID using (var ctx = new DatabaseDir.Database()) //Get entries timesheetEntries = ctx.TimesheetEntries.Include(ts => ts.vismaEntries.Select(ve => ve.LinkedRate)).ToList(); //Convert to projects foreach (TimesheetEntry timesheetEntry in timesheetEntries) { //Filter empty project IDs if (string.IsNullOrWhiteSpace(timesheetEntry.ProjectID)) { continue; } //Filter timesheets with no "Arbejde" types if (timesheetEntry.vismaEntries.Where(x => x.LinkedRate.Type == "Arbejde").ToList().Count() == 0) { continue; } //Filter if a period is specified if (SelectedWeek > 0 && SelectedYear > 0) { DateTime from = DateHelper.WeekNumToDateTime(SelectedWeek, SelectedYear, 0); DateTime to = DateHelper.WeekNumToDateTime(SelectedWeek, SelectedYear, 6); if (timesheetEntry.Date < from || timesheetEntry.Date > to) { continue; //Then skip } } //Initalize double normalHours = 0; double overtimeHours = 0; //Sum up hours from the entry foreach (VismaEntry vismaEntry in timesheetEntry.vismaEntries) { //Filter non "Arbejde" (work) types if (vismaEntry.LinkedRate.Type != "Arbejde") { continue; } //Sum overtime hours if (vismaEntry.LinkedRate.Name == "Normal") { if (vismaEntry.Value > 0) { normalHours += vismaEntry.Value; } } else { overtimeHours += vismaEntry.Value; } } //Add time to project if (!AllProjects.Where(p => p.ProjectID == timesheetEntry.ProjectID).ToList().Any()) { //If project is not already listed AllProjects.Add(new Project(timesheetEntry.ProjectID, normalHours, overtimeHours)); } else { //Else add hours to existing Project SelectedProject = AllProjects.Where(p => p.ProjectID == timesheetEntry.ProjectID).FirstOrDefault(); SelectedProject.TotalNormalHours += normalHours; SelectedProject.TotalOverTimeHours += overtimeHours; } } AllProjects.Sort((x, y) => string.Compare(x.ProjectID, y.ProjectID)); FiltherProjects(); }