Edit/delete work function is done

This commit is contained in:
RavilGismatullin 2024-08-23 19:44:26 +04:00
parent f468ca7603
commit 7745307e48
25 changed files with 759 additions and 199 deletions

View File

@ -77,7 +77,7 @@ namespace ServiceStationBusinessLogic.BusinessLogic {
};
foreach (var work in works) {
var task = _taskStorage.GetElement(new TaskSearchModel { Id = work.TaskId }) ?? throw new Exception("Ошибка получения данных");
var task = _taskStorage.GetElement(new TaskSearchModel { Id = work.TaskByWorkId }) ?? throw new Exception("Ошибка получения данных");
record.WorkTask.Add(new(work.Id, work.Date.ToShortDateString(), work.Price, task.Id, task.Name));
record.TotalCount++;
}

View File

@ -92,13 +92,13 @@ namespace ServiceStationBusinessLogic.BusinessLogic
if (string.IsNullOrEmpty(model.ExecutorId.ToString())) {
throw new ArgumentNullException("Нет номера исполнителя", nameof(model.ExecutorId));
}
if (string.IsNullOrEmpty(model.TaskId.ToString())) {
throw new ArgumentNullException("Нет номера задачи", nameof(model.TaskId));
if (string.IsNullOrEmpty(model.TaskByWorkId.ToString())) {
throw new ArgumentNullException("Нет номера задачи", nameof(model.TaskByWorkId));
}
if (model.ClientList.Count <= 0) {
throw new ArgumentException("Работа не может быть без клиента", nameof(model.ClientList));
}
_logger.LogInformation($"Work.Id:{model.Id}.Date:{model.Date}.Price:{model.Price}.ExecutorId:{model.ExecutorId}.TaskId:{model.TaskId}." +
_logger.LogInformation($"Work.Id:{model.Id}.Date:{model.Date}.Price:{model.Price}.ExecutorId:{model.ExecutorId}.TaskId:{model.TaskByWorkId}." +
$"ClientList.Count:{model.ClientList.Count}");
}
}

View File

@ -8,7 +8,7 @@ namespace ServiceStationContracts.BindingModels
public DateTime Date { get; set; } = DateTime.Now;
public double Price { get; set; }
public int ExecutorId { get; set; }
public int TaskId { get; set; }
public int TaskByWorkId { get; set; }
public Dictionary<int, IClientModel> ClientList { get; set; } = new();
}

View File

@ -3,7 +3,7 @@ using System.ComponentModel;
namespace ServiceStationContracts.ViewModels
{
public class ClientViewModel : IClientModel
public class ClientViewModel : IClientModel, IEquatable<ClientViewModel>
{
public int Id { get; set; }
@ -12,5 +12,15 @@ namespace ServiceStationContracts.ViewModels
[DisplayName("Всего баллов")]
public int TotalPoints { get; set; }
public bool Equals(ClientViewModel? other) {
if (other is null) {
return false;
}
return this.Id == other.Id && this.FIO == other.FIO;
}
public override bool Equals(object obj) => Equals(obj as ClientViewModel);
public override int GetHashCode() => (Id, FIO).GetHashCode();
}
}

View File

@ -16,7 +16,7 @@ namespace ServiceStationContracts.ViewModels
public int ExecutorId { get; set; }
public int TaskId { get; set; }
public int TaskByWorkId { get; set; }
[DisplayName("Задача")]
public string TaskName { get; set; } = string.Empty;

View File

@ -12,7 +12,7 @@ namespace ServiceStationDataModels.Models
DateTime Date { get; }
double Price { get; }
int ExecutorId { get; }
int TaskId { get; }
int TaskByWorkId { get; }
// ClientId, ClientModel
Dictionary<int, IClientModel> ClientList { get; }

View File

@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
using ServiceSourceClientApp.Models;
using ServiceSourceExecutorApp;
using ServiceStationContracts.BindingModels;
@ -115,10 +116,82 @@ namespace ServiceSourceClientApp.Controllers {
});
}
[HttpGet]
public IActionResult EditWork(int Id) {
if (Id == 0) {
return RedirectToAction("Index");
}
var work_info = APIClient.GetRequest<List<List<string>>>($"api/Main/GetWork?_workId={Id}")
?? throw new Exception("Îøèáêà ïîëó÷åíèÿ äàííûõ");
ViewBag.Tasks = APIClient.GetRequest<List<TaskViewModel>>($"api/Main/GetTasks?");
int task_load_id = JsonConvert.DeserializeObject<int>(work_info[0][0]);
var task_load = APIClient.GetRequest<TaskViewModel>($"api/Main/GetTask?_taskId={task_load_id}")
?? throw new Exception("Îøèáêà ïîëó÷åíèÿ äàííûõ");
if (ViewBag.Tasks[0].Name != task_load.Name) {
int index = 0;
for (int i = 0; i < ViewBag.Tasks.Count; i++) {
if (ViewBag.Tasks[i].Name == task_load.Name) {
index = i;
break;
}
}
var tmp = ViewBag.Tasks[0];
ViewBag.Tasks[0] = task_load;
ViewBag.Tasks[index] = tmp;
}
List<ClientViewModel> clients_list = new();
foreach (var rec in work_info[1]) {
var client = JsonConvert.DeserializeObject<ClientViewModel>(rec) ?? throw new Exception("Îøèáêà äåñåðèàëèçàöèè");
clients_list.Add(client);
}
var clients = APIClient.GetRequest<List<ClientViewModel>>($"api/Main/GetClients?")
?? throw new Exception("Îøèáêà ïîëó÷åíèÿ äàííûõ");
IEnumerable<ClientViewModel> result = clients.Except(clients_list);
List<ClientViewModel> new_client = new();
foreach (var client in result) {
new_client.Add(client);
}
(int, List<ClientViewModel>, List<ClientViewModel>) tuple = (Id, clients_list, new_client);
return View(tuple);
}
[HttpPost]
public void EditWork(int[] ids, int task, int id) {
if (APIClient.executor == null) {
Response.Redirect("~/Home/Enter");
return;
}
APIClient.PostRequest("api/Main/UpdateWork", new WorkFromWebBindingModel {
Id = id,
Price = Calc(task, ids.Length),
ExecutorId = APIClient.executor.Id,
TaskId = task,
client_ids = ids
});
}
[HttpPost]
public double Calc(int task, int count) {
var task_info = APIClient.GetRequest<TaskViewModel>($"api/Main/GetTask?_taskId={task}") ?? throw new Exception("Îøèáêà ïîëó÷åèÿ äàííûõ");
return task_info.Price + 700 * count;
}
[HttpGet]
public IActionResult DeleteWork(int id) {
APIClient.PostRequest("api/Main/DeleteWork", new WorkBindingModel {
Id = id,
});
return RedirectToAction("Index");
}
}
}

View File

@ -135,10 +135,10 @@
url: '/Home/CreateWork',
data: {'ids':val, 'task': task},
success: function () {
window.location.href = "Index";
},
error: function () {
window.location.href = "Index";
}
})
});

View File

@ -0,0 +1,221 @@
@using ServiceStationContracts.ViewModels
@{
ViewData["Title"] = "EditWork";
}
@model (int, List<ClientViewModel>, List<ClientViewModel>)
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<div class="text-center">
<h2 class="display-4">Редактировать работу №:@Model.Item1</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Задача:</div>
<div class="col-8">
<select id="task" name="task" class="form-control" asp-items="@(new SelectList(ViewBag.Tasks, "Id", "Name"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Стоимость:</div>
<div class="col-8">
<input id="price" type="text" name="price" readonly />
</div>
</div>
</form>
<div class="text-center">
<h2 class="display-5">Клиенты в работе</h2>
</div>
<div class="text-center">
@{
if (Model.Item2 == null) {
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<div class="text-end">
<button class="btn btn-outline-primary" id="btnEdit">Сохранить изменения</button>
</div>
<table class="table">
<thead>
<tr>
<th>
Номер клиента
</th>
<th>
ФИО клиента
</th>
<th>
<input type="checkbox" class="form-check-input old" id="Select_all" name="Select_all" /> Выбрать все
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Item2) {
<tr>
<th>
@Html.DisplayFor(modelItem => item.Id)
</th>
<th>
@Html.DisplayFor(modelItem => item.FIO)
</th>
<th>
<input type="checkbox" class="form-check-input old" id="Select_rec" name="Select_rec" value="@item.Id" />
</th>
</tr>
}
</tbody>
</table>
}
</div>
<div class="text-center">
<h2 class="display-5">Добавить новых клиентов</h2>
</div>
<div class="text-center">
@{
if (Model.Item3 == null) {
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Номер клиента
</th>
<th>
ФИО клиента
</th>
<th>
<input type="checkbox" class="form-check-input new" id="Select_all_new" name="Select_all_new" /> Выбрать все
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Item3) {
<tr>
<th>
@Html.DisplayFor(modelItem => item.Id)
</th>
<th>
@Html.DisplayFor(modelItem => item.FIO)
</th>
<th>
<input type="checkbox" class="form-check-input new" id="Select_rec_new" name="Select_rec_new" value="@item.Id" />
</th>
</tr>
}
</tbody>
</table>
}
</div>
<script>
$('#task').on('change', function () {
check();
});
$('.form-check-input').on('change', function () {
check();
});
document.getElementById('Select_all').checked = true;
checked_all();
check();
function check() {
debugger
var task = $('#task').val();
let checkboxes = document.getElementsByTagName('input');
var count = 0;
$("input[name='Select_rec']:checked").each(function () {
count++;
});
$("input[name='Select_rec_new']:checked").each(function () {
count++;
});
if (task && count >= 0) {
$.ajax({
method: 'POST',
url: '/Home/Calc',
data: { task: task, count: count },
success: function (result) {
$('#price').val(result)
},
error: function () {
}
})
};
}
function checked_all() {
debugger
let checkboxes = document.querySelectorAll('.form-check-input.old');
let val = null;
for (var i = 0; i < checkboxes.length; i++) {
if (val == null) {
val = checkboxes[i].checked;
}
else {
checkboxes[i].checked = val;
}
}
}
$('#Select_all').on('click', function () {
checked_all();
check();
});
$('#Select_all_new').on('click', function () {
debugger
let checkboxes = document.querySelectorAll('.form-check-input.new');
let val = null;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type === 'checkbox') {
if (val == null) {
val = checkboxes[i].checked;
}
else {
checkboxes[i].checked = val;
}
}
}
check();
});
$('#btnEdit').on('click', function () {
let val = [];
var task = $('#task').val();
var id = $('#id').val();
$("input[name='Select_rec']:checked").each(function () {
val.push($(this).val());
});
$("input[name='Select_rec_new']:checked").each(function () {
val.push($(this).val());
});
$.ajax({
type: 'POST',
url: '/Home/EditWork',
data: { 'ids': val, 'task': task, 'id':@Model.Item1 },
success: function () {
window.location.href = "Index";
},
error: function () {
window.location.href = "Index";
}
})
});
</script>

View File

@ -35,7 +35,7 @@
Номер задания
</th>
<th>
Задания
Задание
</th>
</tr>
</thead>
@ -52,11 +52,15 @@
@Html.DisplayFor(modelItem => item.Price)
</th>
<th>
@Html.DisplayFor(modelItem => item.TaskId)
@Html.DisplayFor(modelItem => item.TaskByWorkId)
</th>
<th>
@Html.DisplayFor(modelItem => item.TaskName)
</th>
<td>
<a class="btn btn-primary btn-sm" asp-action="EditWork" style="background-color:orange" asp-route-ID=" @item.Id">Изменить</a>
<a class="btn btn-primary btn-sm" asp-action="DeleteWork" style="background-color:red;" asp-route-ID="@item.Id">Удалить</a>
</td>
</tr>
}
</tbody>

View File

@ -6,6 +6,7 @@ using ServiceStationContracts.BusinessLogic;
using ServiceStationContracts.SearchModels;
using ServiceStationContracts.StorageContracts;
using ServiceStationContracts.ViewModels;
using Newtonsoft.Json;
namespace ServiceStationRestAPI.Controllers {
@ -78,7 +79,7 @@ namespace ServiceStationRestAPI.Controllers {
Date = model.Date,
Price = model.Price,
ExecutorId = model.ExecutorId,
TaskId = model.TaskId,
TaskByWorkId = model.TaskId,
ClientList = new()
};
@ -137,9 +138,24 @@ namespace ServiceStationRestAPI.Controllers {
}
[HttpGet]
public WorkViewModel? GetWork(int _workId) {
public List<List<string>> GetWork(int _workId) {
try {
return _workLogic.ReadElement(new WorkSearchModel { Id = _workId });
var list = new List<List<string>>();
var work_info = _workLogic.ReadElement(new WorkSearchModel { Id = _workId }) ?? throw new Exception("Ошибка получения данных");
list.Add(new List<string> { work_info.TaskByWorkId.ToString() });
List<string> client_list = new();
foreach (var client in work_info.ClientList) {
var record = new ClientViewModel {
Id = client.Key,
FIO = client.Value.FIO,
TotalPoints = client.Value.TotalPoints,
};
string jsRec = JsonConvert.SerializeObject(record);
client_list.Add(jsRec);
}
list.Add(client_list);
return list;
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения работы || work_id = {_workId}");

View File

@ -67,25 +67,22 @@ namespace ServiceStationsDataBaseImplement.Implements
using var context = new Database();
if (model.Id.HasValue) {
return context.Works
.Include(x => x._task)
.Include(x => x.WorkClients)
.ThenInclude(x => x._work)
.Include(x => x.WorkClients)
.ThenInclude(x => x._client)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
else if (model.ExecutorId.HasValue) {
return context.Works
.Include(x => x._task)
.Include(x => x.WorkClients)
.ThenInclude(x => x._work)
.ThenInclude(x => x._client)
.FirstOrDefault(x => x.ExecutorId == model.ExecutorId)
?.GetViewModel;
}
return context.Works
.Include(x => x._task)
.Include(x => x.WorkClients)
.ThenInclude(x => x._work)
.FirstOrDefault(x => x.TaskId == model.TaskId)
.ThenInclude(x => x._client)
.FirstOrDefault(x => x.TaskByWorkId == model.TaskId)
?.GetViewModel;
}
@ -94,7 +91,6 @@ namespace ServiceStationsDataBaseImplement.Implements
using var context = new Database();
if (model.DateFrom.HasValue && model.DateTo.HasValue) {
return context.Works
.Include(x => x._task)
.Include(x => x.WorkClients)
.ThenInclude(x => x._client)
.Where(x => x.Date >= model.DateFrom && x.Date <= model.DateTo)
@ -102,20 +98,16 @@ namespace ServiceStationsDataBaseImplement.Implements
.ToList();
}
else if (model.ExecutorId.HasValue) {
return context.Works
.Include(x => x._task)
.Include(x => x.WorkClients)
.ThenInclude(x => x._client)
return context.Works
.Where(x => x.ExecutorId == model.ExecutorId)
.ToList()
.Select(x => x.GetViewModel)
.Include(x => x._task)
.Select(x => x.GetViewModel)
.ToList();
}
return context.Works
.Include(x => x._task)
.Include(x => x.WorkClients)
.ThenInclude(x => x._client)
.Where(x => x.TaskId == model.TaskId)
.Where(x => x.TaskByWorkId == model.TaskId)
.Select(x => x.GetViewModel)
.ToList();
}
@ -124,7 +116,6 @@ namespace ServiceStationsDataBaseImplement.Implements
{
using var context = new Database();
return context.Works
.Include(x => x._task)
.Include(x => x.WorkClients)
.ThenInclude(x => x._client)
.Select(x => x.GetViewModel)

View File

@ -1,62 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ServiceStationsDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class Migration03 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Login",
table: "Clients");
migrationBuilder.DropColumn(
name: "Password",
table: "Clients");
migrationBuilder.AddColumn<double>(
name: "Price",
table: "Tasks",
type: "float",
nullable: false,
defaultValue: 0.0);
migrationBuilder.AddColumn<int>(
name: "TotalPoints",
table: "Clients",
type: "int",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Price",
table: "Tasks");
migrationBuilder.DropColumn(
name: "TotalPoints",
table: "Clients");
migrationBuilder.AddColumn<string>(
name: "Login",
table: "Clients",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "Password",
table: "Clients",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
}
}

View File

@ -12,8 +12,8 @@ using ServiceStationsDataBaseImplement;
namespace ServiceStationsDataBaseImplement.Migrations
{
[DbContext(typeof(Database))]
[Migration("20240822081747_Migration03")]
partial class Migration03
[Migration("20240823061523_InitMigration")]
partial class InitMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -107,17 +107,14 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int>("TaskId")
.HasColumnType("int");
b.Property<int?>("_taskId")
b.Property<int>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ExecutorId");
b.HasIndex("_taskId");
b.HasIndex("TaskByWorkId");
b.ToTable("Works");
});
@ -150,7 +147,7 @@ namespace ServiceStationsDataBaseImplement.Migrations
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Executor", null)
b.HasOne("ServiceStationsDataBaseImplement.Models.Executor", "_executor")
.WithMany("Works")
.HasForeignKey("ExecutorId")
.OnDelete(DeleteBehavior.Cascade)
@ -158,7 +155,11 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.HasOne("ServiceStationsDataBaseImplement.Models.TaskByWork", "_task")
.WithMany()
.HasForeignKey("_taskId");
.HasForeignKey("TaskByWorkId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("_executor");
b.Navigation("_task");
});

View File

@ -18,8 +18,7 @@ namespace ServiceStationsDataBaseImplement.Migrations
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
Login = table.Column<string>(type: "nvarchar(max)", nullable: false)
TotalPoints = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
@ -47,7 +46,8 @@ namespace ServiceStationsDataBaseImplement.Migrations
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
@ -63,7 +63,7 @@ namespace ServiceStationsDataBaseImplement.Migrations
Date = table.Column<DateTime>(type: "datetime2", nullable: false),
Price = table.Column<double>(type: "float", nullable: false),
ExecutorId = table.Column<int>(type: "int", nullable: false),
TaskId = table.Column<int>(type: "int", nullable: false)
TaskByWorkId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
@ -74,6 +74,12 @@ namespace ServiceStationsDataBaseImplement.Migrations
principalTable: "Executors",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Works_Tasks_TaskByWorkId",
column: x => x.TaskByWorkId,
principalTable: "Tasks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
@ -108,6 +114,11 @@ namespace ServiceStationsDataBaseImplement.Migrations
table: "Works",
column: "ExecutorId");
migrationBuilder.CreateIndex(
name: "IX_Works_TaskByWorkId",
table: "Works",
column: "TaskByWorkId");
migrationBuilder.CreateIndex(
name: "IX_WorksClients_ClientId",
table: "WorksClients",
@ -122,9 +133,6 @@ namespace ServiceStationsDataBaseImplement.Migrations
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Tasks");
migrationBuilder.DropTable(
name: "WorksClients");
@ -136,6 +144,9 @@ namespace ServiceStationsDataBaseImplement.Migrations
migrationBuilder.DropTable(
name: "Executors");
migrationBuilder.DropTable(
name: "Tasks");
}
}
}

View File

@ -12,8 +12,8 @@ using ServiceStationsDataBaseImplement;
namespace ServiceStationsDataBaseImplement.Migrations
{
[DbContext(typeof(Database))]
[Migration("20240820063305_InitMigration")]
partial class InitMigration
[Migration("20240823061703_Migration02")]
partial class Migration02
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -37,13 +37,8 @@ namespace ServiceStationsDataBaseImplement.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("TotalPoints")
.HasColumnType("int");
b.HasKey("Id");
@ -87,6 +82,9 @@ namespace ServiceStationsDataBaseImplement.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Tasks");
@ -109,7 +107,7 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int>("TaskId")
b.Property<int>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
@ -147,11 +145,13 @@ namespace ServiceStationsDataBaseImplement.Migrations
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Executor", null)
b.HasOne("ServiceStationsDataBaseImplement.Models.Executor", "_executor")
.WithMany("Works")
.HasForeignKey("ExecutorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("_executor");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.WorkClient", b =>

View File

@ -10,39 +10,30 @@ namespace ServiceStationsDataBaseImplement.Migrations
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "_taskId",
table: "Works",
type: "int",
nullable: true);
migrationBuilder.DropForeignKey(
name: "FK_Works_Tasks_TaskByWorkId",
table: "Works");
migrationBuilder.CreateIndex(
name: "IX_Works__taskId",
table: "Works",
column: "_taskId");
migrationBuilder.AddForeignKey(
name: "FK_Works_Tasks__taskId",
table: "Works",
column: "_taskId",
principalTable: "Tasks",
principalColumn: "Id");
migrationBuilder.DropIndex(
name: "IX_Works_TaskByWorkId",
table: "Works");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Works_Tasks__taskId",
table: "Works");
migrationBuilder.CreateIndex(
name: "IX_Works_TaskByWorkId",
table: "Works",
column: "TaskByWorkId");
migrationBuilder.DropIndex(
name: "IX_Works__taskId",
table: "Works");
migrationBuilder.DropColumn(
name: "_taskId",
table: "Works");
migrationBuilder.AddForeignKey(
name: "FK_Works_Tasks_TaskByWorkId",
table: "Works",
column: "TaskByWorkId",
principalTable: "Tasks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}

View File

@ -12,8 +12,8 @@ using ServiceStationsDataBaseImplement;
namespace ServiceStationsDataBaseImplement.Migrations
{
[DbContext(typeof(Database))]
[Migration("20240822072626_Migration02")]
partial class Migration02
[Migration("20240823062623_Migration03")]
partial class Migration03
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -37,13 +37,8 @@ namespace ServiceStationsDataBaseImplement.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("TotalPoints")
.HasColumnType("int");
b.HasKey("Id");
@ -87,8 +82,16 @@ namespace ServiceStationsDataBaseImplement.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int?>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TaskByWorkId");
b.ToTable("Tasks");
});
@ -109,18 +112,13 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int>("TaskId")
.HasColumnType("int");
b.Property<int?>("_taskId")
b.Property<int>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ExecutorId");
b.HasIndex("_taskId");
b.ToTable("Works");
});
@ -150,6 +148,15 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.ToTable("WorksClients");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.TaskByWork", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Work", "work")
.WithMany()
.HasForeignKey("TaskByWorkId");
b.Navigation("work");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Executor", null)
@ -157,12 +164,6 @@ namespace ServiceStationsDataBaseImplement.Migrations
.HasForeignKey("ExecutorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ServiceStationsDataBaseImplement.Models.TaskByWork", "_task")
.WithMany()
.HasForeignKey("_taskId");
b.Navigation("_task");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.WorkClient", b =>

View File

@ -0,0 +1,48 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ServiceStationsDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class Migration03 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "TaskByWorkId",
table: "Tasks",
type: "int",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Tasks_TaskByWorkId",
table: "Tasks",
column: "TaskByWorkId");
migrationBuilder.AddForeignKey(
name: "FK_Tasks_Works_TaskByWorkId",
table: "Tasks",
column: "TaskByWorkId",
principalTable: "Works",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Tasks_Works_TaskByWorkId",
table: "Tasks");
migrationBuilder.DropIndex(
name: "IX_Tasks_TaskByWorkId",
table: "Tasks");
migrationBuilder.DropColumn(
name: "TaskByWorkId",
table: "Tasks");
}
}
}

View File

@ -0,0 +1,209 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ServiceStationsDataBaseImplement;
#nullable disable
namespace ServiceStationsDataBaseImplement.Migrations
{
[DbContext(typeof(Database))]
[Migration("20240823064037_Migration04")]
partial class Migration04
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.18")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("TotalPoints")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Executor", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Executors");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.TaskByWork", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int?>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("TaskByWorkId")
.IsUnique()
.HasFilter("[TaskByWorkId] IS NOT NULL");
b.ToTable("Tasks");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<int>("ExecutorId")
.HasColumnType("int");
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ExecutorId");
b.ToTable("Works");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.WorkClient", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("PointCount")
.HasColumnType("int");
b.Property<int>("WorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("WorkId");
b.ToTable("WorksClients");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.TaskByWork", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Work", "work")
.WithOne("_task")
.HasForeignKey("ServiceStationsDataBaseImplement.Models.TaskByWork", "TaskByWorkId");
b.Navigation("work");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Executor", null)
.WithMany("Works")
.HasForeignKey("ExecutorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.WorkClient", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Client", "_client")
.WithMany("WorkClients")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ServiceStationsDataBaseImplement.Models.Work", "_work")
.WithMany("WorkClients")
.HasForeignKey("WorkId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("_client");
b.Navigation("_work");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Client", b =>
{
b.Navigation("WorkClients");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Executor", b =>
{
b.Navigation("Works");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
{
b.Navigation("WorkClients");
b.Navigation("_task");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ServiceStationsDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class Migration04 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Tasks_TaskByWorkId",
table: "Tasks");
migrationBuilder.CreateIndex(
name: "IX_Tasks_TaskByWorkId",
table: "Tasks",
column: "TaskByWorkId",
unique: true,
filter: "[TaskByWorkId] IS NOT NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Tasks_TaskByWorkId",
table: "Tasks");
migrationBuilder.CreateIndex(
name: "IX_Tasks_TaskByWorkId",
table: "Tasks",
column: "TaskByWorkId");
}
}
}

View File

@ -39,7 +39,7 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.HasKey("Id");
b.ToTable("Clients", (string)null);
b.ToTable("Clients");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Executor", b =>
@ -64,7 +64,7 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.HasKey("Id");
b.ToTable("Executors", (string)null);
b.ToTable("Executors");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.TaskByWork", b =>
@ -82,9 +82,16 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int?>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Tasks", (string)null);
b.HasIndex("TaskByWorkId")
.IsUnique()
.HasFilter("[TaskByWorkId] IS NOT NULL");
b.ToTable("Tasks");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
@ -104,19 +111,14 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.Property<double>("Price")
.HasColumnType("float");
b.Property<int>("TaskId")
.HasColumnType("int");
b.Property<int?>("_taskId")
b.Property<int>("TaskByWorkId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ExecutorId");
b.HasIndex("_taskId");
b.ToTable("Works", (string)null);
b.ToTable("Works");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.WorkClient", b =>
@ -142,7 +144,16 @@ namespace ServiceStationsDataBaseImplement.Migrations
b.HasIndex("WorkId");
b.ToTable("WorksClients", (string)null);
b.ToTable("WorksClients");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.TaskByWork", b =>
{
b.HasOne("ServiceStationsDataBaseImplement.Models.Work", "work")
.WithOne("_task")
.HasForeignKey("ServiceStationsDataBaseImplement.Models.TaskByWork", "TaskByWorkId");
b.Navigation("work");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
@ -152,12 +163,6 @@ namespace ServiceStationsDataBaseImplement.Migrations
.HasForeignKey("ExecutorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ServiceStationsDataBaseImplement.Models.TaskByWork", "_task")
.WithMany()
.HasForeignKey("_taskId");
b.Navigation("_task");
});
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.WorkClient", b =>
@ -192,6 +197,8 @@ namespace ServiceStationsDataBaseImplement.Migrations
modelBuilder.Entity("ServiceStationsDataBaseImplement.Models.Work", b =>
{
b.Navigation("WorkClients");
b.Navigation("_task");
});
#pragma warning restore 612, 618
}

View File

@ -26,7 +26,7 @@ namespace ServiceStationsDataBaseImplement.Models
public string FIO { get; set; } = string.Empty;
[ForeignKey("ExecutorId")]
public virtual List<Work> Works { get; set; } = new();
public virtual List<Work>? Works { get; set; }
public static Executor? Create(ExecutorBindingModel? model) {
if (model == null) {
@ -38,7 +38,6 @@ namespace ServiceStationsDataBaseImplement.Models
Password = model.Password,
FIO = model.FIO
};
}
public void Update(ExecutorBindingModel? model) {

View File

@ -4,6 +4,7 @@ using ServiceStationDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
@ -18,6 +19,9 @@ namespace ServiceStationsDataBaseImplement.Models {
[Required]
public double Price { get; set; }
[ForeignKey("TaskByWorkId")]
public virtual Work? work { get; set; }
public static TaskByWork? Create(TaskBindingModel? model) {
if (model == null) {
return null;

View File

@ -21,18 +21,17 @@ namespace ServiceStationsDataBaseImplement.Models
[Required]
public double Price { get; set; }
[ForeignKey("ExecutorId")]
public int ExecutorId { get; set; }
[ForeignKey("TaskId")]
public int TaskId { get; set; }
public int TaskByWorkId { get; set; }
[ForeignKey("TaskByWorkId")]
public virtual TaskByWork? _task { get; set; }
[ForeignKey("WorkId")]
public virtual List<WorkClient> WorkClients { get; set; } = new();
public Dictionary<int, IClientModel>? _clientList = null;
[NotMapped]
@ -54,7 +53,7 @@ namespace ServiceStationsDataBaseImplement.Models
Date = model.Date,
Price = model.Price,
ExecutorId = model.ExecutorId,
TaskId = model.TaskId,
TaskByWorkId = model.TaskByWorkId,
WorkClients = model.ClientList.Select(x => new WorkClient {
_client = context.Clients.First(y => y.Id == x.Key),
PointCount = 0
@ -74,16 +73,16 @@ namespace ServiceStationsDataBaseImplement.Models
Date = Date,
Price = Price,
ExecutorId = ExecutorId,
TaskId = TaskId,
TaskByWorkId = TaskByWorkId,
ClientList = ClientList,
TaskName = _task?.Name ?? string.Empty
TaskName = _task?.Name ?? string.Empty,
};
public void UpdateClients(Database context, WorkBindingModel model) {
var worckClients = context.WorksClients.Where(rec => rec.WorkId == model.Id).ToList();
if (worckClients != null && worckClients.Count > 0) {
var _worckClients = context.WorksClients.Where(rec => rec.WorkId == model.Id).ToList();
if (_worckClients != null && _worckClients.Count > 0) {
// Нужно удалить те записи, которых нет в модели
context.WorksClients.RemoveRange(worckClients.Where(rec => !model.ClientList.ContainsKey(rec.ClientId)));
context.WorksClients.RemoveRange(_worckClients);
context.SaveChanges();
}
// получаем работу, добавляем новые записи
@ -97,6 +96,5 @@ namespace ServiceStationsDataBaseImplement.Models
}
_clientList = null;
}
}
}