Контакты, продолжение

This commit is contained in:
Olga Nemt 2023-10-12 16:33:30 +05:00
parent a48381f10f
commit 4a67c5f629
16 changed files with 17850 additions and 104 deletions

View File

@ -12,9 +12,22 @@ namespace AsbCloudApp.Data.User
/// <inheritdoc/>
public int Id { get; set; }
/// <summary>
/// ключ типа компании
/// </summary>
[Required]
public int IdCompanyType { get; set; }
/// <summary>
/// ключ скважины
/// </summary>
[Required]
public int IdWell { get; set; }
/// <summary>
/// ФИО
/// </summary>
[Required]
[StringLength(260, MinimumLength = 0, ErrorMessage = "Допустимая длина ФИО от 1 до 260 символов")]
public string FIO { get; set; } = null!;
@ -28,25 +41,23 @@ namespace AsbCloudApp.Data.User
/// <summary>
/// Phone
/// </summary>
[Required]
[StringLength(50, MinimumLength = 1, ErrorMessage = "Допустимая длина телефона от 1 до 50 символов")]
public string? Phone { get; set; }
public string Phone { get; set; } = null!;
/// <summary>
/// Должность
/// </summary>
[Required]
[StringLength(100, MinimumLength = 1, ErrorMessage = "Допустимая длина должности от 1 до 100 символов")]
public string? Position { get; set; }
public string Position { get; set; } = null;
/// <summary>
/// Id компании
/// Компания
/// </summary>
[Required]
public int IdCompany { get; set; }
/// <summary>
/// DTO компании
/// </summary>
public CompanyDto? Company { get; set; }
[StringLength(260, MinimumLength = 3, ErrorMessage = "Допустимая длина должности от 3 до 260 символов")]
public string Company { get; set; } = null!;
}
}

View File

@ -12,13 +12,22 @@ namespace AsbCloudApp.Services
public interface IWellContactService
{
/// <summary>
/// Получение пользователей по ключу скважины и типу контакта
/// Получение контактов по ключу скважины и типу контакта
/// </summary>
/// <param name="wellId">ключ скважины</param>
/// <param name="idWell">ключ скважины</param>
/// <param name="contactTypeId">тип контакта</param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<CompanyWithContactsDto>> GetAsync(int wellId, int contactTypeId, CancellationToken token);
Task<IEnumerable<ContactDto>> GetAllAsync(int idWell, int contactTypeId, CancellationToken token);
/// <summary>
/// Получение пользователя по ключу
/// </summary>
/// <param name="idWell">ключ скважины</param>
/// <param name="id">тип пользователя</param>
/// <param name="token"></param>
/// <returns></returns>
Task<ContactDto?> GetAsync(int idWell, int id, CancellationToken token);
/// <summary>
/// Получение типов контактов
@ -37,13 +46,19 @@ namespace AsbCloudApp.Services
Task<int> InsertAsync(ContactDto contactDto, CancellationToken token);
/// <summary>
/// Обновление контактов по ключу скважины, типу контакта и ключам пользователей
/// Изменение контакта
/// </summary>
/// <param name="idWell">ключ скважины</param>
/// <param name="contactTypeId">ключ типа контакта</param>
/// <param name="userIds">ключи пользователей</param>
/// <param name="contactDto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> UpdateRangeAsync(int idWell, int contactTypeId, IEnumerable<int> userIds, CancellationToken token);
Task<int> UpdateAsync(ContactDto contactDto, CancellationToken token);
/// <summary>
/// Удаление контакта
/// </summary>
/// <param name="id">ключ скважины</param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> DeleteAsync(int id, CancellationToken token);
}
}

View File

@ -13,7 +13,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace AsbCloudDb.Migrations
{
[DbContext(typeof(AsbCloudDbContext))]
[Migration("20231009052848_Add_Contacts")]
[Migration("20231012063505_Add_Contacts")]
partial class Add_Contacts
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -165,6 +165,13 @@ namespace AsbCloudDb.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Company")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("company")
.HasComment("компания");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(255)
@ -179,17 +186,21 @@ namespace AsbCloudDb.Migrations
.HasColumnName("fio")
.HasComment("ФИО");
b.Property<int>("IdCompany")
b.Property<int>("IdCompanyType")
.HasMaxLength(255)
.HasColumnType("integer")
.HasColumnName("id_company");
.HasColumnName("id_company_type")
.HasComment("вид деятельности");
b.Property<string>("Phone")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("phone")
.HasComment("номер телефона");
b.Property<string>("Position")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("position")
@ -197,7 +208,7 @@ namespace AsbCloudDb.Migrations
b.HasKey("Id");
b.HasIndex("IdCompany");
b.HasIndex("IdCompanyType");
b.ToTable("t_contact");
@ -7771,13 +7782,13 @@ namespace AsbCloudDb.Migrations
modelBuilder.Entity("AsbCloudDb.Model.Contact", b =>
{
b.HasOne("AsbCloudDb.Model.Company", "Company")
b.HasOne("AsbCloudDb.Model.CompanyType", "CompanyType")
.WithMany("Contacts")
.HasForeignKey("IdCompany")
.HasForeignKey("IdCompanyType")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Company");
b.Navigation("CompanyType");
});
modelBuilder.Entity("AsbCloudDb.Model.DailyReport.DailyReport", b =>
@ -8599,8 +8610,6 @@ namespace AsbCloudDb.Migrations
modelBuilder.Entity("AsbCloudDb.Model.Company", b =>
{
b.Navigation("Contacts");
b.Navigation("RelationCompaniesWells");
b.Navigation("Users");
@ -8609,6 +8618,8 @@ namespace AsbCloudDb.Migrations
modelBuilder.Entity("AsbCloudDb.Model.CompanyType", b =>
{
b.Navigation("Companies");
b.Navigation("Contacts");
});
modelBuilder.Entity("AsbCloudDb.Model.Deposit", b =>

View File

@ -15,28 +15,29 @@ namespace AsbCloudDb.Migrations
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
id_company = table.Column<int>(type: "integer", nullable: false),
id_company_type = table.Column<int>(type: "integer", maxLength: 255, nullable: false, comment: "вид деятельности"),
fio = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false, comment: "ФИО"),
email = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false, comment: "email"),
phone = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true, comment: "номер телефона"),
position = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: true, comment: "должность")
phone = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false, comment: "номер телефона"),
position = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false, comment: "должность"),
company = table.Column<string>(type: "character varying(255)", maxLength: 255, nullable: false, comment: "компания")
},
constraints: table =>
{
table.PrimaryKey("PK_t_contact", x => x.id);
table.ForeignKey(
name: "FK_t_contact_t_company_id_company",
column: x => x.id_company,
principalTable: "t_company",
name: "FK_t_contact_t_company_type_id_company_type",
column: x => x.id_company_type,
principalTable: "t_company_type",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
},
comment: "Контакты");
migrationBuilder.CreateIndex(
name: "IX_t_contact_id_company",
name: "IX_t_contact_id_company_type",
table: "t_contact",
column: "id_company");
column: "id_company_type");
}
protected override void Down(MigrationBuilder migrationBuilder)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_Permission_Delete_To_Well_Contact : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.InsertData(
table: "t_permission",
columns: new[] { "id", "description", "name" },
values: new object[] { 528, "Разрешение на удаление контакта", "WellContact.delete" });
migrationBuilder.InsertData(
table: "t_relation_user_role_permission",
columns: new[] { "id_permission", "id_user_role" },
values: new object[] { 528, 1 });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "t_relation_user_role_permission",
keyColumns: new[] { "id_permission", "id_user_role" },
keyValues: new object[] { 528, 1 });
migrationBuilder.DeleteData(
table: "t_permission",
keyColumn: "id",
keyValue: 528);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,49 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AsbCloudDb.Migrations
{
public partial class Add_Well_To_Contacts : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "id_well",
table: "t_contact",
type: "integer",
maxLength: 255,
nullable: false,
defaultValue: 0,
comment: "ключ скважины");
migrationBuilder.CreateIndex(
name: "IX_t_contact_id_well",
table: "t_contact",
column: "id_well");
migrationBuilder.AddForeignKey(
name: "FK_t_contact_t_well_id_well",
table: "t_contact",
column: "id_well",
principalTable: "t_well",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_t_contact_t_well_id_well",
table: "t_contact");
migrationBuilder.DropIndex(
name: "IX_t_contact_id_well",
table: "t_contact");
migrationBuilder.DropColumn(
name: "id_well",
table: "t_contact");
}
}
}

View File

@ -163,6 +163,13 @@ namespace AsbCloudDb.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Company")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("company")
.HasComment("компания");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(255)
@ -177,17 +184,27 @@ namespace AsbCloudDb.Migrations
.HasColumnName("fio")
.HasComment("ФИО");
b.Property<int>("IdCompany")
b.Property<int>("IdCompanyType")
.HasMaxLength(255)
.HasColumnType("integer")
.HasColumnName("id_company");
.HasColumnName("id_company_type")
.HasComment("вид деятельности");
b.Property<int>("IdWell")
.HasMaxLength(255)
.HasColumnType("integer")
.HasColumnName("id_well")
.HasComment("ключ скважины");
b.Property<string>("Phone")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("phone")
.HasComment("номер телефона");
b.Property<string>("Position")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("character varying(255)")
.HasColumnName("position")
@ -195,7 +212,9 @@ namespace AsbCloudDb.Migrations
b.HasKey("Id");
b.HasIndex("IdCompany");
b.HasIndex("IdCompanyType");
b.HasIndex("IdWell");
b.ToTable("t_contact");
@ -2328,6 +2347,12 @@ namespace AsbCloudDb.Migrations
Id = 527,
Description = "Разрешение на удаление инструкций",
Name = "Manual.delete"
},
new
{
Id = 528,
Description = "Разрешение на удаление контакта",
Name = "WellContact.delete"
});
});
@ -3990,6 +4015,11 @@ namespace AsbCloudDb.Migrations
{
IdUserRole = 1,
IdPermission = 527
},
new
{
IdUserRole = 1,
IdPermission = 528
});
});
@ -7769,13 +7799,21 @@ namespace AsbCloudDb.Migrations
modelBuilder.Entity("AsbCloudDb.Model.Contact", b =>
{
b.HasOne("AsbCloudDb.Model.Company", "Company")
b.HasOne("AsbCloudDb.Model.CompanyType", "CompanyType")
.WithMany("Contacts")
.HasForeignKey("IdCompany")
.HasForeignKey("IdCompanyType")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Company");
b.HasOne("AsbCloudDb.Model.Well", "Well")
.WithMany("Contacts")
.HasForeignKey("IdWell")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CompanyType");
b.Navigation("Well");
});
modelBuilder.Entity("AsbCloudDb.Model.DailyReport.DailyReport", b =>
@ -8597,8 +8635,6 @@ namespace AsbCloudDb.Migrations
modelBuilder.Entity("AsbCloudDb.Model.Company", b =>
{
b.Navigation("Contacts");
b.Navigation("RelationCompaniesWells");
b.Navigation("Users");
@ -8607,6 +8643,8 @@ namespace AsbCloudDb.Migrations
modelBuilder.Entity("AsbCloudDb.Model.CompanyType", b =>
{
b.Navigation("Companies");
b.Navigation("Contacts");
});
modelBuilder.Entity("AsbCloudDb.Model.Deposit", b =>
@ -8688,6 +8726,8 @@ namespace AsbCloudDb.Migrations
modelBuilder.Entity("AsbCloudDb.Model.Well", b =>
{
b.Navigation("Contacts");
b.Navigation("DrillingProgramParts");
b.Navigation("ProcessMaps");

View File

@ -29,8 +29,5 @@ namespace AsbCloudDb.Model
[InverseProperty(nameof(RelationCompanyWell.Company))]
public virtual ICollection<RelationCompanyWell> RelationCompaniesWells { get; set; } = null!;
[InverseProperty(nameof(Contact.Company))]
public virtual ICollection<Contact> Contacts { get; set; } = null!;
}
}

View File

@ -21,5 +21,8 @@ namespace AsbCloudDb.Model
[InverseProperty(nameof(Company.CompanyType))]
public virtual ICollection<Company> Companies { get; set; } = null!;
[InverseProperty(nameof(Contact.CompanyType))]
public virtual ICollection<Contact> Contacts { get; set; } = null!;
}
}

View File

@ -12,8 +12,13 @@ namespace AsbCloudDb.Model
[Column("id")]
public int Id { get; set; }
[Column("id_company")]
public int IdCompany { get; set; }
[Column("id_company_type"), Comment("вид деятельности")]
[StringLength(255)]
public int IdCompanyType { get; set; }
[Column("id_well"), Comment("ключ скважины")]
[StringLength(255)]
public int IdWell { get; set; }
[Column("fio"), Comment("ФИО")]
[StringLength(255)]
@ -25,14 +30,22 @@ namespace AsbCloudDb.Model
[Column("phone"), Comment("номер телефона")]
[StringLength(50)]
public string? Phone { get; set; }
public string Phone { get; set; } = string.Empty;
[Column("position"), Comment("должность")]
[StringLength(255)]
public string? Position { get; set; }
public string Position { get; set; } = string.Empty;
[ForeignKey(nameof(IdCompany))]
[InverseProperty(nameof(Model.Company.Contacts))]
public virtual Company Company { get; set; } = null!;
[Column("company"), Comment("компания")]
[StringLength(255)]
public string Company { get; set; } = string.Empty;
[ForeignKey(nameof(IdCompanyType))]
[InverseProperty(nameof(Model.CompanyType.Contacts))]
public virtual CompanyType CompanyType { get; set; } = null!;
[ForeignKey(nameof(IdWell))]
[InverseProperty(nameof(Model.Well.Contacts))]
public virtual Well Well { get; set; } = null!;
}
}

View File

@ -163,7 +163,8 @@
new (){ Id = 525, Name = "ProcessMap.editCompletedWell", Description = "Разрешение на редактирование РТК у завершенной скважины"},
new (){ Id = 526, Name = "WellOperation.editCompletedWell", Description = "Разрешение на редактирование операций у завершенной скважины"},
new() { Id = 527, Name = "Manual.delete", Description = "Разрешение на удаление инструкций"}
new() { Id = 527, Name = "Manual.delete", Description = "Разрешение на удаление инструкций"},
new (){ Id = 528, Name="WellContact.delete", Description="Разрешение на удаление контакта"},
};
}
}

View File

@ -68,5 +68,8 @@ namespace AsbCloudDb.Model
[InverseProperty(nameof(ProcessMap.Well))]
public virtual ICollection<ProcessMap> ProcessMaps { get; set; } = null!;
[InverseProperty(nameof(Contact.Well))]
public virtual ICollection<Contact> Contacts { get; set; } = null!;
}
}

View File

@ -1,7 +1,9 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.User;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using DocumentFormat.OpenXml.Office2019.Excel.RichData2;
using Mapster;
using Microsoft.EntityFrameworkCore;
using System;
@ -21,19 +23,12 @@ namespace AsbCloudInfrastructure.Services
this.db = db;
}
public async Task<IEnumerable<CompanyWithContactsDto>> GetAsync(int wellId, int contactTypeId, CancellationToken token)
public async Task<IEnumerable<ContactDto>> GetAllAsync(int wellId, int contactTypeId, CancellationToken token)
{
var query = db.Companies
var query = db.Contacts
.Where(c => c.IdCompanyType == contactTypeId)
.Where(c => c.RelationCompaniesWells.Any(rc => rc.IdWell == wellId))
.Select(c => new CompanyWithContactsDto()
{
Caption = c.Caption,
Id = c.Id,
Contacts = c.Contacts
.OrderBy(u => u.FIO)
.Select(u => u.Adapt<ContactDto>())
});
.Where(c => c.IdWell == wellId)
.Select(c => c.Adapt<ContactDto>());
var entities = await query.AsNoTracking()
.ToArrayAsync(token)
@ -42,11 +37,19 @@ namespace AsbCloudInfrastructure.Services
return entities;
}
public async Task<ContactDto?> GetAsync(int idWell, int id, CancellationToken token)
{
var dbContact = await CheckMembershipContactToWell(idWell, id, token);
var result = dbContact?.Adapt<ContactDto>();
return result;
}
public async Task<IEnumerable<CompanyTypeDto>> GetTypesAsync(int idWell, CancellationToken token)
{
var query = db.CompaniesTypes
.Where(t => t.IsContact)
.Where(t => t.Companies.Any(c => c.Users.Any() && c.RelationCompaniesWells.Any(w => w.IdWell == idWell)))
.OrderBy(t => t.Order);
var entities = await query.AsNoTracking()
@ -61,36 +64,46 @@ namespace AsbCloudInfrastructure.Services
public async Task<int> InsertAsync(ContactDto contactDto, CancellationToken token)
{
var entity = contactDto.Adapt<Contact>();
//var entity = new Contact()
//{
// Email = contactDto.Email,
// FIO = contactDto.FIO,
// IdCompany = contactDto.IdCompany,
// Phone = contactDto.Phone,
// Position = contactDto.Position
//};
db.Contacts.Add(entity);
await db.SaveChangesAsync(token).ConfigureAwait(false);
return entity.Id;
}
public async Task<int> UpdateRangeAsync(int idWell, int contactTypeId, IEnumerable<int> userIds, CancellationToken token)
{
var items = db.RelationContactsWells
.Where(x => x.IdWell == idWell && x.User.Company.IdCompanyType == contactTypeId);
var wellContacts = userIds.Select(userId => new RelationContactWell()
public async Task<int> UpdateAsync(ContactDto contactDto, CancellationToken token)
{
IdWell = idWell,
IdUser = userId,
});
db.RelationContactsWells.RemoveRange(items);
db.RelationContactsWells.AddRange(wellContacts);
var entity = contactDto.Adapt<Contact>();
db.Contacts.Update(entity);
return await db.SaveChangesAsync(token)
.ConfigureAwait(false);
}
public async Task<int> DeleteAsync(int id, CancellationToken token)
{
var contact = await db.Contacts
.Where(c => c.Id == id)
.FirstOrDefaultAsync(token)
.ConfigureAwait(false);
if (contact is null)
throw new ForbidException("Contact doesn't exist");
db.Contacts.Remove(contact);
return await db.SaveChangesAsync(token);
}
private async Task<Contact?> CheckMembershipContactToWell(int idWell, int idContact, CancellationToken token)
{
var contact = await db.Contacts
.Where(c => c.IdWell == idWell)
.Where(c => c.Id == idContact)
.FirstOrDefaultAsync(token)
.ConfigureAwait(false);
return contact;
}
}
}

View File

@ -1,8 +1,11 @@
using AsbCloudApp.Data;
using AsbCloudApp.Data.User;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
@ -44,20 +47,38 @@ namespace AsbCloudWebApi.Controllers
}
/// <summary>
/// Получение пользователей по типу контакта и ключу скважины
/// Получение контактов по типу контакта и ключу скважины
/// </summary>
/// <param name="idWell">ключ скважины</param>
/// <param name="contactTypeId">тип контакта</param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("api/well/{idWell}/contactType/{contactTypeId}")]
[ProducesResponseType(typeof(IEnumerable<CompanyWithContactsDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetAsync(int idWell, int contactTypeId, CancellationToken token)
[ProducesResponseType(typeof(IEnumerable<ContactDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetAllAsync(int idWell, int contactTypeId, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = await wellContactsRepository.GetAsync(idWell, contactTypeId, token).ConfigureAwait(false);
var result = await wellContactsRepository.GetAllAsync(idWell, contactTypeId, token).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Получение контакта по ключу
/// </summary>
/// <param name="idWell">ключ скважины</param>
/// <param name="id">ключ контакта</param>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet("api/well/{idWell}/contact/{id}")]
[ProducesResponseType(typeof(IEnumerable<ContactDto>), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> GetAsync(int idWell, int id, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = await wellContactsRepository.GetAsync(idWell, id, token).ConfigureAwait(false);
return Ok(result);
}
@ -68,39 +89,68 @@ namespace AsbCloudWebApi.Controllers
/// <param name="token"></param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(typeof(ContactDto), (int)System.Net.HttpStatusCode.OK)]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<IActionResult> InsertAsync(
[FromBody] ContactDto contactDto,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(contactDto.IdWell, token).ConfigureAwait(false))
return Forbid();
var result = await wellContactsRepository.InsertAsync(contactDto, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// изменение контакта
/// </summary>
/// <param name="contactDto">контакт</param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPut]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<IActionResult> UpdateAsync(
[FromBody] ContactDto contactDto,
CancellationToken token)
{
if (!await CanUserAccessToWellAsync(contactDto.IdWell, token).ConfigureAwait(false))
return Forbid();
var result = await wellContactsRepository.UpdateAsync(contactDto, token)
.ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Создание контактов по ключу скважины, типу контакта и ключам пользователей
/// Удаление контакта
/// </summary>
/// <param name="idWell">ключ скважины</param>
/// <param name="contactTypeId">ключ типа контакта</param>
/// <param name="userIds">ключи пользователей</param>
/// <param name="token"></param>
/// <returns></returns>
[HttpPost("api/well/{idWell}/contactType/{contactTypeId}")]
/// <param name="id">id контакта</param>
/// <param name="token">Токен отмены задачи</param>
/// <returns>Количество удаленных из БД строк</returns>
[HttpDelete("api/well/{idWell}/contact/{id}")]
[Permission]
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
public async Task<IActionResult> UpdateRangeAsync(
[Range(1, int.MaxValue, ErrorMessage = "Id скважины не может быть меньше 1")] int idWell,
[Range(1, int.MaxValue, ErrorMessage = "Id типа контакта не может быть меньше 1")] int contactTypeId,
[FromBody] IEnumerable<int> userIds,
CancellationToken token)
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<IActionResult> DeleteAsync(int idWell, int id, CancellationToken token)
{
if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
return Forbid();
var result = await wellContactsRepository.UpdateRangeAsync(idWell, contactTypeId, userIds, token).ConfigureAwait(false);
var result = await wellContactsRepository.DeleteAsync(id, token)
.ConfigureAwait(false);
return Ok(result);
}
@ -109,6 +159,8 @@ namespace AsbCloudWebApi.Controllers
int? idCompany = User.GetCompanyId();
return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
idWell, token).ConfigureAwait(false);
}
}