Save DataSet

This commit is contained in:
2022-12-21 18:35:26 +01:00
parent db13b1ab1b
commit 0f28e18ed2
13 changed files with 359 additions and 40 deletions

View File

@@ -34,6 +34,23 @@ mat-form-field {
.load {
text-align: center;
}
.loading-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgba(100, 100, 100, 0.3);
z-index: 1400;
}
.loading-img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
/* for mobile */
@media screen and (max-width: 700px) {
.container {

View File

@@ -19,6 +19,10 @@ export class DataSet extends Base {
Object.assign(this, Object.assign(this, super.deserialize(input)));
return this;
}
override serialize() {
this.number = 0; // will be overrided in backend
return Object.assign({}, this);
}
static getForm(fb: UntypedFormBuilder) {
return fb.group({
id: [null],
@@ -44,27 +48,16 @@ export class DataSet extends Base {
this.createdBy = undefined;
this.modifiedBy = undefined;
}
//API Actions
/*
static add(input: Account, _http: HttpClient, _data: DataService): Promise<string> {
//API Actions
static add(input: DataSet, _http: HttpClient): Promise<string> {
return new Promise((resolve, reject) => {
_http.post<string>(`${environment.api.url}/accounts`, {...input.serialize(), modifiedById: _data.currentUser.id }).subscribe({
_http.post<string>(`${environment.api.url}/datasets`, {...input.serialize(), }).subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
}
);
});
}
static update(input: Account, _http: HttpClient, _data: DataService): Promise<string> {
return new Promise((resolve, reject) => {
_http.patch<string>(`${environment.api.url}/accounts`, {...input.serialize(), modifiedById: _data.currentUser.id }).subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
}
);
});
}
*/
static getList(_http: HttpClient): any {
return new Promise((resolve, reject) => {
_http.get<DataSet[]>(`${environment.api.url}/datasets`)
@@ -75,7 +68,6 @@ export class DataSet extends Base {
})
});
}
static getById(id: string, _http: HttpClient): Promise<DataSet> {
return new Promise((resolve, reject) => {
_http.get<DataSet>(`${environment.api.url}/datasets/${id}`).pipe(map(x => new DataSet().deserialize(x))).subscribe({
@@ -98,14 +90,4 @@ export class DataSet extends Base {
})
})
}
/*
static delete(id: string, _http: HttpClient): Promise<string> {
return new Promise((resolve, reject)=> {
_http.delete<string>(`${environment.api.url}/accounts/${id}`).subscribe({
next: (data) => resolve(data),
error: (e) => reject(e)
})
});
}
*/
}

View File

@@ -59,16 +59,9 @@ export class DataSetEditComponent implements OnInit {
if (this.form.invalid) {
return;
}
/*
this.document.loadForm(this.form);
let id;
if (this.route$.snapshot.paramMap.get('id') === 'new') {
id = await DataSet.add(this.document, this.http$, this._data);
} else {
id = await DataSet.update(this.document, this._http, this._data);
}
this._router.navigate(['../../Detail', id], { relativeTo: this._route});
*/
const id = await DataSet.add(this.document, this.http$);
// this._router.navigate(['../../Detail', id], { relativeTo: this._route});
}
generateNumber() {
this.form.patchValue({

View File

@@ -23,9 +23,14 @@
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Źródło</mat-header-cell>
<mat-header-cell *matHeaderCellDef mat-sort-header>Nazwa</mat-header-cell>
<mat-cell *matCellDef="let item">{{item.name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="source">
<mat-header-cell *matHeaderCellDef mat-sort-header>Źródło</mat-header-cell>
<mat-cell *matCellDef="let item">{{item.source}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let item; columns: displayedColumns;" [routerLink]="['Detail/', item.id]"></mat-row>

View File

@@ -11,7 +11,7 @@ import { DataSet } from 'src/app/models/dataSet.model';
styleUrls: ['./data-sets-list.component.scss']
})
export class DataSetsListComponent implements OnInit {
displayedColumns = ['number', 'name'];
displayedColumns = ['number', 'name', 'source'];
dataSource!: MatTableDataSource<DataSet>;
@ViewChild(MatPaginator) paginator!: MatPaginator;

View File

@@ -53,7 +53,7 @@ namespace WebAPI.Controllers
Subject = new ClaimsIdentity(new[]
{
new Claim("Id", Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Jti,
Guid.NewGuid().ToString())
}),

View File

@@ -35,6 +35,19 @@ namespace WebAPI.Controllers
}
}
[HttpPost]
public IActionResult Save(DataSet input)
{
try
{
Request.Headers.TryGetValue("userId", out var value);
Guid currentUserId = new Guid(value);
return Ok(AddDataSet(input, currentUserId).Id);
} catch(Exception e)
{
return BadRequest(e.ToString());
}
}
[HttpPost]
[DisableRequestSizeLimit]
[Route("parseFile")]
public IActionResult ParseFile()
@@ -42,5 +55,42 @@ namespace WebAPI.Controllers
var parser = new csvParser();
return Ok(parser.parse(Request.Form.Files[0]));
}
//
private DataSet AddDataSet(DataSet input, Guid currentUserId)
{
input.Number = db.DataSets.Count() + 1;
input.CreatedById = currentUserId;
input.ModifiedById = currentUserId;
input.CreatedAt = DateTime.UtcNow;
input.ModifiedAt = DateTime.UtcNow;
db.DataSets.Add(input);
SaveDataRows(input.Id, input.DataRows, currentUserId);
db.SaveChanges();
return input;
}
private void SaveDataRows(Guid id, ICollection<Models.DataRow> dataRows, Guid currentUserId)
{
try
{
List<Guid> ids = new List<Guid>();
foreach (Models.DataRow dataRow in dataRows)
{
dataRow.CreatedById = currentUserId;
dataRow.CreatedAt = DateTime.UtcNow;
dataRow.ModifiedById = currentUserId;
dataRow.ModifiedAt = DateTime.UtcNow;
dataRow.DataSetId= id;
db.DataRows.Add(dataRow);
}
}
catch (Exception)
{
throw;
}
}
}
}

View File

@@ -0,0 +1,199 @@
// <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 WebAPI;
#nullable disable
namespace WebAPI.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20221221165749_DataSetIdOnDataRow")]
partial class DataSetIdOnDataRow
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc2")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc3")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc4")
.HasColumnType("nvarchar(max)");
b.Property<string>("Desc5")
.HasColumnType("nvarchar(max)");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<float>("Value")
.HasColumnType("real");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("DataSetId");
b.HasIndex("ModifiedById");
b.ToTable("DataRows");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<bool>("IsDeleted")
.HasColumnType("bit");
b.Property<DateTime>("ModifiedAt")
.HasColumnType("datetime2");
b.Property<Guid>("ModifiedById")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("Number")
.IsRequired()
.HasColumnType("int");
b.Property<string>("Source")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("CreatedById");
b.HasIndex("ModifiedById");
b.ToTable("DataSets");
});
modelBuilder.Entity("WebAPI.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime2");
b.Property<string>("Email")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserName")
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("WebAPI.Models.DataRow", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.HasOne("WebAPI.Models.User", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()
.HasForeignKey("ModifiedById")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
b.Navigation("ModifiedBy");
});
modelBuilder.Entity("WebAPI.Models.DataSet", b =>
{
b.Navigation("DataRows");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace WebAPI.Migrations
{
/// <inheritdoc />
public partial class DataSetIdOnDataRow : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows");
migrationBuilder.AlterColumn<Guid>(
name: "DataSetId",
table: "DataRows",
type: "uniqueidentifier",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"),
oldClrType: typeof(Guid),
oldType: "uniqueidentifier",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows",
column: "DataSetId",
principalTable: "DataSets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows");
migrationBuilder.AlterColumn<Guid>(
name: "DataSetId",
table: "DataRows",
type: "uniqueidentifier",
nullable: true,
oldClrType: typeof(Guid),
oldType: "uniqueidentifier");
migrationBuilder.AddForeignKey(
name: "FK_DataRows_DataSets_DataSetId",
table: "DataRows",
column: "DataSetId",
principalTable: "DataSets",
principalColumn: "Id");
}
}
}

View File

@@ -38,7 +38,7 @@ namespace WebAPI.Migrations
b.Property<Guid>("CreatedById")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("DataSetId")
b.Property<Guid>("DataSetId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Desc1")
@@ -152,7 +152,9 @@ namespace WebAPI.Migrations
b.HasOne("WebAPI.Models.DataSet", null)
.WithMany("DataRows")
.HasForeignKey("DataSetId");
.HasForeignKey("DataSetId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("WebAPI.Models.User", "ModifiedBy")
.WithMany()

View File

@@ -28,6 +28,7 @@ namespace WebAPI.Models
[Required]
public Guid ModifiedById { get; set; }
public User? ModifiedBy { get; set; }
public Guid DataSetId { get; set; }
#endregion
}
}

View File

@@ -1,6 +1,8 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using WebAPI;
@@ -42,6 +44,7 @@ builder.Services.AddAuthentication(options =>
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Secret"]))
};
});
builder.Services.AddAuthorization();
@@ -54,7 +57,12 @@ var app = builder.Build();
app.Use(async (context, next) =>
{
context.Request.Headers.TryGetValue("Authorization", out var auth);
string token = context.Request.Headers["Authorization"].ToString();
if (token.Length > 0) {
var handler = new JwtSecurityTokenHandler();
var data = handler.ReadJwtToken(token.Split(' ')[1]);
context.Request.Headers.Add("UserId", new Microsoft.Extensions.Primitives.StringValues(data.Subject));
}
await next(context);
});

View File

@@ -37,6 +37,8 @@ namespace WebAPI.dataParsers
dataRow.Code = data[0][i];
dataRow.Desc1 = data[j][0];
dataRow.Value = value;
dataRow.CreatedAt = DateTime.UtcNow;
dataRow.ModifiedAt= DateTime.UtcNow;
dataRows.Add(dataRow);
}
}