Reports done + ability to switch databases + begin implementation of db sync feature

This commit is contained in:
abazov73 2023-05-11 12:11:29 +04:00
parent 306064c808
commit f1976a82d2
15 changed files with 280 additions and 37 deletions

View File

@ -31,18 +31,18 @@ namespace ConstructionCompanyBusinessLogic.BusinessLogics
public void GenerateEmployees()
{
int posInd = 1;
int posInd = 0;
for (int i = 0; i < 200; i++)
{
_employee.Create(new EmployeeBindingModel { EmployeeName = "testEmp" + (i + 1), PositionID = posInd });
posInd++;
if (posInd == 11) posInd = 1;
if (posInd == 20) posInd = 0;
}
}
public void GenerateEmployeesOrders()
{
for (int i = 1; i <= 200; i++)
for (int i = 0; i < 200; i++)
{
_employeeOrder.Create(new EmployeeOrderBindingModel { EmployeeId = i, OrderId = i});
}
@ -51,7 +51,7 @@ namespace ConstructionCompanyBusinessLogic.BusinessLogics
public void GenerateMaterialOrders()
{
int quantity = 1;
for (int i = 1; i <= 200; i++)
for (int i = 0; i < 200; i++)
{
_materialOrder.Create(new MaterialOrderBindingModel { MaterialId = i, OrderId = i, Quantity = quantity});
quantity++;
@ -65,8 +65,8 @@ namespace ConstructionCompanyBusinessLogic.BusinessLogics
int quantity = 1;
for (int i = 1; i <= 100; i++)
{
int mat = rand.Next(1, 10);
int ord = rand.Next(1, 100);
int mat = rand.Next(0, 10);
int ord = rand.Next(0, 100);
if (_materialOrder.ReadElement(new MaterialOrderSearchModel { MaterialId = mat, OrderId = ord}) != null)
{
i--;

View File

@ -12,6 +12,7 @@
<ItemGroup>
<ProjectReference Include="..\ConstructionCompanyContracts\ConstructionCompanyContracts.csproj" />
<ProjectReference Include="..\ConstructionCompanyPsqlImplement\ConstructionCompanyPsqlImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -8,6 +8,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConstructionCompanyDataModels.Enums;
using ConstructionCompanyContracts.ViewModels;
namespace ConstructionCompanyMongoDBImplement
{
@ -75,6 +76,12 @@ namespace ConstructionCompanyMongoDBImplement
}
}
public ConstructionCompanyDatabase()
{
refreshDb();
}
public static ConstructionCompanyDatabase GetInstance()
{
if (_instance == null)
@ -86,7 +93,87 @@ namespace ConstructionCompanyMongoDBImplement
public BsonDocument ReadDocument(BsonDocument filter, string collectionName)
{
var collection = client.GetDatabase(databaseName).GetCollection<BsonDocument>(collectionName);
BsonDocument result = collection.Find(filter).ToList()[0];
BsonDocument result = collection.Find(filter).First();
return result;
}
public void flushDb()
{
var db = client.GetDatabase(databaseName);
db.GetCollection<BsonDocument>("Employees").DeleteMany(new BsonDocument());
db.GetCollection<BsonDocument>("Orders").DeleteMany(new BsonDocument());
db.GetCollection<BsonDocument>("Materials").DeleteMany(new BsonDocument());
db.GetCollection<BsonDocument>("Positions").DeleteMany(new BsonDocument());
}
public List<EmployeeViewModel> reportMaterials(int materialId)
{
var materials = client.GetDatabase(databaseName).GetCollection<BsonDocument>("Materials");
var res = materials.Aggregate()
.Lookup(
"Orders",
"_id",
"materials.materialId",
"order"
)
.Lookup(
"Employees",
"order.employeesId",
"_id",
"employee"
)
.Match(new BsonDocument { { "_id", materialId} })
.ToList();
BsonArray resEmployees = res[0][4].AsBsonArray;
List<EmployeeViewModel> result = new List<EmployeeViewModel>();
foreach (var employee in resEmployees)
{
result.Add(_employees.First(x => x.Id == employee[0].ToInt32()).GetViewModel);
}
return result;
}
public List<BrigadeReportViewModel> reportPositionsAverage(DateTime from, DateTime to)
{
var positions = client.GetDatabase(databaseName).GetCollection<BsonDocument>("Positions");
var res = positions.Aggregate()
.Lookup(
"Employees",
"_id",
"positionId",
"employee"
)
.Lookup(
"Orders",
"employee._id",
"employeesId",
"order"
)
.Unwind("order")
.Match(new BsonDocument { { "order.dateBegin", new BsonDocument("$gte", new BsonDateTime(from)) } })
.Match(new BsonDocument { { "order.dateBegin", new BsonDocument("$lte", new BsonDateTime(to)) } })
.Unwind("order.materials")
.Group(new BsonDocument
{
{"_id", "$_id"},
{"average", new BsonDocument("$avg", "$order.materials.quantity")}
})
.ToList();
var result = new List<BrigadeReportViewModel>();
foreach (var report in res)
{
int posId = report[0].ToInt32();
string posName = _positions.First(x => x.Id == posId).PositionName;
int avg = report[1].ToInt32();
result.Add(new BrigadeReportViewModel { PositionId = posId, PositionName = posName, materialAvg = avg });
}
return result;
}
public List<BsonDocument> FilterDocuments(BsonDocument filter, string collectionName)
{
var collection = client.GetDatabase(databaseName).GetCollection<BsonDocument>(collectionName);
List<BsonDocument> result = collection.Find(filter).ToList();
return result;
}

View File

@ -96,17 +96,29 @@ namespace ConstructionCompanyMongoDBImplement.Implements
}
public List<EmployeeViewModel>? GetEmployeesUsingMaterial(MaterialBindingModel model)
{
//var command = Material.GetEmployeeCommand(model);
//if (string.IsNullOrEmpty(command))
if (model == null)
{
return null;
}
//List<Employee> employeesList = _source.Employees;
//BsonDocument filter = new BsonDocument { { "materials.materialId", new BsonDocument("$eq", model.Id) } };
//List<BsonDocument> fiteredOrders = _source.FilterDocuments(filter, "Orders");
//List<EmployeeViewModel> employees = new List<EmployeeViewModel>();
//foreach (var order in fiteredOrders)
//{
// return null;
//}
//var employeesId = _source.ExecuteReader(command, 1);
List<EmployeeViewModel> employees = new List<EmployeeViewModel>();
//foreach (var id in employeesId)
//{
// employees.Add(_source.Employees.First(x => x.Id == Convert.ToInt32(id[0])).GetViewModel);
// var orderEmployees = order[8].AsBsonArray;
// foreach (var employee in orderEmployees)
// {
// var emp = employees.FirstOrDefault(x => x.Id == employee.ToInt32());
// if (emp == null)
// {
// employees.Add(employeesList.First(x => x.Id == employee.ToInt32()).GetViewModel);
// }
// }
//}
var employees = _source.reportMaterials(model.Id);
return employees;
}
}

View File

@ -103,14 +103,8 @@ namespace ConstructionCompanyMongoDBImplement.Implements
public List<BrigadeReportViewModel> GetPositionsAverage(DateTime dateFrom, DateTime dateTo)
{
//var command = Position.PositionsAVGCommnad(dateFrom, dateTo);
//var result = _source.ExecuteReader(command, 2);
List<BrigadeReportViewModel> positionsAverages = new List<BrigadeReportViewModel>();
//foreach (var posAvgPair in result)
//{
// string positionName = _source.Positions.First(x => x.Id == Convert.ToInt32(posAvgPair[0])).PositionName;
// positionsAverages.Add(new BrigadeReportViewModel { PositionId = Convert.ToInt32(posAvgPair[0]), PositionName = positionName, materialAvg = Convert.ToDouble(posAvgPair[1]) });
//}
//_source.flushDb();
List<BrigadeReportViewModel> positionsAverages = _source.reportPositionsAverage(dateFrom, dateTo);
return positionsAverages;
}
}

View File

@ -43,7 +43,7 @@ namespace ConstructionCompanyMongoDBImplement.Models
{
{"_id", model.Id},
{"EmployeeName", $"{model.EmployeeName}"},
{"positionId", $"{model.PositionID}" }
{"positionId", model.PositionID}
};
}
@ -57,7 +57,7 @@ namespace ConstructionCompanyMongoDBImplement.Models
{
{"_id", model.Id},
{"EmployeeName", $"{model.EmployeeName}"},
{"positionId", $"{model.PositionID}" }
{"positionId", model.PositionID}
};
}
public EmployeeViewModel GetViewModel => new()

View File

@ -55,7 +55,7 @@ namespace ConstructionCompanyMongoDBImplement.Models
{"_id", model.Id},
{"description", $"{model.Description}"},
{"adress", $"{model.Adress}"},
{"price", $"{model.Price}"},
{"price", model.Price},
{"status", $"{model.Status}"},
{"customerNumber", $"{model.CustomerNumber}"},
{"dateBegin", new BsonDateTime(model.DateBegin)},
@ -76,7 +76,7 @@ namespace ConstructionCompanyMongoDBImplement.Models
{"_id", model.Id},
{"description", $"{model.Description}"},
{"adress", $"{model.Adress}"},
{"price", $"{model.Price}"},
{"price", model.Price},
{"status", $"{model.Status}"},
{"customerNumber", $"{model.CustomerNumber}"},
{"dateBegin", new BsonDateTime(model.DateBegin)},

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ConstructionCompanyView.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
<section name="ConstructionCompanyView.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<ConstructionCompanyView.Properties.Settings>
<setting name="bdType" serializeAs="String">
<value>postgres</value>
</setting>
</ConstructionCompanyView.Properties.Settings>
<ConstructionCompanyView.Settings>
<setting name="bdType" serializeAs="String">
<value>postgres</value>
</setting>
</ConstructionCompanyView.Settings>
</userSettings>
</configuration>

View File

@ -41,6 +41,11 @@
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Update="Properties\Settings.Designer.cs">
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
@ -54,6 +59,10 @@
<None Update="nlogConstruction.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
</Project>

View File

@ -23,7 +23,7 @@ namespace ConstructionCompanyView
private void buttonShow_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value > dateTimePickerTo.Value)
if (dateTimePickerFrom.Value.Date > dateTimePickerTo.Value.Date)
{
MessageBox.Show("Неверно выбраны даты!");
return;

View File

@ -33,6 +33,8 @@
this.buttonManager = new System.Windows.Forms.Button();
this.buttonHR = new System.Windows.Forms.Button();
this.buttonGenerate = new System.Windows.Forms.Button();
this.buttonSwitchDB = new System.Windows.Forms.Button();
this.buttonSync = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
@ -77,20 +79,42 @@
//
// buttonGenerate
//
this.buttonGenerate.Location = new System.Drawing.Point(12, 309);
this.buttonGenerate.Location = new System.Drawing.Point(33, 309);
this.buttonGenerate.Name = "buttonGenerate";
this.buttonGenerate.Size = new System.Drawing.Size(154, 29);
this.buttonGenerate.Size = new System.Drawing.Size(174, 29);
this.buttonGenerate.TabIndex = 4;
this.buttonGenerate.Text = "Создать компанию";
this.buttonGenerate.UseVisualStyleBackColor = true;
this.buttonGenerate.Click += new System.EventHandler(this.buttonGenerate_Click);
//
// buttonSwitchDB
//
this.buttonSwitchDB.Location = new System.Drawing.Point(543, 309);
this.buttonSwitchDB.Name = "buttonSwitchDB";
this.buttonSwitchDB.Size = new System.Drawing.Size(229, 29);
this.buttonSwitchDB.TabIndex = 5;
this.buttonSwitchDB.Text = "Переключить на ";
this.buttonSwitchDB.UseVisualStyleBackColor = true;
this.buttonSwitchDB.Click += new System.EventHandler(this.buttonSwitchDB_Click);
//
// buttonSync
//
this.buttonSync.Location = new System.Drawing.Point(299, 309);
this.buttonSync.Name = "buttonSync";
this.buttonSync.Size = new System.Drawing.Size(174, 29);
this.buttonSync.TabIndex = 6;
this.buttonSync.Text = "Синхронизировать БД";
this.buttonSync.UseVisualStyleBackColor = true;
this.buttonSync.Click += new System.EventHandler(this.buttonSync_Click);
//
// FormLogin
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.ClientSize = new System.Drawing.Size(784, 350);
this.Controls.Add(this.buttonSync);
this.Controls.Add(this.buttonSwitchDB);
this.Controls.Add(this.buttonGenerate);
this.Controls.Add(this.buttonHR);
this.Controls.Add(this.buttonManager);
@ -98,6 +122,7 @@
this.Controls.Add(this.label1);
this.Name = "FormLogin";
this.Text = "Вход";
this.Load += new System.EventHandler(this.FormLogin_Load);
this.ResumeLayout(false);
this.PerformLayout();
@ -110,5 +135,7 @@
private Button buttonManager;
private Button buttonHR;
private Button buttonGenerate;
private Button buttonSwitchDB;
private Button buttonSync;
}
}

View File

@ -24,6 +24,7 @@ namespace ConstructionCompanyView
private void buttonWarehouse_Click(object sender, EventArgs e)
{
//MessageBox.Show(Properties.Settings.Default.bdType);
var service = Program.ServiceProvider?.GetService(typeof(FormWarehouseMenu));
if (service is FormWarehouseMenu form)
{
@ -85,5 +86,31 @@ namespace ConstructionCompanyView
MessageBox.Show($"materials={materials}, positions={positions}, employees={employees}, orders={orders}, materialOrders={materialOrders}, employeeOrders={employeesOrders}", "Результаты");
MessageBox.Show("Готово!");
}
private void FormLogin_Load(object sender, EventArgs e)
{
string dbType = Properties.Settings.Default.bdType;
if (dbType == "postgres") buttonSwitchDB.Text = "Переклюить на MongoDB";
else buttonSwitchDB.Text = "Переключить на PostgreSQL";
}
private void buttonSwitchDB_Click(object sender, EventArgs e)
{
var dialogResult = MessageBox.Show("Данное действие требует перезапуска программы!", "Продолжить?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.No || dialogResult == DialogResult.Cancel) return;
string dbType = Properties.Settings.Default.bdType;
if (dbType == "postgres") Properties.Settings.Default.bdType = "mongoDB";
else Properties.Settings.Default.bdType = "postgres";
Properties.Settings.Default.Save();
MessageBox.Show("Сейчас программа автоматически выключится.", "Готово");
this.Close();
}
private void buttonSync_Click(object sender, EventArgs e)
{
ConstructionCompanyPsqlImplement.ConstructionCompanyDatabase psqlDb = ConstructionCompanyPsqlImplement.ConstructionCompanyDatabase.GetInstance();
ConstructionCompanyMongoDBImplement.ConstructionCompanyDatabase mongoDb = ConstructionCompanyMongoDBImplement.ConstructionCompanyDatabase.GetInstance();
mongoDb.flushDb();
}
}
}

View File

@ -2,6 +2,7 @@ using ConstructionCompanyBusinessLogic.BusinessLogics;
using ConstructionCompanyContracts.BusinessLogicContracts;
using ConstructionCompanyContracts.StorageContracts;
using ConstructionCompanyMongoDBImplement.Implements;
using ConstructionCompanyPsqlImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
@ -34,12 +35,9 @@ namespace ConstructionCompanyView
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlogConstruction.config");
});
services.AddTransient<IMaterialStorage, MaterialStorage>();
services.AddTransient<IPositionStorage, PositionStorage>();
services.AddTransient<IEmployeeStorage, EmployeeStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IEmployeeOrderStorage, EmployeeOrderStorage>();
services.AddTransient<IMaterialOrderStorage, MaterialOrderStorage>();
if (Properties.Settings.Default.bdType == "postgres") addPgsql(services);
else addMongoDB(services);
services.AddTransient<IMaterialLogic, MaterialLogic>();
services.AddTransient<IPositionLogic, PositionLogic>();
@ -68,5 +66,25 @@ namespace ConstructionCompanyView
services.AddTransient<FormWarehouseReport>();
services.AddTransient<FormBrigadeReport>();
}
private static void addPgsql(ServiceCollection services)
{
services.AddTransient<IMaterialStorage, ConstructionCompanyPsqlImplement.Implements.MaterialStorage>();
services.AddTransient<IPositionStorage, ConstructionCompanyPsqlImplement.Implements.PositionStorage>();
services.AddTransient<IEmployeeStorage, ConstructionCompanyPsqlImplement.Implements.EmployeeStorage>();
services.AddTransient<IOrderStorage, ConstructionCompanyPsqlImplement.Implements.OrderStorage>();
services.AddTransient<IEmployeeOrderStorage, ConstructionCompanyPsqlImplement.Implements.EmployeeOrderStorage>();
services.AddTransient<IMaterialOrderStorage, ConstructionCompanyPsqlImplement.Implements.MaterialOrderStorage>();
}
private static void addMongoDB(ServiceCollection services)
{
services.AddTransient<IMaterialStorage, ConstructionCompanyMongoDBImplement.Implements.MaterialStorage>();
services.AddTransient<IPositionStorage, ConstructionCompanyMongoDBImplement.Implements.PositionStorage>();
services.AddTransient<IEmployeeStorage, ConstructionCompanyMongoDBImplement.Implements.EmployeeStorage>();
services.AddTransient<IOrderStorage, ConstructionCompanyMongoDBImplement.Implements.OrderStorage>();
services.AddTransient<IEmployeeOrderStorage, ConstructionCompanyMongoDBImplement.Implements.EmployeeOrderStorage>();
services.AddTransient<IMaterialOrderStorage, ConstructionCompanyMongoDBImplement.Implements.MaterialOrderStorage>();
}
}
}

View File

@ -0,0 +1,38 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ConstructionCompanyView.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.3.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("postgres")]
public string bdType {
get {
return ((string)(this["bdType"]));
}
set {
this["bdType"] = value;
}
}
}
}

View File

@ -0,0 +1,9 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="ConstructionCompanyView.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="bdType" Type="System.String" Scope="User">
<Value Profile="(Default)">postgres</Value>
</Setting>
</Settings>
</SettingsFile>