Compare commits

...

3 Commits

Author SHA1 Message Date
Mikan
637b7ff815 update 2025-05-23 19:20:57 +03:00
Mikan
32a16c9954 update 2025-05-22 21:15:36 +03:00
Mikan
004e3901f2 base auth 2025-05-22 20:26:15 +03:00
31 changed files with 2033 additions and 17 deletions

View File

@@ -2,8 +2,43 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:OfficeFlow"
xmlns:converters="clr-namespace:OfficeFlow.Utils.Converters"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<!-- Регистрация конвертера -->
<converters:CountConverter x:Key="CountConverter"/>
<converters:DateConverter x:Key="DateConverter"/>
<converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter"/>
<!-- Определение стиля для кнопки -->
<Style x:Key="AccentButtonStyle" TargetType="Button">
<Setter Property="Background" Value="#4CAF50" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Padding" Value="10,5" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Background="{TemplateBinding Background}"
CornerRadius="5"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#43A047" />
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>

View File

@@ -1,17 +1,8 @@
using System;
using System.Collections.Generic;
using OfficeFlow.Pages;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow
{
@@ -28,6 +19,10 @@ namespace OfficeFlow
{
MainFrame.Navigate(new Pages.StartupPages.InitializeDataPage());
}
else
{
MainFrame.Navigate(new MainPage());
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeFlow.Models
{
public partial class Employee
{
public User User
{
get
{
return this.User_Employee.FirstOrDefault()?.User;
}
set
{
var userEmployee = this.User_Employee.FirstOrDefault();
if (userEmployee == null)
{
userEmployee = new User_Employee
{
Employee = this,
};
App.Entities.User_Employee.Add(userEmployee);
}
userEmployee.User = value;
}
}
}
}

View File

@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeFlow.Models
{
public partial class User
{
public Role Role {
get
{
return this.User_Role.FirstOrDefault()?.Role;
}
set
{
var userRole = this.User_Role.FirstOrDefault();
if (userRole == null)
{
userRole = new User_Role {
User = this,
};
App.Entities.User_Role.Add(userRole);
}
userRole.Role = value;
}
}
public Employee Employee
{
get
{
return this.User_Employee.FirstOrDefault()?.Employee;
}
set
{
var userEmployee = this.User_Employee.FirstOrDefault();
if (userEmployee == null)
{
userEmployee = new User_Employee
{
User = this,
};
App.Entities.User_Employee.Add(userEmployee);
}
userEmployee.Employee = value;
}
}
}
}

View File

@@ -64,6 +64,39 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="Models\Utils\Employee.cs" />
<Compile Include="Models\Utils\User.cs" />
<Compile Include="Pages\EmployeePages\CreateEmployeePage.xaml.cs">
<DependentUpon>CreateEmployeePage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\EmployeePages\CreateUserPage.xaml.cs">
<DependentUpon>CreateUserPage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\EmployeePages\EmployeesPage.xaml.cs">
<DependentUpon>EmployeesPage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\EmployeePages\EmployeesPositionsPage.xaml.cs">
<DependentUpon>EmployeesPositionsPage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\EmployeePages\LinkUserPage.xaml.cs">
<DependentUpon>LinkUserPage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\EmployeePages\NewEmployeePage.xaml.cs">
<DependentUpon>NewEmployeePage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\EmployeePages\NewUserPage.xaml.cs">
<DependentUpon>NewUserPage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\LoginPage.xaml.cs">
<DependentUpon>LoginPage.xaml</DependentUpon>
</Compile>
<Compile Include="Pages\MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="Utils\Converters\CountConverter.cs" />
<Compile Include="Utils\Converters\DateConverter.cs" />
<Compile Include="Utils\Converters\NullToVisibilityConverter.cs" />
<Compile Include="Utils\Session.cs" />
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
@@ -76,6 +109,42 @@
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Page Include="Pages\EmployeePages\CreateEmployeePage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\EmployeePages\CreateUserPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\EmployeePages\EmployeesPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\EmployeePages\EmployeesPositionsPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\EmployeePages\LinkUserPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\EmployeePages\NewEmployeePage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\EmployeePages\NewUserPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\LoginPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\MainPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Pages\StartupPages\CreateAdministratorPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>

View File

@@ -0,0 +1,51 @@
<Page x:Class="OfficeFlow.Pages.EmployeePages.CreateEmployeePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages.EmployeePages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Создать сотрудника">
<Grid Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Заголовок -->
<TextBlock Text="Создать нового сотрудника" FontSize="20" FontWeight="Bold" Margin="0,0,0,20"/>
<!-- ФИО -->
<StackPanel Grid.Row="1" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="ФИО:" FontSize="16"/>
<TextBox x:Name="TBFullName" Width="300" Height="30"/>
</StackPanel>
<!-- Должность -->
<StackPanel Grid.Row="2" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Должность:" FontSize="16"/>
<ComboBox x:Name="CBPositions" DisplayMemberPath="PositionName" Width="300" Height="30"/>
</StackPanel>
<!-- Контактная информация -->
<StackPanel Grid.Row="3" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Контактная информация:" FontSize="16"/>
<TextBox x:Name="TBContactInfo" Width="300" Height="30"/>
</StackPanel>
<!-- Кнопки -->
<StackPanel Grid.Row="5" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="Отмена" Width="100" Height="30" Margin="0,0,10,0" Click="Cancel_Click" IsCancel="True"/>
<Button Content="Создать" Width="100" Height="30" Click="CreateEmployee_Click" Style="{StaticResource AccentButtonStyle}"/>
</StackPanel>
</Grid>
</Page>

View File

@@ -0,0 +1,86 @@
using OfficeFlow.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages.EmployeePages
{
/// <summary>
/// Interaction logic for CreateEmployee.xaml
/// </summary>
public partial class CreateEmployeePage : Page
{
public CreateEmployeePage()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
// Загружаем должности
var positions = App.Entities.Positions.ToList();
CBPositions.ItemsSource = positions;
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
private void CreateEmployee_Click(object sender, RoutedEventArgs e)
{
string fullName = TBFullName.Text.Trim();
Position position = CBPositions.SelectedValue as Position;
string contactInfo = TBContactInfo.Text.Trim();
if (string.IsNullOrEmpty(fullName) || position == null)
{
MessageBox.Show("Заполните все обязательные поля.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
using (var transaction = App.Entities.Database.BeginTransaction())
{
try
{
// Создаем нового сотрудника
var newEmployee = new Employee
{
FullName = fullName,
ContactInfo = string.IsNullOrEmpty(contactInfo) ? null : contactInfo,
Position = position,
EmployeeStatus = App.Entities.EmployeeStatuses.Where(es => es.StatusName == "Работает").FirstOrDefault(),
};
App.Entities.Employees.Add(newEmployee);
App.Entities.SaveChanges();
transaction.Commit();
MessageBox.Show("Сотрудник успешно создан.", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
NavigationService.GoBack();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show($"Ошибка при создании сотрудника: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
}

View File

@@ -0,0 +1,55 @@
<Page x:Class="OfficeFlow.Pages.EmployeePages.CreateUserPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages.EmployeePages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Создать пользователя">
<Grid Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Заголовок -->
<TextBlock Text="Создать нового пользователя" FontSize="20" FontWeight="Bold" Margin="0,0,0,20"/>
<!-- Логин -->
<StackPanel Grid.Row="1" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Логин:" FontSize="16"/>
<TextBox x:Name="TBLLogin" Width="300" Height="30"/>
</StackPanel>
<!-- Пароль -->
<StackPanel Grid.Row="2" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Пароль:" FontSize="16"/>
<PasswordBox x:Name="PBPassword" Width="300" Height="30"/>
</StackPanel>
<!-- Email -->
<StackPanel Grid.Row="3" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Email:" FontSize="16"/>
<TextBox x:Name="TBLEmail" Width="300" Height="30"/>
</StackPanel>
<!-- Роль -->
<StackPanel Grid.Row="4" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Роль:" FontSize="16"/>
<ComboBox x:Name="CBRoles" DisplayMemberPath="RoleName" SelectedValuePath="RoleID" Width="300" Height="30"/>
</StackPanel>
<!-- Кнопки -->
<StackPanel Grid.Row="5" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="Отмена" Width="100" Height="30" Margin="0,0,10,0" Click="Cancel_Click" IsCancel="True"/>
<Button Content="Создать" Width="100" Height="30" Click="CreateUser_Click" Style="{StaticResource AccentButtonStyle}"/>
</StackPanel>
</Grid>
</Page>

View File

@@ -0,0 +1,94 @@
using OfficeFlow.Models;
using OfficeFlow.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages.EmployeePages
{
/// <summary>
/// Interaction logic for CreateUserPage.xaml
/// </summary>
public partial class CreateUserPage : Page
{
private Employee _employee;
public CreateUserPage(Employee employee)
{
InitializeComponent();
_employee = employee ?? throw new ArgumentNullException(nameof(employee));
LoadRoles();
}
private void LoadRoles()
{
// Загружаем все доступные роли
var roles = App.Entities.Roles.ToList();
CBRoles.ItemsSource = roles;
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
private void CreateUser_Click(object sender, RoutedEventArgs e)
{
string login = TBLLogin.Text.Trim();
string password = PBPassword.Password.Trim();
string email = TBLEmail.Text.Trim();
var selectedRole = CBRoles.SelectedItem as Role;
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || selectedRole == null)
{
MessageBox.Show("Заполните все поля и выберите роль.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
email = String.IsNullOrWhiteSpace(email) ? null : email;
using (var transaction = App.Entities.Database.BeginTransaction())
{
try
{
// Создаем нового пользователя
var newUser = Session.CreateUser(
login,
password,
selectedRole,
email
);
newUser.Employee = _employee;
App.Entities.SaveChanges();
transaction.Commit();
MessageBox.Show("Пользователь успешно создан.", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
NavigationService.GoBack();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show($"Ошибка при создании пользователя: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
}

View File

@@ -0,0 +1,69 @@
<Page x:Class="OfficeFlow.Pages.EmployeePages.EmployeesPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages.EmployeePages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Сотрудники" Loaded="Page_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<DataGrid x:Name="DGData" AutoGenerateColumns="False" CellEditEnding="DGData_CellEditEnding" PreviewKeyDown="DGData_PreviewKeyDown">
<DataGrid.Columns>
<DataGridTextColumn Header="ФИО" Binding="{Binding FullName, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridComboBoxColumn
Header="Должность"
SelectedValueBinding="{Binding PositionID, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="PositionName"
SelectedValuePath="PositionID"
x:Name="DGCBPosition"
/>
<DataGridTextColumn Header="Контактная информация" Binding="{Binding ContactInfo, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn
Header="Дата приёма на работу"
Binding="{Binding HireDate, Converter={StaticResource DateConverter}, UpdateSourceTrigger=PropertyChanged}"
/>
<DataGridComboBoxColumn
Header="Статус"
SelectedValueBinding="{Binding EmployeeStatus, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="StatusName"
x:Name="DGCBStatus"
/>
<DataGridTextColumn
Header="Логин пользователя"
Binding="{Binding User.Login}"
IsReadOnly="True"/>
<!-- Столбец с кнопкой "Создать учётную запись" -->
<DataGridTemplateColumn Header="Действия">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<!-- Кнопка "Создать учётную запись" -->
<Button
Content="Создать учётную запись"
Visibility="{Binding User, Converter={StaticResource NullToVisibilityConverter}}"
Click="CreateAccount_Click" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<StackPanel Grid.Row="1">
<Button x:Name="BNew" Content="Добавить" Style="{StaticResource AccentButtonStyle}" Click="BNew_Click"/>
<Button x:Name="BBack" Content="Назад" Click="BBack_Click"/>
</StackPanel>
</Grid>
</Page>

View File

@@ -0,0 +1,176 @@
using OfficeFlow.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages.EmployeePages
{
/// <summary>
/// Interaction logic for EmployeesPage.xaml
/// </summary>
public partial class EmployeesPage : Page
{
public EmployeesPage()
{
InitializeComponent();
DGCBPosition.ItemsSource = App.Entities.Positions.ToList();
DGCBStatus.ItemsSource = App.Entities.EmployeeStatuses.ToList();
}
private void Refresh()
{
DGData.ItemsSource = new ObservableCollection<Employee>(App.Entities.Employees.ToList());
}
private void BBack_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
private void DGData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction != DataGridEditAction.Commit)
{
return;
}
if (e.Row.Item is Employee newPosition)
{
using (var transaction = App.Entities.Database.BeginTransaction())
{
try
{
Employee employee = App.Entities.Employees.Find(newPosition.EmployeeID);
if (employee == null)
{
employee = new Employee();
App.Entities.Employees.Add(employee);
}
employee.FullName = newPosition.FullName;
employee.Position = newPosition.Position;
employee.ContactInfo = newPosition.ContactInfo;
employee.HireDate = newPosition.HireDate;
employee.EmployeeStatus = newPosition.EmployeeStatus;
//employee.User
App.Entities.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(
"Ошибка при добавлении, проверьте данные!",
"Не удалось добавить данные в БД",
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
}
Refresh();
}
}
private void DGData_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Delete)
{
return;
}
var selectedPosition = DGData.SelectedItem as Employee;
// Получаем выбранную строку
if (selectedPosition == null || selectedPosition.EmployeeID == 0)
{
return;
}
var result = MessageBox.Show(
$"Вы уверены, что хотите удалить '{selectedPosition.FullName}'? Лучше заменить у него статус!",
"Подтверждение удаления",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result == MessageBoxResult.No)
{
return;
}
using (var transaction = App.Entities.Database.BeginTransaction())
{
try
{
App.Entities.Employees.Remove(selectedPosition);
App.Entities.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(
"Ошибка при удалении, проверьте данные!",
"Не удалось удалить данные из БД",
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
}
Refresh();
}
private void CreateAccount_Click(object sender, RoutedEventArgs e)
{
if (sender is Button button && button.DataContext is Employee employee)
{
// Передаем данные сотрудника на страницу LinkUser
NavigationService.Navigate(new LinkUserPage(employee));
}
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
Refresh();
}
private void BNew_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new CreateEmployeePage());
}
}
}

View File

@@ -0,0 +1,30 @@
<Page x:Class="OfficeFlow.Pages.EmployeePages.EmployeesPositionsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages.EmployeePages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Настройка должностей">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<DataGrid x:Name="DGData" AutoGenerateColumns="False" CellEditEnding="DGData_CellEditEnding" PreviewKeyDown="DGData_PreviewKeyDown">
<DataGrid.Columns>
<DataGridTextColumn Header="Название должности*" Binding="{Binding PositionName, UpdateSourceTrigger=PropertyChanged}"/>
<DataGridTextColumn Header="Описание" Binding="{Binding PositionDescription, UpdateSourceTrigger=PropertyChanged}" Width="auto"/>
<DataGridTextColumn
Header="Количество сотрудников"
Binding="{Binding Employees, Converter={StaticResource CountConverter}}"
IsReadOnly="True"
/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="BBack" Grid.Row="1" Content="Назад" Click="BBack_Click"/>
</Grid>
</Page>

View File

@@ -0,0 +1,167 @@
using OfficeFlow.Models;
using OfficeFlow.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages.EmployeePages
{
/// <summary>
/// Interaction logic for EmployeesPositionsPage.xaml
/// </summary>
public partial class EmployeesPositionsPage : Page
{
public EmployeesPositionsPage()
{
InitializeComponent();
Refresh();
}
private void Refresh()
{
DGData.ItemsSource = new ObservableCollection<Position>(App.Entities.Positions.ToList());
}
private void BBack_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
private void DGData_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction != DataGridEditAction.Commit)
{
return;
}
if (e.Row.Item is Position newPosition)
{
if (String.IsNullOrWhiteSpace(newPosition.PositionName))
{
MessageBox.Show(
"Необходимо сначала указать название",
"Неправильный порядок добавления данных",
MessageBoxButton.OK,
MessageBoxImage.Exclamation
);
return;
}
using (var transaction = App.Entities.Database.BeginTransaction())
{
try
{
Position position = App.Entities.Positions.Find(newPosition.PositionID);
if (position == null)
{
position = new Position();
App.Entities.Positions.Add(position);
}
position.PositionName = newPosition.PositionName;
position.PositionDescription = String.IsNullOrWhiteSpace(newPosition.PositionDescription)?null: newPosition.PositionDescription.Trim();
App.Entities.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(
"Ошибка при добавлении, проверьте данные!",
"Не удалось добавить данные в БД",
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
}
Refresh();
}
}
private void DGData_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Delete)
{
return;
}
var selectedPosition = DGData.SelectedItem as Position;
// Получаем выбранную строку
if (selectedPosition == null || selectedPosition.PositionID == 0)
{
return;
}
if (selectedPosition.Employees.Count() > 0)
{
MessageBox.Show(
"Некорретная операция!",
"Нельзя удалить пока есть работники с такой должностью",
MessageBoxButton.OK,
MessageBoxImage.Error
);
return;
}
var result = MessageBox.Show(
$"Вы уверены, что хотите удалить должность '{selectedPosition.PositionName}'?",
"Подтверждение удаления",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result == MessageBoxResult.No) {
return;
}
using (var transaction = App.Entities.Database.BeginTransaction())
{
try
{
App.Entities.Positions.Remove(selectedPosition);
App.Entities.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(
"Ошибка при удалении, проверьте данные!",
"Не удалось удалить данные из БД",
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
}
Refresh();
}
}
}

View File

@@ -0,0 +1,36 @@
<Page x:Class="OfficeFlow.Pages.EmployeePages.LinkUserPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages.EmployeePages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Связать пользователя" Loaded="Page_Loaded">
<Grid Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Заголовок -->
<TextBlock Text="Связать сотрудника с пользователем" FontSize="20" FontWeight="Bold" Margin="0,0,0,20"/>
<!-- Выбор пользователя -->
<StackPanel Grid.Row="1" Orientation="Vertical">
<TextBlock Text="Выберите пользователя:" FontSize="16" Margin="0,0,0,10"/>
<ComboBox x:Name="CBUsers" DisplayMemberPath="Login" SelectedValuePath="UserID" Margin="0,0,0,20" Width="300"/>
<!-- Кнопка "Создать нового пользователя" -->
<Button Content="Создать нового пользователя" Width="200" Height="30" Click="CreateNewUser_Click" HorizontalAlignment="Left"/>
</StackPanel>
<!-- Кнопка "Связать" -->
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="Отмена" Width="100" Height="30" Margin="0,0,10,0" Click="Cancel_Click" IsCancel="True"/>
<Button Content="Связать" Width="100" Height="30" Click="LinkUser_Click"/>
</StackPanel>
</Grid>
</Page>

View File

@@ -0,0 +1,98 @@
using OfficeFlow.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages.EmployeePages
{
/// <summary>
/// Interaction logic for LinkUserPage.xaml
/// </summary>
public partial class LinkUserPage : Page
{
private Employee _employee;
public LinkUserPage(Employee employee)
{
InitializeComponent();
_employee = employee ?? throw new ArgumentNullException(nameof(employee));
LoadAvailableUsers();
}
private void LoadAvailableUsers()
{
// Загружаем пользователей, у которых нет связанного сотрудника
var availableUsers = App.Entities.Users
.Where(u => u.User_Employee.Count() == 0)
.ToList();
CBUsers.ItemsSource = availableUsers;
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
}
private void CreateNewUser_Click(object sender, RoutedEventArgs e)
{
// Переход на страницу создания нового пользователя
NavigationService.Navigate(new CreateUserPage(_employee));
}
private void LinkUser_Click(object sender, RoutedEventArgs e)
{
if (CBUsers.SelectedItem is User selectedUser)
{
using (var transaction = App.Entities.Database.BeginTransaction())
{
try
{
// Находим сотрудника и связываем его с выбранным пользователем
var employee = App.Entities.Employees.Find(_employee.EmployeeID);
if (employee != null)
{
employee.User = selectedUser;
App.Entities.SaveChanges();
transaction.Commit();
}
MessageBox.Show("Пользователь успешно связан.", "Успех", MessageBoxButton.OK, MessageBoxImage.Information);
NavigationService.GoBack();
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show($"Ошибка при связывании пользователя: {ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
else
{
MessageBox.Show("Выберите пользователя из списка.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
if (_employee.User != null)
{
NavigationService.GoBack();
}
}
}
}

View File

@@ -0,0 +1,14 @@
<Page x:Class="OfficeFlow.Pages.EmployeePages.NewEmployeePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages.EmployeePages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="NewEmployeePage">
<Grid>
</Grid>
</Page>

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages.EmployeePages
{
/// <summary>
/// Interaction logic for NewEmployeePage.xaml
/// </summary>
public partial class NewEmployeePage : Page
{
public NewEmployeePage()
{
InitializeComponent();
}
}
}

View File

@@ -0,0 +1,14 @@
<Page x:Class="OfficeFlow.Pages.EmployeePages.NewUserPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages.EmployeePages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="NewUserPage">
<Grid>
</Grid>
</Page>

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages.EmployeePages
{
/// <summary>
/// Interaction logic for NewUserPage.xaml
/// </summary>
public partial class NewUserPage : Page
{
public NewUserPage()
{
InitializeComponent();
}
}
}

View File

@@ -0,0 +1,46 @@
<Page x:Class="OfficeFlow.Pages.LoginPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Вход в систему">
<Grid Margin="10">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Заголовок -->
<TextBlock Text="Вход в систему" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" Margin="0,0,0,20"/>
<!-- Логин -->
<StackPanel Grid.Row="1" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Логин:" FontSize="14" Margin="0,0,0,5"/>
<TextBox x:Name="LoginTextBox" Height="30" VerticalContentAlignment="Center" Margin="0,0,0,10"/>
</StackPanel>
<!-- Пароль -->
<StackPanel Grid.Row="2" Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Пароль:" FontSize="14" Margin="0,0,0,5"/>
<PasswordBox x:Name="PasswordBox" Height="30" VerticalContentAlignment="Center" Margin="0,0,0,10"/>
</StackPanel>
<!-- Кнопка входа -->
<Button Grid.Row="3" Content="Войти" Width="100" Height="35" Click="LoginButton_Click" Background="#4CAF50" Foreground="White" HorizontalAlignment="Center"/>
<!-- Текст ошибки -->
<TextBlock x:Name="ErrorMessage" Grid.Row="4" Text="" Foreground="Red" FontSize="12" HorizontalAlignment="Center" Margin="0,10,0,0" Visibility="Collapsed"/>
</Grid>
</StackPanel>
</Grid>
</Page>

View File

@@ -0,0 +1,68 @@
using OfficeFlow.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages
{
/// <summary>
/// Interaction logic for LoginPage.xaml
/// </summary>
public partial class LoginPage : Page
{
public LoginPage()
{
InitializeComponent();
}
private void LoginButton_Click(object sender, RoutedEventArgs e)
{
try
{
Session.Authenticate(App.Entities.Users.FirstOrDefault());
}
finally
{
NavigationService.Navigate(new MainPage());
}
string login = LoginTextBox.Text.Trim();
string password = PasswordBox.Password;
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
ErrorMessage.Text = "Заполните все поля.";
ErrorMessage.Visibility = Visibility.Visible;
return;
}
try
{
Session.Authenticate(login, password);
NavigationService.Navigate(new MainPage());
}
catch (Exception)
{
ErrorMessage.Text = "Неверный логин или пароль.";
ErrorMessage.Visibility = Visibility.Visible;
}
}
}
}

View File

@@ -0,0 +1,55 @@
<Page x:Class="OfficeFlow.Pages.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OfficeFlow.Pages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="Главная" Loaded="Page_Loaded">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Header Section -->
<DockPanel Background="#2d3436" Height="60">
<StackPanel>
<Menu FontSize="14" x:Name="MainMenu">
<MenuItem Header="Справка">
<MenuItem Header="О программе" x:Name="MenuItemAbout" Click="MenuItemAbout_Click"/>
</MenuItem>
</Menu>
<TextBlock Text="OfficeFlow - Главная" Foreground="White" FontSize="20"
VerticalAlignment="Center" Margin="20,0,0,0"/>
</StackPanel>
</DockPanel>
<!-- Main Content -->
<StackPanel Grid.Row="1" Margin="20">
<TextBlock Text="Добро пожаловать в OfficeFlow!" FontSize="24" FontWeight="Bold" Margin="0,0,0,10"/>
<TextBlock Text="Здесь вы можете управлять данными об аренде, клиентах и услугах." FontSize="16" Margin="0,0,0,20"/>
<!-- Quick Access Buttons -->
<WrapPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="0,0,0,20">
<Button Content="Управление клиентами" Width="150" Height="40" Margin="5" Style="{StaticResource AccentButtonStyle}"/>
<Button Content="Управление помещениями" Width="150" Height="40" Margin="5" Style="{StaticResource AccentButtonStyle}"/>
<Button Content="Платежи и счета" Width="150" Height="40" Margin="5" Style="{StaticResource AccentButtonStyle}"/>
</WrapPanel>
<!-- Statistics Section -->
<GroupBox Header="Статистика" Margin="0,0,0,20">
<StackPanel>
<TextBlock Text="Занятых помещений: " FontSize="14" Margin="0,0,0,5"/>
<TextBlock Text="Общая выручка за месяц: " FontSize="14" Margin="0,0,0,5"/>
<TextBlock Text="Количество активных клиентов: " FontSize="14"/>
</StackPanel>
</GroupBox>
</StackPanel>
</Grid>
</Page>

View File

@@ -0,0 +1,197 @@
using OfficeFlow.Pages.EmployeePages;
using OfficeFlow.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace OfficeFlow.Pages
{
/// <summary>
/// Interaction logic for MainPage.xaml
/// </summary>
public partial class MainPage : Page
{
public MainPage()
{
InitializeComponent();
}
public void ReloadMenu()
{
MainMenu.Items.Clear();
string roleName = Session.CurrentUser.Role.RoleName;
switch (roleName)
{
case "Администратор":
MainMenu.Items.Add(CreateAdminMenu());
MainMenu.Items.Add(CreateManagerMenu());
MainMenu.Items.Add(CreateAccountantMenu());
break;
case "Менеджер":
MainMenu.Items.Add(CreateManagerMenu());
break;
case "Бухгалтер":
MainMenu.Items.Add(CreateAccountantMenu());
break;
default:
break;
}
var aboutMenuItem = new MenuItem
{
Header = "Справка",
};
aboutMenuItem.Click += MenuItemAbout_Click;
MainMenu.Items.Add(
aboutMenuItem
);
}
private MenuItem CreateAdminMenu()
{
MenuItem adminMenuItem = new MenuItem
{
Name = "MenuItemAdmin",
Header = "Администрирование"
};
var empl = new MenuItem
{
Header = "Сотрудники",
};
empl.Click += (object sender, RoutedEventArgs e) => NavigationService.Navigate(new EmployeesPage());
adminMenuItem.Items.Add(empl);
var emplPositions = new MenuItem
{
Header = "Должности",
};
emplPositions.Click += (object sender, RoutedEventArgs e) => NavigationService.Navigate(new EmployeesPositionsPage());
adminMenuItem.Items.Add(emplPositions);
var users = new MenuItem
{
Header = "Учётные записи",
};
users.Click += (object sender, RoutedEventArgs e) => throw new NotImplementedException();
adminMenuItem.Items.Add(users);
var tmp = new MenuItem
{
Header = "Кабинеты",
};
tmp.Click += (object sender, RoutedEventArgs e) => throw new NotImplementedException();
adminMenuItem.Items.Add(tmp);
tmp = new MenuItem
{
Header = "Услуги",
};
tmp.Click += (object sender, RoutedEventArgs e) => throw new NotImplementedException();
adminMenuItem.Items.Add(tmp);
tmp = new MenuItem
{
Header = "Виды условий оплат",
};
tmp.Click += (object sender, RoutedEventArgs e) => throw new NotImplementedException();
adminMenuItem.Items.Add(tmp);
tmp = new MenuItem
{
Header = "Единицы измерений для услуг",
};
tmp.Click += (object sender, RoutedEventArgs e) => throw new NotImplementedException();
adminMenuItem.Items.Add(tmp);
return adminMenuItem;
}
private MenuItem CreateManagerMenu()
{
MenuItem managerMenuItem = new MenuItem { Header = "Управление" };
var tenantsMenuItem = new MenuItem { Header = "Арендаторы" };
tenantsMenuItem.Click += (sender, e) => throw new NotImplementedException();
managerMenuItem.Items.Add(tenantsMenuItem);
var roomsMenuItem = new MenuItem { Header = "Помещения" };
roomsMenuItem.Click += (sender, e) => throw new NotImplementedException();
managerMenuItem.Items.Add(roomsMenuItem);
return managerMenuItem;
}
private MenuItem CreateAccountantMenu()
{
MenuItem accountantMenuItem = new MenuItem { Header = "Финансы" };
var rentalPaymentsMenuItem = new MenuItem { Header = "Платежи за аренду" };
rentalPaymentsMenuItem.Click += (sender, e) => throw new NotImplementedException();
accountantMenuItem.Items.Add(rentalPaymentsMenuItem);
var servicePaymentsMenuItem = new MenuItem { Header = "Платежи за услуги" };
servicePaymentsMenuItem.Click += (sender, e) => throw new NotImplementedException();
accountantMenuItem.Items.Add(servicePaymentsMenuItem);
return accountantMenuItem;
}
public void ClearHistory()
{
while (NavigationService.CanGoBack)
{
NavigationService.RemoveBackEntry();
}
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
ClearHistory();
if (Session.CurrentUser == null)
{
NavigationService.Navigate(new LoginPage());
}
else
{
ReloadMenu();
}
}
private void MenuItemAbout_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Программа была сделана в рамках дипломной работы " +
"специальности \"Информационные системы и программирование\".");
}
}
}

View File

@@ -6,9 +6,51 @@
xmlns:local="clr-namespace:OfficeFlow.Pages.StartupPages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="CreateAdministrator">
Title="Создание главного администратора">
<Grid>
<Grid Background="#F5F5F5">
<!-- Основной контейнер -->
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Width="400">
<!-- Заголовок -->
<TextBlock Text="Теперь создадим первого пользователя"
FontSize="20" FontWeight="Bold"
TextAlignment="Center" Margin="0,0,0,20"/>
<!-- Поле для ввода логина -->
<StackPanel Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Логин:" FontSize="14" FontWeight="SemiBold"/>
<TextBox x:Name="LoginTextBox" Height="30" FontSize="14" Padding="5"/>
</StackPanel>
<!-- Поле для ввода пароля -->
<StackPanel Orientation="Vertical" Margin="0,0,0,10">
<TextBlock Text="Пароль:" FontSize="14" FontWeight="SemiBold"/>
<PasswordBox x:Name="PasswordBox" Height="30" FontSize="14" Padding="5"/>
</StackPanel>
<!-- Поле для ввода email -->
<StackPanel Orientation="Vertical" Margin="0,0,0,20">
<TextBlock Text="Email:" FontSize="14" FontWeight="SemiBold"/>
<TextBox x:Name="EmailTextBox" Height="30" FontSize="14" Padding="5"/>
</StackPanel>
<Button Content="Создать администратора"
Background="#4CAF50" Foreground="White"
FontSize="16" Height="40"
Click="CreateAdministrator_Click"
Cursor="Hand"
x:Name="BCreate"
/>
<!-- Сообщение об ошибке или успехе -->
<TextBlock x:Name="StatusMessage"
Text=""
FontSize="14"
Foreground="Red"
TextAlignment="Center"
Margin="0,10,0,0"
Visibility="Collapsed"/>
</StackPanel>
</Grid>
</Page>

View File

@@ -1,4 +1,6 @@
using System;
using OfficeFlow.Models;
using OfficeFlow.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -24,5 +26,102 @@ namespace OfficeFlow.Pages.StartupPages
{
InitializeComponent();
}
private void CreateAdministrator_Click(object sender, RoutedEventArgs e)
{
// Получаем значения из полей
string login = LoginTextBox.Text.Trim();
string password = PasswordBox.Password.Trim();
string email = EmailTextBox.Text.Trim();
// Проверяем, что все поля заполнены
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
{
ShowStatusMessage("Ошибка: заполните все поля.", true);
return;
}
// Простая валидация email
if (!IsValidEmail(email))
{
ShowStatusMessage("Ошибка: введите корректный email.", true);
return;
}
bool success = false;
using (var transaction = App.Entities.Database.BeginTransaction())
{
// Логика создания администратора (например, сохранение в базу данных)
try
{
var newUser = Session.CreateUser(login, password, App.Entities.Roles.Where((r) => r.RoleName == "Администратор").First(), email);
App.Entities.SaveChanges();
// Фиксируем транзакцию
transaction.Commit();
ShowStatusMessage("Администратор успешно создан!", false);
ClearFields();
Session.Authenticate(newUser);
success = true;
}
catch (Exception ex)
{
transaction.Rollback();
ShowStatusMessage($"Ошибка: {ex.Message}", true);
}
}
if (success)
{
NavigationService.Navigate(new MainPage());
}
}
private bool IsValidEmail(string email)
{
if (string.IsNullOrEmpty(email))
{
return true;
}
try
{
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
private void ShowStatusMessage(string message, bool isError)
{
StatusMessage.Text = message;
StatusMessage.Foreground = isError ? Brushes.Red : Brushes.Green;
StatusMessage.Visibility = Visibility.Visible;
}
private void ClearFields()
{
LoginTextBox.Clear();
PasswordBox.Clear();
EmailTextBox.Clear();
}
}
}

View File

@@ -17,7 +17,9 @@
<TextBlock Text="Нажмите кнопку ниже, чтобы создать стартовые данные."
FontSize="14" Margin="0,0,0,20" />
<Button Content="Инициализировать стартовые данные"
Width="250" Height="40" Click="Button_Click"/>
Width="250" Height="40" Click="Button_Click"
Background="#4CAF50" Foreground="White"
/>
</StackPanel>
</Grid>
</Page>

View File

@@ -32,6 +32,12 @@ namespace OfficeFlow.Pages.StartupPages
var needAccountStatuses = App.Entities.AccountStatuses.Count() == 0;
var needEmployeeStatuses = App.Entities.EmployeeStatuses.Count() == 0;
var needPaymentTerms = App.Entities.PaymentTerms.Count() == 0;
var needPaymentStatuses = App.Entities.PaymentStatuses.Count() == 0;
var needTenantStatuses = App.Entities.TenantStatuses.Count() == 0;
var needRentalStatuses = App.Entities.RentalStatuses.Count() == 0;
var needRoomStatuses = App.Entities.RoomStatuses.Count() == 0;
using (var transaction = App.Entities.Database.BeginTransaction())
{
@@ -131,6 +137,133 @@ namespace OfficeFlow.Pages.StartupPages
});
}
// Заполнение условий оплаты
if (needPaymentTerms)
{
App.Entities.PaymentTerms.Add(new PaymentTerm()
{
TermName = "Ежемесячно",
TermDescription = "Оплата производится один раз в месяц."
});
App.Entities.PaymentTerms.Add(new PaymentTerm()
{
TermName = "Ежеквартально",
TermDescription = "Оплата производится один раз в квартал (3 месяца)."
});
App.Entities.PaymentTerms.Add(new PaymentTerm()
{
TermName = "Ежегодно",
TermDescription = "Оплата производится один раз в год."
});
App.Entities.PaymentTerms.Add(new PaymentTerm()
{
TermName = "По факту",
TermDescription = "Оплата производится после предоставления услуги."
});
}
// Заполнение статусов платежей
if (needPaymentStatuses)
{
App.Entities.PaymentStatuses.Add(new PaymentStatus()
{
StatusName = "Оплачен",
StatusDescription = "Платеж успешно проведен."
});
App.Entities.PaymentStatuses.Add(new PaymentStatus()
{
StatusName = "Не оплачен",
StatusDescription = "Платеж ожидает оплаты."
});
App.Entities.PaymentStatuses.Add(new PaymentStatus()
{
StatusName = "Частично оплачен",
StatusDescription = "Платеж частично покрыт."
});
App.Entities.PaymentStatuses.Add(new PaymentStatus()
{
StatusName = "Отменен",
StatusDescription = "Платеж отменен."
});
}
// Заполнение статусов арендаторов
if (needTenantStatuses)
{
App.Entities.TenantStatuses.Add(new TenantStatus()
{
StatusName = "Активен",
StatusDescription = "Арендатор активно пользуется услугами."
});
App.Entities.TenantStatuses.Add(new TenantStatus()
{
StatusName = "Неактивен",
StatusDescription = "Арендатор временно не использует услуги."
});
App.Entities.TenantStatuses.Add(new TenantStatus()
{
StatusName = "Заблокирован",
StatusDescription = "Арендатор заблокирован из-за нарушений."
});
App.Entities.TenantStatuses.Add(new TenantStatus()
{
StatusName = "Ожидает подтверждения",
StatusDescription = "Арендатор зарегистрирован, но его статус ожидает подтверждения."
});
}
// Заполнение статусов аренды
if (needRentalStatuses)
{
App.Entities.RentalStatuses.Add(new RentalStatus()
{
StatusName = "Активна",
StatusDescription = "Аренда действует и оплачивается."
});
App.Entities.RentalStatuses.Add(new RentalStatus()
{
StatusName = "Завершена",
StatusDescription = "Аренда завершена и больше не действует."
});
App.Entities.RentalStatuses.Add(new RentalStatus()
{
StatusName = "Просрочена",
StatusDescription = "Аренда просрочена и требует оплаты."
});
App.Entities.RentalStatuses.Add(new RentalStatus()
{
StatusName = "Резерв",
StatusDescription = "Помещение зарезервировано, но аренда еще не началась."
});
}
// Заполнение статусов помещений
if (needRoomStatuses)
{
App.Entities.RoomStatuses.Add(new RoomStatus()
{
StatusName = "Свободно",
StatusDescription = "Помещение свободно для аренды."
});
App.Entities.RoomStatuses.Add(new RoomStatus()
{
StatusName = "Занято",
StatusDescription = "Помещение занято арендатором."
});
App.Entities.RoomStatuses.Add(new RoomStatus()
{
StatusName = "В ремонте",
StatusDescription = "Помещение находится в ремонте и недоступно для аренды."
});
App.Entities.RoomStatuses.Add(new RoomStatus()
{
StatusName = "Резерв",
StatusDescription = "Помещение зарезервировано, но аренда еще не началась."
});
}
App.Entities.SaveChanges();
transaction.Commit();

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace OfficeFlow.Utils.Converters
{
public class CountConverter : IValueConverter
{
/// <summary>
/// Преобразует входное значение (коллекцию) в количество элементов.
/// </summary>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Проверяем, является ли входное значение коллекцией
if (value is ICollection collection)
{
return collection.Count;
}
// Если значение не является коллекцией, возвращаем 0
return 0;
}
/// <summary>
/// Обратное преобразование (не используется в данном случае).
/// </summary>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

View File

@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace OfficeFlow.Utils.Converters
{
public class DateConverter : IValueConverter
{
/// <summary>
/// Преобразует входное значение даты в строку в заданном формате.
/// </summary>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is DateTime date)
{
// Если передан параметр, используем его как формат даты
string format = parameter as string ?? "dd.MM.yyyy";
return date.ToString(format);
}
// Если значение не является датой, возвращаем пустую строку
return string.Empty;
}
/// <summary>
/// Обратное преобразование (строка -> дата).
/// </summary>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string strDate && DateTime.TryParse(strDate, out DateTime result))
{
return result;
}
// Если преобразование невозможно, возвращаем null
return null;
}
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows;
namespace OfficeFlow.Utils.Converters
{
public class NullToVisibilityConverter : IValueConverter
{
/// <summary>
/// Преобразует null в Visibility.Collapsed и наоборот.
/// </summary>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

118
OfficeFlow/Utils/Session.cs Normal file
View File

@@ -0,0 +1,118 @@
using OfficeFlow.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeFlow.Utils
{
public static class Session
{
// Текущий авторизованный пользователь
public static User CurrentUser { get; private set; }
/// <summary>
/// Авторизация пользователя по логину и паролю
/// </summary>
/// <param name="login">Логин пользователя</param>
/// <param name="password">Пароль пользователя</param>
/// <returns>True, если авторизация успешна</returns>
public static bool Authenticate(string login, string password)
{
try
{
// Находим пользователя по логину
var user = App.Entities.Users.FirstOrDefault(u => u.Login == login);
if (user == null)
{
throw new Exception("Пользователь с таким логином не найден.");
}
// Проверяем пароль
if (!String.Equals(HashPassword(password), user.PasswordHash))//!BCrypt.Verify(password, user.PasswordHash))
{
throw new Exception("Неверный пароль.");
}
// Устанавливаем текущего пользователя
CurrentUser = user;
return true;
}
catch (Exception ex)
{
throw new Exception($"Ошибка авторизации: {ex.Message}");
}
}
/// <summary>
/// Создание нового пользователя
/// </summary>
/// <param name="login">Логин</param>
/// <param name="password">Пароль</param>
/// <param name="email">Email</param>
/// <returns>Созданный пользователь</returns>
public static User CreateUser(string login, string password, Role role, string email=null)
{
try
{
// Проверяем уникальность логина и email
if (App.Entities.Users.Any(u => u.Login == login))
{
throw new Exception("Пользователь с таким логином уже существует.");
}
// Создаем нового пользователя
var newUser = new User
{
Login = login,
PasswordHash = HashPassword(password), // Хэшируем пароль
Email = email,
AccountStatusID = App.Entities.AccountStatuses.Where((acs) => acs.StatusName == "Активен").First().StatusID
};
App.Entities.Users.Add(newUser);
App.Entities.User_Role.Add(
new User_Role
{
Role = role,
User = newUser
}
);
// Возвращаем созданного пользователя
return newUser;
}
catch (Exception ex)
{
throw new Exception($"Ошибка при создании пользователя: {ex.Message}");
}
}
/// <summary>
/// Хэширование пароля
/// </summary>
/// <param name="password">Пароль</param>
/// <returns>Хэшированный пароль</returns>
private static string HashPassword(string password)
{
return password.GetHashCode().ToString();
}
/// <summary>
/// Выход из системы (очистка текущего пользователя)
/// </summary>
public static void Logout()
{
CurrentUser = null;
}
public static bool Authenticate(User user)
{
CurrentUser = user;
return true;
}
}
}