This commit is contained in:
2023-07-20 21:38:05 +03:00
parent 4bac59f322
commit 2f108bef4f
35 changed files with 1863 additions and 909 deletions
+2 -2
View File
@@ -13,8 +13,8 @@ public class Item
/// UnCategorized category is CategoryId = UserId /// UnCategorized category is CategoryId = UserId
/// </summary> /// </summary>
public Guid CategoryId { get; set; } public Guid CategoryId { get; set; }
public ItemCategory Category { get; set; } = null!; public ItemCategory? Category { get; set; }
public Guid ItemGlobalId { get; set; } public Guid ItemGlobalId { get; set; }
public ItemGlobal ItemGlobal { get; set; } = null!; public ItemGlobal ItemGlobal { get; set; } = null!;
public IEnumerable<Motion> Motions { get; set; } = null!; public List<Motion>? Motions { get; set; }
} }
+2 -1
View File
@@ -8,5 +8,6 @@ public class ItemCategory
public Guid UserId { get; set; } public Guid UserId { get; set; }
public User User { get; set; } = null!; public User User { get; set; } = null!;
public string Name { get; set; } = null!; public string Name { get; set; } = null!;
public IEnumerable<Item> Items { get; set; } = null!; public List<Item> Items { get; set; } = null!;
public bool IsInternal { get; set; }
} }
@@ -90,4 +90,12 @@ public class AccountRepository : AppRepository<Account>, IAccountRepository
{ {
return RemoveBase(account) > 0; return RemoveBase(account) > 0;
} }
public List<Account> FindAccounts(Guid userId, string term)
{
return _context.Accounts
.Where(x => x.AccessRights.Any(a => a.UserId == userId))
.Where(x => x.Name.Contains(term))
.ToList();
}
} }
@@ -12,4 +12,5 @@ public interface IAccountRepository
Account? Get(Guid userId, Guid id); Account? Get(Guid userId, Guid id);
bool Update(Account account); bool Update(Account account);
bool Remove(Account account); bool Remove(Account account);
List<Account> FindAccounts(Guid userId, string term);
} }
@@ -10,4 +10,5 @@ public interface IItemRepository
Item? GetByGlobal(Guid userId, Guid globalMotionId); Item? GetByGlobal(Guid userId, Guid globalMotionId);
bool Add(Item item); bool Add(Item item);
bool Update(Item item); bool Update(Item item);
List<Item> Find(Guid userId, string term, int limit);
} }
@@ -31,7 +31,7 @@ public class ItemRepository : AppRepository<Item>, IItemRepository
.Include(x => x.Motions) .Include(x => x.Motions)
.Include(x => x.Category) .Include(x => x.Category)
.Include(x => x.ItemGlobal) .Include(x => x.ItemGlobal)
.FirstOrDefault(x => x.Category.UserId == userId && x.ItemGlobalId == globalMotionId); .FirstOrDefault(x => x.Category!.UserId == userId && x.ItemGlobalId == globalMotionId);
} }
public bool Update(Item item) public bool Update(Item item)
@@ -43,4 +43,15 @@ public class ItemRepository : AppRepository<Item>, IItemRepository
{ {
return base.AddBase(item) > 0; return base.AddBase(item) > 0;
} }
public List<Item> Find(Guid userId, string term, int limit)
{
return _context
.Items
.Include(x => x.ItemGlobal)
.Where(x => x.Category!.UserId == userId && x.ItemGlobal.Name.Contains(term))
.OrderByDescending(x => x.Motions.Count())
.Take(limit)
.ToList();
}
} }
@@ -0,0 +1,611 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MyOffice.DbContext;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace MyOffice.Migrations.Postgres.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20230627044606_IsInternal")]
partial class IsInternal
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:CollationDefinition:my_ci_collation", "en-u-ks-primary,en-u-ks-primary,icu,False")
.HasAnnotation("ProductVersion", "7.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("MyOffice.Data.Models.Accounts.Account", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CurrencyGlobalId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("CurrencyGlobalId");
b.ToTable("Accounts");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.AccountAccess", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<bool>("IsAllowManage")
.HasColumnType("boolean");
b.Property<bool>("IsAllowRead")
.HasColumnType("boolean");
b.Property<bool>("IsAllowWrite")
.HasColumnType("boolean");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("UserId");
b.ToTable("AccountAccesses");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.AccountAccountCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<Guid>("CategoryId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("CategoryId");
b.ToTable("AccountAccountCategories");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.AccountCategory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AccountCategories");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.Motion", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AccountId")
.HasColumnType("uuid");
b.Property<decimal>("AmountMinus")
.HasPrecision(18, 6)
.HasColumnType("numeric(18,6)");
b.Property<decimal>("AmountPlus")
.HasPrecision(18, 6)
.HasColumnType("numeric(18,6)");
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("DateTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<int>("ItemId")
.HasColumnType("integer");
b.Property<Guid?>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("ItemId");
b.HasIndex("UserId");
b.ToTable("Motions");
});
modelBuilder.Entity("MyOffice.Data.Models.Currencies.Currency", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CurrencyGlobalId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ShortName")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("CurrencyGlobalId");
b.HasIndex("UserId");
b.ToTable("Currencies");
});
modelBuilder.Entity("MyOffice.Data.Models.Currencies.CurrencyGlobal", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("DefaultQuantity")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Symbol")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("CurrencyGlobals");
});
modelBuilder.Entity("MyOffice.Data.Models.Currencies.CurrencyRate", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<Guid>("CurrencyId")
.HasColumnType("uuid");
b.Property<DateTime>("DateTime")
.HasColumnType("timestamp with time zone");
b.Property<int>("Quantity")
.HasColumnType("integer");
b.Property<decimal>("Rate")
.HasColumnType("numeric");
b.HasKey("Id");
b.HasIndex("CurrencyId");
b.ToTable("CurrencyRates");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.Item", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<Guid>("CategoryId")
.HasColumnType("uuid");
b.Property<Guid>("ItemGlobalId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("ItemGlobalId");
b.ToTable("Items");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.ItemCategory", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<bool>("IsInternal")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("ItemCategories");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.ItemGlobal", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("ItemGlobals");
});
modelBuilder.Entity("MyOffice.Data.Models.Users.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CurrencyId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text")
.UseCollation("my_ci_collation");
b.Property<string>("FirstName")
.HasColumnType("text");
b.Property<string>("FullName")
.HasColumnType("text");
b.Property<bool>("IsEmailConfirmed")
.HasColumnType("boolean");
b.Property<string>("LastName")
.HasColumnType("text");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Phone")
.HasColumnType("text");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("text")
.UseCollation("my_ci_collation");
b.HasKey("Id");
b.HasIndex("CurrencyId");
b.ToTable("Users");
});
modelBuilder.Entity("MyOffice.Data.Models.Users.UserExternal", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp with time zone");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text")
.UseCollation("my_ci_collation");
b.Property<string>("ExternalId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Provider")
.IsRequired()
.HasColumnType("text")
.UseCollation("my_ci_collation");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("UserClaims");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.Account", b =>
{
b.HasOne("MyOffice.Data.Models.Currencies.CurrencyGlobal", "CurrencyGlobal")
.WithMany("Accounts")
.HasForeignKey("CurrencyGlobalId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CurrencyGlobal");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.AccountAccess", b =>
{
b.HasOne("MyOffice.Data.Models.Accounts.Account", "Account")
.WithMany("AccessRights")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MyOffice.Data.Models.Users.User", "User")
.WithMany("AccountAccess")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
b.Navigation("User");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.AccountAccountCategory", b =>
{
b.HasOne("MyOffice.Data.Models.Accounts.Account", "Account")
.WithMany("Categories")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MyOffice.Data.Models.Accounts.AccountCategory", "Category")
.WithMany("Accounts")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
b.Navigation("Category");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.AccountCategory", b =>
{
b.HasOne("MyOffice.Data.Models.Users.User", "User")
.WithMany("AccountCategories")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.Motion", b =>
{
b.HasOne("MyOffice.Data.Models.Accounts.Account", "Account")
.WithMany("Motions")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MyOffice.Data.Models.Items.Item", "Item")
.WithMany("Motions")
.HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MyOffice.Data.Models.Users.User", null)
.WithMany("AccountMotions")
.HasForeignKey("UserId");
b.Navigation("Account");
b.Navigation("Item");
});
modelBuilder.Entity("MyOffice.Data.Models.Currencies.Currency", b =>
{
b.HasOne("MyOffice.Data.Models.Currencies.CurrencyGlobal", "CurrencyGlobal")
.WithMany("Currencies")
.HasForeignKey("CurrencyGlobalId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MyOffice.Data.Models.Users.User", "User")
.WithMany("Currencies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CurrencyGlobal");
b.Navigation("User");
});
modelBuilder.Entity("MyOffice.Data.Models.Currencies.CurrencyRate", b =>
{
b.HasOne("MyOffice.Data.Models.Currencies.Currency", "Currency")
.WithMany("Rates")
.HasForeignKey("CurrencyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Currency");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.Item", b =>
{
b.HasOne("MyOffice.Data.Models.Items.ItemCategory", "Category")
.WithMany("Items")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MyOffice.Data.Models.Items.ItemGlobal", "ItemGlobal")
.WithMany("Items")
.HasForeignKey("ItemGlobalId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Category");
b.Navigation("ItemGlobal");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.ItemCategory", b =>
{
b.HasOne("MyOffice.Data.Models.Users.User", "User")
.WithMany("ItemCategories")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("MyOffice.Data.Models.Users.User", b =>
{
b.HasOne("MyOffice.Data.Models.Currencies.CurrencyGlobal", "Currency")
.WithMany()
.HasForeignKey("CurrencyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Currency");
});
modelBuilder.Entity("MyOffice.Data.Models.Users.UserExternal", b =>
{
b.HasOne("MyOffice.Data.Models.Users.User", "User")
.WithMany("UserClaims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.Account", b =>
{
b.Navigation("AccessRights");
b.Navigation("Categories");
b.Navigation("Motions");
});
modelBuilder.Entity("MyOffice.Data.Models.Accounts.AccountCategory", b =>
{
b.Navigation("Accounts");
});
modelBuilder.Entity("MyOffice.Data.Models.Currencies.Currency", b =>
{
b.Navigation("Rates");
});
modelBuilder.Entity("MyOffice.Data.Models.Currencies.CurrencyGlobal", b =>
{
b.Navigation("Accounts");
b.Navigation("Currencies");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.Item", b =>
{
b.Navigation("Motions");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.ItemCategory", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("MyOffice.Data.Models.Items.ItemGlobal", b =>
{
b.Navigation("Items");
});
modelBuilder.Entity("MyOffice.Data.Models.Users.User", b =>
{
b.Navigation("AccountAccess");
b.Navigation("AccountCategories");
b.Navigation("AccountMotions");
b.Navigation("Currencies");
b.Navigation("ItemCategories");
b.Navigation("UserClaims");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace MyOffice.Migrations.Postgres.Migrations
{
/// <inheritdoc />
public partial class IsInternal : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsInternal",
table: "ItemCategories",
type: "boolean",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsInternal",
table: "ItemCategories");
}
}
}
@@ -240,7 +240,7 @@ namespace MyOffice.Migrations.Postgres.Migrations
b.ToTable("CurrencyRates"); b.ToTable("CurrencyRates");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.Item", b => modelBuilder.Entity("MyOffice.Data.Models.Items.Item", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -263,12 +263,15 @@ namespace MyOffice.Migrations.Postgres.Migrations
b.ToTable("Items"); b.ToTable("Items");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.ItemCategory", b => modelBuilder.Entity("MyOffice.Data.Models.Items.ItemCategory", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("uuid"); .HasColumnType("uuid");
b.Property<bool>("IsInternal")
.HasColumnType("boolean");
b.Property<string>("Name") b.Property<string>("Name")
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
@@ -283,7 +286,7 @@ namespace MyOffice.Migrations.Postgres.Migrations
b.ToTable("ItemCategories"); b.ToTable("ItemCategories");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.ItemGlobal", b => modelBuilder.Entity("MyOffice.Data.Models.Items.ItemGlobal", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
@@ -447,7 +450,7 @@ namespace MyOffice.Migrations.Postgres.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("MyOffice.Data.Models.Motions.Item", "Item") b.HasOne("MyOffice.Data.Models.Items.Item", "Item")
.WithMany("Motions") .WithMany("Motions")
.HasForeignKey("ItemId") .HasForeignKey("ItemId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
@@ -492,15 +495,15 @@ namespace MyOffice.Migrations.Postgres.Migrations
b.Navigation("Currency"); b.Navigation("Currency");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.Item", b => modelBuilder.Entity("MyOffice.Data.Models.Items.Item", b =>
{ {
b.HasOne("MyOffice.Data.Models.Motions.ItemCategory", "Category") b.HasOne("MyOffice.Data.Models.Items.ItemCategory", "Category")
.WithMany("Items") .WithMany("Items")
.HasForeignKey("CategoryId") .HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("MyOffice.Data.Models.Motions.ItemGlobal", "ItemGlobal") b.HasOne("MyOffice.Data.Models.Items.ItemGlobal", "ItemGlobal")
.WithMany("Items") .WithMany("Items")
.HasForeignKey("ItemGlobalId") .HasForeignKey("ItemGlobalId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
@@ -511,7 +514,7 @@ namespace MyOffice.Migrations.Postgres.Migrations
b.Navigation("ItemGlobal"); b.Navigation("ItemGlobal");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.ItemCategory", b => modelBuilder.Entity("MyOffice.Data.Models.Items.ItemCategory", b =>
{ {
b.HasOne("MyOffice.Data.Models.Users.User", "User") b.HasOne("MyOffice.Data.Models.Users.User", "User")
.WithMany("ItemCategories") .WithMany("ItemCategories")
@@ -570,17 +573,17 @@ namespace MyOffice.Migrations.Postgres.Migrations
b.Navigation("Currencies"); b.Navigation("Currencies");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.Item", b => modelBuilder.Entity("MyOffice.Data.Models.Items.Item", b =>
{ {
b.Navigation("Motions"); b.Navigation("Motions");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.ItemCategory", b => modelBuilder.Entity("MyOffice.Data.Models.Items.ItemCategory", b =>
{ {
b.Navigation("Items"); b.Navigation("Items");
}); });
modelBuilder.Entity("MyOffice.Data.Models.Motions.ItemGlobal", b => modelBuilder.Entity("MyOffice.Data.Models.Items.ItemGlobal", b =>
{ {
b.Navigation("Items"); b.Navigation("Items");
}); });
+1
View File
@@ -44,6 +44,7 @@
"@swimlane/ngx-charts": "^20.1.2", "@swimlane/ngx-charts": "^20.1.2",
"@swimlane/ngx-datatable": "^20.1.0", "@swimlane/ngx-datatable": "^20.1.0",
"@types/d3-shape": "^3.1.1", "@types/d3-shape": "^3.1.1",
"angular-animations": "^0.11.0",
"angular-auth-oidc-client": "^15.0.3", "angular-auth-oidc-client": "^15.0.3",
"angular-feather": "^6.5.0", "angular-feather": "^6.5.0",
"angular-gauge": "^4.0.0", "angular-gauge": "^4.0.0",
+2
View File
@@ -28,4 +28,6 @@ export class ApiRoutes {
static Motions = '/api/accounts/:id/motions'; static Motions = '/api/accounts/:id/motions';
static Motion = '/api/accounts/:id/motions/:motionId'; static Motion = '/api/accounts/:id/motions/:motionId';
static Items = '/api/items';
} }
@@ -5,20 +5,20 @@ import {
Validators, Validators,
} from '@angular/forms'; } from '@angular/forms';
export const atLeastOneNumber = (validator: ValidatorFn, controls: string[] = []) => ( export const atLeastOneNumber = (validator: ValidatorFn, controls: string[] = []) =>
group: FormGroup, (group: FormGroup,): ValidationErrors | null => {
): ValidationErrors | null => {
if (!controls) {
controls = Object.keys(group.controls);
}
const hasAtLeastOne = group && group.controls && controls if (!controls) {
.some(k => { controls = Object.keys(group.controls);
var v = group.controls[k].value; }
return v && !isNaN(v) && v !== 0 && !validator(group.controls[k]);
});
return hasAtLeastOne ? null : { const hasAtLeastOne = group && group.controls && controls
atLeastOne: true, .some(k => {
var v = group.controls[k].value;
return !!(v && !isNaN(v) && parseFloat(v) !== 0 && !validator(group.controls[k]));
});
return hasAtLeastOne ? null : {
atLeastOne: true,
};
}; };
};
File diff suppressed because it is too large Load Diff
@@ -2,4 +2,5 @@ export interface ItemCategoryModel {
id?: string, id?: string,
name?: string, name?: string,
allowDelete: boolean, allowDelete: boolean,
isInternal: boolean,
} }
+1 -1
View File
@@ -1,7 +1,7 @@
export interface MotionModel { export interface MotionModel {
id?: string; id?: string;
date?: Date; date?: Date;
motion?: string; item?: string;
description?: string; description?: string;
plus?: number; plus?: number;
minus?: number; minus?: number;
@@ -1,4 +1,4 @@
<form [formGroup]="form" novalidate autocomplete="off"> <form [formGroup]="form" novalidate autocomplete="off" [@pulse]="inProgress">
<div class="" style="display: flex;"> <div class="" style="display: flex;">
<div class="" style="width: 310px; min-width: 310px;"> <div class="" style="width: 310px; min-width: 310px;">
<div style="display: flex; align-items: center;"> <div style="display: flex; align-items: center;">
@@ -7,7 +7,7 @@
</a> </a>
<mat-form-field class="example-full-width" appearance="fill"> <mat-form-field class="example-full-width" appearance="fill">
<input matInput [matDatepicker]="picker3" (focus)="picker3.open()" value={{motion.date}} formControlName="date" required> <input #dateInput matInput [matDatepicker]="picker3" (focus)="picker3.open()" value={{motion.date}} formControlName="date" required>
<mat-hint>YYYY/MM/DD</mat-hint> <mat-hint>YYYY/MM/DD</mat-hint>
<mat-datepicker-toggle tabindex="-1" matSuffix [for]="picker3"></mat-datepicker-toggle> <mat-datepicker-toggle tabindex="-1" matSuffix [for]="picker3"></mat-datepicker-toggle>
<mat-datepicker #picker3></mat-datepicker> <mat-datepicker #picker3></mat-datepicker>
@@ -23,11 +23,19 @@
</div> </div>
<div class="" style="flex-grow: 1;"> <div class="" style="flex-grow: 1;">
<mat-form-field class="example-full-width" appearance="fill"> <mat-form-field class="example-full-width" appearance="fill">
<mat-label>Motion</mat-label> <mat-label>
<input #motionInput matInput formControlName="motion" required> Motion
<mat-error *ngIf="form.controls['motion'].hasError('required')"> <span *ngIf="selectedItem">!!</span>
</mat-label>
<input #motionInput matInput formControlName="item" required [matAutocomplete]="auto">
<mat-error *ngIf="form.controls['item'].hasError('required') && !form.pristine">
Please enter motion Please enter motion
</mat-error> </mat-error>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="selectedFn($event.option.value)">
<mat-option *ngFor="let item of filteredItems" [value]="item">
{{item.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field> </mat-form-field>
<mat-form-field class="example-full-width" appearance="fill"> <mat-form-field class="example-full-width" appearance="fill">
<input matInput formControlName="description"> <input matInput formControlName="description">
@@ -36,17 +44,18 @@
<div class="" style="width: 100px; min-width: 100px;"> <div class="" style="width: 100px; min-width: 100px;">
<mat-form-field class="example-full-width" appearance="fill"> <mat-form-field class="example-full-width" appearance="fill">
<input matInput [value]="motion.plus | number:'0.2-2'" formControlName="plus" currencyMask [options]="{ prefix: '', precision: 4, inputMode: 1 }"> <input matInput [value]="motion.plus | number:'0.2-2'" formControlName="plus" currencyMask [options]="{ prefix: '', precision: 4, inputMode: 1 }">
<mat-error *ngIf="form.hasError('atLeastOne')">
Please enter motion
</mat-error>
</mat-form-field> </mat-form-field>
<mat-form-field class="example-full-width" appearance="fill"> <mat-form-field class="example-full-width" appearance="fill">
<input matInput [value]="motion.minus | number:'0.2-2'" formControlName="minus" currencyMask [options]="{ prefix: '', precision: 4, inputMode: 1 }"> <input matInput [value]="motion.minus | number:'0.2-2'" formControlName="minus" currencyMask [options]="{ prefix: '', precision: 4, inputMode: 1 }">
<mat-error *ngIf="form.hasError('atLeastOne')">
Please enter motion
</mat-error>
</mat-form-field> </mat-form-field>
</div> </div>
<div class="" style="display: inline-block; width: 150px; min-width: 150px;"> <div class="" style="display: inline-block; width: 150px; min-width: 150px;">
<!--
<button type="button" mat-stroked-button color="primary" *ngIf="!motion.id" (click)="add()">
<i class="material-icons font-40">add</i>
</button>
-->
<button type="button" class="m-2" mat-mini-fab color="primary" *ngIf="!motion.id" (click)="add()"> <button type="button" class="m-2" mat-mini-fab color="primary" *ngIf="!motion.id" (click)="add()">
<i class="material-icons ">add</i> <i class="material-icons ">add</i>
</button> </button>
@@ -59,6 +68,16 @@
<button type="button" class="m-2" mat-mini-fab color="primary" *ngIf="motion.id" (click)="delete()"> <button type="button" class="m-2" mat-mini-fab color="primary" *ngIf="motion.id" (click)="delete()">
<i class="material-icons ">delete</i> <i class="material-icons ">delete</i>
</button> </button>
<div class="preloader m-4" *ngIf="inProgress">
<div class="spinner-layer pl-green">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
</div> </div>
</div> </div>
<hr /> <hr />
@@ -13,21 +13,31 @@ import { ElementRef } from '@angular/core';
// libs // libs
import * as moment from 'moment'; import * as moment from 'moment';
import Swal from 'sweetalert2'; import Swal from 'sweetalert2';
import { Observable } from 'rxjs';
import { pulseAnimation } from 'angular-animations';
// app // app
import { ApiRoutes } from '../../api-routes'; import { ApiRoutes } from '../../api-routes';
import { AccountModel } from '../../model/account.model'; import { AccountModel } from '../../model/account.model';
import { MotionModel } from '../../model/motion.model'; import { MotionModel } from '../../model/motion.model';
import { ItemModel } from '../../model/item.model';
import { atLeastOneNumber } from '../../core/validators/atleastonenumber.validator'; import { atLeastOneNumber } from '../../core/validators/atleastonenumber.validator';
@Component({ @Component({
selector: 'account-motion', selector: 'account-motion',
templateUrl: './motion.component.html', templateUrl: './motion.component.html',
styleUrls: ['./motion.component.scss'], styleUrls: ['./motion.component.scss'],
animations: [
pulseAnimation({ direction: '<=>', duration: 200 }),
],
}) })
export class MotionComponent { export class MotionComponent {
public form!: FormGroup; public form!: FormGroup;
public errorMessage?: string; public errorMessage?: string;
public filteredItems: ItemModel[] = [];
public option?: string;
public selectedItem?: ItemModel;
public inProgress: boolean = false;
@Input('motion') motion!: MotionModel; @Input('motion') motion!: MotionModel;
@Input('account') account!: AccountModel; @Input('account') account!: AccountModel;
@@ -36,6 +46,7 @@ export class MotionComponent {
@Output() onDelete: EventEmitter<MotionModel> = new EventEmitter<MotionModel>(); @Output() onDelete: EventEmitter<MotionModel> = new EventEmitter<MotionModel>();
@ViewChild('motionInput') motionInput?: ElementRef; @ViewChild('motionInput') motionInput?: ElementRef;
@ViewChild('dateInput') dateInput?: ElementRef;
constructor( constructor(
private fb: FormBuilder, private fb: FormBuilder,
@@ -52,8 +63,8 @@ export class MotionComponent {
this.motion.date, this.motion.date,
[Validators.required], [Validators.required],
], ],
motion: [ item: [
this.motion.motion, this.motion.item,
[Validators.required], [Validators.required],
], ],
description: [ description: [
@@ -68,46 +79,112 @@ export class MotionComponent {
}, { }, {
validator: atLeastOneNumber(Validators.required, ['plus', 'minus']) validator: atLeastOneNumber(Validators.required, ['plus', 'minus'])
}); });
this.form.controls['item'].valueChanges.subscribe(value => {
if (!value) {
return;
}
this.selectedItem = undefined;
this.httpClient
.get<ItemModel[]>(ApiRoutes.Items + '?term=' + encodeURIComponent(value))
.subscribe(x => {
this.filteredItems = x;
});
});
}
displayFn(item: any): string {
var value = item && item.name ? item.name : item;
return value;
}
selectedFn(item: ItemModel) {
this.selectedItem = item;
} }
add() { add() {
this.form.markAllAsTouched(); this.form.markAllAsTouched();
if (!this.form.valid) {
if (this.form.hasError('atLeastOne')) {
this.form.get('plus')!.setErrors(this.form.errors);
this.form.get('minus')!.setErrors(this.form.errors);
}
return;
}
this.setInProgress();
var data = this.form.value;
data.motion = data.item.name
? data.item.name
: data.item;
data.itemId = this.selectedItem?.id;
this.httpClient this.httpClient
.post<MotionModel>(ApiRoutes.Motions.replace(':id', this.account.id!), this.form.value) .post<MotionModel>(ApiRoutes.Motions.replace(':id', this.account.id!), data)
.subscribe(response => { .subscribe(response => {
this.onAdd?.emit(response); this.onAdd?.emit(response);
this.form.patchValue({ this.form.patchValue({
motion: '', item: '',
plus: 0, plus: 0,
minus: 0, minus: 0,
}); });
this.form.markAsUntouched();
this.filteredItems = [];
this.motionInput?.nativeElement.focus(); this.motionInput?.nativeElement.focus();
this.form.markAsUntouched();
this.setInProgress(false);
}, error => { }, error => {
this.errorMessage = error.detail; this.errorMessage = error.detail;
this.setInProgress(false);
}); });
} }
private setInProgress(inProgress: boolean = true) {
this.inProgress = inProgress;
}
update() { update() {
this.form.markAllAsTouched();
if (!this.form.valid) {
if (this.form.hasError('atLeastOne')) {
this.form.get('plus')!.setErrors(this.form.errors);
this.form.get('minus')!.setErrors(this.form.errors);
}
return;
}
this.setInProgress();
var url = ApiRoutes.Motion var url = ApiRoutes.Motion
.replace(':id', this.account.id!) .replace(':id', this.account.id!)
.replace(':motionId', this.motion.id!); .replace(':motionId', this.motion.id!);
var data = this.form.value;
data.motion = data.item.name
? data.item.name
: data.motion;
data.itemId = this.selectedItem?.id;
this.httpClient this.httpClient
.put<MotionModel>(url, this.form.value) .put<MotionModel>(url, data)
.subscribe(response => { .subscribe(response => {
this.form.markAsUntouched(); this.form.markAsUntouched();
this.setInProgress(false);
}, error => { }, error => {
this.errorMessage = error.detail; this.errorMessage = error.detail;
this.setInProgress(false);
}); });
} }
delete() { delete() {
Swal.fire({ Swal.fire({
title: 'Delete motion ' + this.motion.motion, title: 'Delete motion ' + this.motion.item,
showCancelButton: true, showCancelButton: true,
confirmButtonText: 'Delete', confirmButtonText: 'Delete',
showLoaderOnConfirm: true, showLoaderOnConfirm: true,
@@ -117,12 +194,16 @@ export class MotionComponent {
.replace(':id', this.account.id!) .replace(':id', this.account.id!)
.replace(':motionId', this.motion.id!); .replace(':motionId', this.motion.id!);
this.setInProgress();
this.httpClient.delete<MotionModel>(url) this.httpClient.delete<MotionModel>(url)
.subscribe(data => { .subscribe(data => {
resolve(data); resolve(data);
this.setInProgress(false);
}, error => { }, error => {
Swal.showValidationMessage(error.detail); Swal.showValidationMessage(error.detail);
reject(); reject();
this.setInProgress(false);
}); });
}).catch(x => { }).catch(x => {
+7 -1
View File
@@ -19,6 +19,8 @@ import { MatCardModule } from '@angular/material/card';
import { NgxMaskModule } from 'ngx-mask'; import { NgxMaskModule } from 'ngx-mask';
import { NgxCurrencyModule } from "ngx-currency"; import { NgxCurrencyModule } from "ngx-currency";
import { MatExpansionModule } from '@angular/material/expansion'; import { MatExpansionModule } from '@angular/material/expansion';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatCheckboxModule } from '@angular/material/checkbox';
// app // app
import { PagesRoutingModule } from './pages-routing.module'; import { PagesRoutingModule } from './pages-routing.module';
@@ -39,6 +41,7 @@ import { SettingsItemEditComponent } from './settings/item/edit.item.component';
import { AccountListComponent } from './accounts/account.list.component'; import { AccountListComponent } from './accounts/account.list.component';
import { AccountComponent } from './accounts/account.component'; import { AccountComponent } from './accounts/account.component';
import { MotionComponent } from './accounts/motion.component'; import { MotionComponent } from './accounts/motion.component';
import { SettingsItemCategoryEditComponent } from './settings/item/edit.item.category.component';
@NgModule({ @NgModule({
declarations: [ declarations: [
@@ -56,6 +59,7 @@ import { MotionComponent } from './accounts/motion.component';
SettingsItemCategoryComponent, SettingsItemCategoryComponent,
SettingsItemComponent, SettingsItemComponent,
SettingsItemEditComponent, SettingsItemEditComponent,
SettingsItemCategoryEditComponent,
AccountListComponent, AccountListComponent,
AccountComponent, AccountComponent,
@@ -78,8 +82,10 @@ import { MotionComponent } from './accounts/motion.component';
MatGridListModule, MatGridListModule,
MatCardModule, MatCardModule,
MatExpansionModule, MatExpansionModule,
MatAutocompleteModule,
NgxMaskModule, NgxMaskModule,
NgxCurrencyModule NgxCurrencyModule,
MatCheckboxModule,
], ],
providers: [ providers: [
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' }, { provide: MAT_DATE_LOCALE, useValue: 'en-GB' },
@@ -0,0 +1,38 @@
<div>
<h2 mat-dialog-title>
Edit item category
</h2>
<div mat-dialog-content>
<form [formGroup]="editForm!" (ngSubmit)="onSubmitClick()">
<div class="row">
<div class="col-md-6">
<div class="text-inside">
<mat-form-field class="example-full-width">
<mat-label>Name</mat-label>
<input matInput value={{category.name}} formControlName="name">
</mat-form-field>
</div>
</div>
<div class="col-md-6">
<div class="text-inside">
<mat-checkbox class="example-margin" formControlName="isInternal">Is internal motion</mat-checkbox>
</div>
</div>
</div>
<mat-dialog-actions class="mat-dialog-actions">
<div class="mat-dialog-left">
<div class="alert alert-danger mat-dialog-error" *ngIf="errorMessage">
{{errorMessage}}
</div>
</div>
<div class="mat-dialog-right">
<div class="button-bottom">
<button type="button" mat-button (click)="closeDialog()">Cancel</button>
<button class="btn-space" mat-raised-button color="primary">Save</button>
</div>
</div>
</mat-dialog-actions>
</form>
</div>
</div>
@@ -0,0 +1,75 @@
// angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Inject } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { UntypedFormGroup } from '@angular/forms';
import { Validators } from '@angular/forms';
// libs
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatDialogRef } from '@angular/material/dialog';
// app
import { ApiRoutes } from '../../../api-routes';
import { ItemCategoryModel } from '../../../model/item.category.model';
@Component({
templateUrl: './edit.item.category.component.html',
styleUrls: ['./edit.item.category.component.scss'],
})
export class SettingsItemCategoryEditComponent {
public editForm!: UntypedFormGroup;
public errorMessage?: string;
constructor(
private fb: UntypedFormBuilder,
private httpClient: HttpClient,
private dialogRef: MatDialogRef<SettingsItemCategoryEditComponent>,
@Inject(MAT_DIALOG_DATA) public category: ItemCategoryModel
) {
}
ngOnInit(): void {
this.editForm = this.fb.group({
id: [
this.category.id,
],
name: [
this.category.name,
[Validators.required],
],
isInternal: [
this.category.isInternal,
],
});
console.log(this.editForm.value);
}
closeDialog(): void {
this.dialogRef.close();
}
onSubmitClick() {
if (this.editForm.valid) {
this.errorMessage = undefined;
if (!this.category.id) {
this.httpClient
.post<ItemCategoryModel>(ApiRoutes.SettingsItemCategories, this.editForm.value)
.subscribe(response => {
this.dialogRef.close({ category: response, refresh: true });
}, error => {
this.errorMessage = error.detail;
});
} else {
this.httpClient
.put<ItemCategoryModel>(ApiRoutes.SettingsItemCategory.replace(':id', this.category.id!), this.editForm.value)
.subscribe(response => {
this.dialogRef.close({ category: response, refresh: true });
}, error => {
this.errorMessage = error.detail;
});
}
}
}
}
@@ -8,10 +8,10 @@ import { Validators } from '@angular/forms';
// libs // libs
import { MAT_DIALOG_DATA } from '@angular/material/dialog'; import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatDialogRef } from '@angular/material/dialog';
// app // app
import { ApiRoutes } from '../../../api-routes'; import { ApiRoutes } from '../../../api-routes';
import { MatDialogRef } from '@angular/material/dialog';
import { ItemCategoryModel } from '../../../model/item.category.model'; import { ItemCategoryModel } from '../../../model/item.category.model';
import { ItemModel } from '../../../model/item.model'; import { ItemModel } from '../../../model/item.model';
import { ItemService } from '../../../services/item.service'; import { ItemService } from '../../../services/item.service';
@@ -2,7 +2,7 @@
<div class="content-block"> <div class="content-block">
<div class="block-header"> <div class="block-header">
<!-- breadcrumb --> <!-- breadcrumb -->
<app-breadcrumb [title]="'Blank'" [items]="['Home','Settings']" [active_item]="'Motion categories'"> <app-breadcrumb [title]="'Item categories'" [items]="['Home','Settings']" [active_item]="'Motion categories'">
</app-breadcrumb> </app-breadcrumb>
</div> </div>
<div class="row clearfix"> <div class="row clearfix">
@@ -11,7 +11,6 @@
<mat-card-header> <mat-card-header>
<mat-card-title-group> <mat-card-title-group>
<mat-card-title> <mat-card-title>
Motion categories
</mat-card-title> </mat-card-title>
<mat-card-subtitle> <mat-card-subtitle>
</mat-card-subtitle> </mat-card-subtitle>
@@ -27,6 +26,9 @@
<tbody> <tbody>
<tr *ngFor="let item of categories"> <tr *ngFor="let item of categories">
<td>{{item.name}}</td> <td>{{item.name}}</td>
<td>
<mat-icon *ngIf="item.isInternal">done</mat-icon>
</td>
<td> <td>
<button class="btn-space" (click)="edit(item)" mat-raised-button color="primary"> <button class="btn-space" (click)="edit(item)" mat-raised-button color="primary">
Edit Edit
@@ -4,10 +4,12 @@ import { HttpClient } from '@angular/common/http';
// libs // libs
import Swal from 'sweetalert2'; import Swal from 'sweetalert2';
import { MatDialog } from '@angular/material/dialog';
// app // app
import { ApiRoutes } from '../../../api-routes'; import { ApiRoutes } from '../../../api-routes';
import { ItemCategoryModel } from '../../../model/item.category.model'; import { ItemCategoryModel } from '../../../model/item.category.model';
import { SettingsItemCategoryEditComponent } from './edit.item.category.component';
@Component({ @Component({
templateUrl: './item.category.component.html', templateUrl: './item.category.component.html',
@@ -18,6 +20,7 @@ export class SettingsItemCategoryComponent {
constructor( constructor(
private httpClient: HttpClient, private httpClient: HttpClient,
private dialogModel: MatDialog,
) { ) {
} }
@@ -34,63 +37,26 @@ export class SettingsItemCategoryComponent {
} }
public add() { public add() {
Swal.fire({ this.dialogModel.open(SettingsItemCategoryEditComponent, {
title: 'Item category name', width: '640px',
input: 'text', disableClose: true,
inputAttributes: { data: { },
autocapitalize: 'off', }).afterClosed().subscribe(x => {
}, if (x && x.refresh) {
showCancelButton: true, this.load();
confirmButtonText: 'Add', }
showLoaderOnConfirm: true,
preConfirm: (name) => {
return new Promise((resolve, reject) => {
this.httpClient.post(ApiRoutes.SettingsItemCategories, { name: name })
.subscribe(data => {
resolve(data);
}, error => {
Swal.showValidationMessage(error.detail);
reject();
});
}).catch(x => {
return false;
});
},
allowOutsideClick: () => !Swal.isLoading(),
}).then((result) => {
this.load();
}); });
} }
public edit(category: ItemCategoryModel) { public edit(category: ItemCategoryModel) {
Swal.fire({ this.dialogModel.open(SettingsItemCategoryEditComponent, {
title: 'Item category name', width: '640px',
input: 'text', disableClose: true,
inputValue: category.name, data: category,
inputAttributes: { }).afterClosed().subscribe(x => {
autocapitalize: 'off', if (x && x.refresh) {
}, this.load();
showCancelButton: true, }
confirmButtonText: 'Update',
showLoaderOnConfirm: true,
preConfirm: (name) => {
return new Promise((resolve, reject) => {
this.httpClient.put(ApiRoutes.SettingsItemCategory.replace(':id', category.id!), { name: name })
.subscribe(data => {
resolve(data);
}, error => {
Swal.showValidationMessage(error.detail);
reject();
});
}).catch(x => {
return false;
});
},
allowOutsideClick: () => !Swal.isLoading(),
}).then((result) => {
this.load();
}); });
} }
+11 -6
View File
@@ -292,8 +292,8 @@
{ {
if (motion == null) if (motion == null)
throw new ArgumentNullException(nameof(motion)); throw new ArgumentNullException(nameof(motion));
if (motion.Motion == null) if (motion.Item == null)
throw new ArgumentNullException(nameof(motion.Motion)); throw new ArgumentNullException(nameof(motion.Item));
var result = new Exec<Motion, MotionAddResult>(MotionAddResult.success); var result = new Exec<Motion, MotionAddResult>(MotionAddResult.success);
@@ -303,7 +303,7 @@
return result.Set(MotionAddResult.account_not_found); return result.Set(MotionAddResult.account_not_found);
} }
var itemExec = _itemService.GetOrCreate(userId, motion.Motion); var itemExec = _itemService.GetOrCreate(userId, motion.Item);
if (itemExec.Status != ItemGetOrAddResult.success) if (itemExec.Status != ItemGetOrAddResult.success)
{ {
return result.Set(MotionAddResult.failure); return result.Set(MotionAddResult.failure);
@@ -341,8 +341,8 @@
{ {
if (motion == null) if (motion == null)
throw new ArgumentNullException(nameof(motion)); throw new ArgumentNullException(nameof(motion));
if (motion.Motion == null) if (motion.Item == null)
throw new ArgumentNullException(nameof(motion.Motion)); throw new ArgumentNullException(nameof(motion.Item));
var result = new Exec<Motion, MotionUpdateResult>(MotionUpdateResult.success); var result = new Exec<Motion, MotionUpdateResult>(MotionUpdateResult.success);
@@ -352,7 +352,7 @@
return result.Set(MotionUpdateResult.not_found); return result.Set(MotionUpdateResult.not_found);
} }
var itemExec = _itemService.GetOrCreate(userId, motion.Motion); var itemExec = _itemService.GetOrCreate(userId, motion.Item);
if (itemExec.Status != ItemGetOrAddResult.success) if (itemExec.Status != ItemGetOrAddResult.success)
{ {
return result.Set(MotionUpdateResult.failure); return result.Set(MotionUpdateResult.failure);
@@ -414,5 +414,10 @@
return result.Set(exists); return result.Set(exists);
} }
public List<Account> FindAccounts(Guid userId, string term)
{
return _accountRepository.FindAccounts(userId, term);
}
} }
} }
@@ -3,7 +3,7 @@
public class MotionAddUpdate public class MotionAddUpdate
{ {
public DateTime Date { get; set; } public DateTime Date { get; set; }
public string Motion { get; set; } = null!; public string Item { get; set; } = null!;
public string? Description { get; set; } public string? Description { get; set; }
public decimal Plus { get; set; } public decimal Plus { get; set; }
public decimal Minus { get; set; } public decimal Minus { get; set; }
+163 -153
View File
@@ -1,191 +1,201 @@
namespace MyOffice.Services.Item namespace MyOffice.Services.Item;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Domain;
using MyOffice.Core;
using MyOffice.Data.Models.Accounts;
using MyOffice.Data.Models.Items;
using MyOffice.Data.Repositories.Item;
using MyOffice.Services.Account.Domain;
public class ItemService
{ {
using System; private readonly IItemCategoryRepository _itemCategoryRepository;
using System.Collections.Generic; private readonly IItemRepository _itemRepository;
using System.Linq; private readonly IItemGlobalRepository _itemGlobalRepository;
using System.Xml.Linq;
using Domain;
using MyOffice.Core;
using MyOffice.Data.Models.Accounts;
using MyOffice.Data.Models.Items;
using MyOffice.Data.Repositories.Item;
using MyOffice.Services.Account.Domain;
public class ItemService public ItemService(
IItemCategoryRepository itemCategoryRepository,
IItemRepository itemRepository,
IItemGlobalRepository itemGlobalRepository
)
{ {
private readonly IItemCategoryRepository _itemCategoryRepository; _itemCategoryRepository = itemCategoryRepository;
private readonly IItemRepository _itemRepository; _itemRepository = itemRepository;
private readonly IItemGlobalRepository _itemGlobalRepository; _itemGlobalRepository = itemGlobalRepository;
public ItemService( }
IItemCategoryRepository itemCategoryRepository,
IItemRepository itemRepository, public List<ItemCategory> GetAllCategories(Guid userId)
IItemGlobalRepository itemGlobalRepository {
) var result = _itemCategoryRepository.GetAll(userId);
if (result.All(x => x.Id != userId))
{ {
_itemCategoryRepository = itemCategoryRepository; var category = new ItemCategory
_itemRepository = itemRepository; {
_itemGlobalRepository = itemGlobalRepository; Id = userId,
UserId = userId,
Name = "UnCategorized",
};
_itemCategoryRepository.Add(category);
result.Add(_itemCategoryRepository.Get(userId, userId)!);
}
return result;
}
public Exec<ItemCategory, GeneralExecStatus> CategoryAdd(Guid userId, ItemCategory category)
{
if (category == null)
throw new ArgumentNullException(nameof(category));
var result = new Exec<ItemCategory, GeneralExecStatus>(GeneralExecStatus.success);
category.Id = Guid.NewGuid();
category.UserId = userId;
category.IsInternal = category.IsInternal;
category.Items = new List<Item>();
if (!_itemCategoryRepository.Add(category))
{
return result.Set(GeneralExecStatus.failure);
} }
public List<ItemCategory> GetAllCategories(Guid userId) return result.Set(category);
{ }
var result = _itemCategoryRepository.GetAll(userId);
if (result.All(x => x.Id != userId))
{
var category = new ItemCategory
{
Id = userId,
UserId = userId,
Name = "UnCategorized",
};
_itemCategoryRepository.Add(category);
result.Add(_itemCategoryRepository.Get(userId, userId)!); public Exec<ItemCategory, GeneralExecStatus> CategoryUpdate(Guid userId, Guid id, ItemCategory category)
} {
return result; if (category == null)
throw new ArgumentNullException(nameof(category));
var result = new Exec<ItemCategory, GeneralExecStatus>(GeneralExecStatus.success);
var exists = _itemCategoryRepository.Get(userId, id);
if (exists == null)
{
return result.Set(GeneralExecStatus.not_found);
} }
public Exec<ItemCategory, GeneralExecStatus> CategoryAdd(Guid userId, ItemCategory category) exists.Name = category.Name;
exists.IsInternal = category.IsInternal;
exists.Items = new List<Item>();
if (!_itemCategoryRepository.Update(exists))
{ {
if (category == null) return result.Set(GeneralExecStatus.failure);
throw new ArgumentNullException(nameof(category));
var result = new Exec<ItemCategory, GeneralExecStatus>(GeneralExecStatus.success);
category.Id = Guid.NewGuid();
category.UserId = userId;
if (!_itemCategoryRepository.Add(category))
{
return result.Set(GeneralExecStatus.failure);
}
return result.Set(category);
} }
public Exec<ItemCategory, GeneralExecStatus> CategoryUpdate(Guid userId, Guid id, ItemCategory category) return result.Set(exists);
}
public Exec<ItemCategory, ItemCategoryRemoveResult> CategoryRemove(Guid userId, Guid id)
{
var result = new Exec<ItemCategory, ItemCategoryRemoveResult>(ItemCategoryRemoveResult.success);
var exists = _itemCategoryRepository.Get(userId, id);
if (exists == null)
{ {
if (category == null) return result.Set(ItemCategoryRemoveResult.not_found);
throw new ArgumentNullException(nameof(category));
var result = new Exec<ItemCategory, GeneralExecStatus>(GeneralExecStatus.success);
var exists = _itemCategoryRepository.Get(userId, id);
if (exists == null)
{
return result.Set(GeneralExecStatus.not_found);
}
exists.Name = category.Name;
if (!_itemCategoryRepository.Update(exists))
{
return result.Set(GeneralExecStatus.failure);
}
return result.Set(exists);
} }
public Exec<ItemCategory, ItemCategoryRemoveResult> CategoryRemove(Guid userId, Guid id) if (exists.Items.Any())
{ {
var result = new Exec<ItemCategory, ItemCategoryRemoveResult>(ItemCategoryRemoveResult.success); return result.Set(ItemCategoryRemoveResult.accounts_exists);
}
var exists = _itemCategoryRepository.Get(userId, id); if (!_itemCategoryRepository.Remove(exists))
if (exists == null) {
{ return result.Set(ItemCategoryRemoveResult.failure);
return result.Set(ItemCategoryRemoveResult.not_found);
}
if (exists.Items.Any())
{
return result.Set(ItemCategoryRemoveResult.accounts_exists);
}
if (!_itemCategoryRepository.Remove(exists))
{
return result.Set(ItemCategoryRemoveResult.failure);
}
return result.Set(exists);
} }
public List<Item> GetAll(Guid userId) return result.Set(exists);
}
public List<Item> GetAll(Guid userId)
{
return _itemRepository.GetAll(userId);
}
public List<Item> GetByCategory(Guid userId, Guid categoryId)
{
return _itemRepository.GetByCategory(userId, categoryId);
}
public Exec<Item, GeneralExecStatus> Update(Guid userId, Guid motionId, Guid categoryId)
{
var result = new Exec<Item, GeneralExecStatus>(GeneralExecStatus.success);
var motion = _itemRepository.GetByGlobal(userId, motionId);
if (motion == null)
{ {
return _itemRepository.GetAll(userId); return result.Set(GeneralExecStatus.not_found);
} }
public List<Item> GetByCategory(Guid userId, Guid categoryId) motion.Category!.Id = categoryId;
{ _itemRepository.Update(motion);
return _itemRepository.GetByCategory(userId, categoryId);
}
public Exec<Item, GeneralExecStatus> Update(Guid userId, Guid motionId, Guid categoryId) return result.Set(motion);
{ }
var result = new Exec<Item, GeneralExecStatus>(GeneralExecStatus.success);
var motion = _itemRepository.GetByGlobal(userId, motionId); public Exec<Item, ItemGetOrAddResult> GetOrCreate(Guid userId, string name)
if (motion == null) {
if (name == null)
throw new ArgumentNullException(nameof(name));
var result = new Exec<Item, ItemGetOrAddResult>(ItemGetOrAddResult.success);
var itemGlobal = _itemGlobalRepository.GetByName(name);
if (itemGlobal == null)
{
// add global motion
itemGlobal = new ItemGlobal
{ {
return result.Set(GeneralExecStatus.not_found); Id = Guid.NewGuid(),
} Name = name.Trim(),
};
motion.Category.Id = categoryId; if (!_itemGlobalRepository.Add(itemGlobal))
//motion.CategoryId = categoryId;
_itemRepository.Update(motion);
return result.Set(motion);
}
public Exec<Item, ItemGetOrAddResult> GetOrCreate(Guid userId, string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
var result = new Exec<Item, ItemGetOrAddResult>(ItemGetOrAddResult.success);
var itemGlobal = _itemGlobalRepository.GetByName(name);
if (itemGlobal == null)
{ {
// add global motion return result.Set(ItemGetOrAddResult.failure);
itemGlobal = new ItemGlobal
{
Id = Guid.NewGuid(),
Name = name.Trim(),
};
if (!_itemGlobalRepository.Add(itemGlobal))
{
return result.Set(ItemGetOrAddResult.failure);
}
return GetOrCreate(userId, itemGlobal);
} }
return GetOrCreate(userId, itemGlobal); return GetOrCreate(userId, itemGlobal);
} }
private Exec<Item, ItemGetOrAddResult> GetOrCreate(Guid userId, ItemGlobal itemGlobal) return GetOrCreate(userId, itemGlobal);
}
private Exec<Item, ItemGetOrAddResult> GetOrCreate(Guid userId, ItemGlobal itemGlobal)
{
if (itemGlobal == null)
throw new ArgumentNullException(nameof(itemGlobal));
var result = new Exec<Item, ItemGetOrAddResult>(ItemGetOrAddResult.success);
var item = _itemRepository.GetByGlobal(userId, itemGlobal.Id);
if (item == null)
{ {
if (itemGlobal == null) // add item to UnCategorized category
throw new ArgumentNullException(nameof(itemGlobal)); item = new Item
var result = new Exec<Item, ItemGetOrAddResult>(ItemGetOrAddResult.success);
var item = _itemRepository.GetByGlobal(userId, itemGlobal.Id);
if (item == null)
{ {
// add item to UnCategorized category CategoryId = userId,
item = new Item ItemGlobalId = itemGlobal.Id,
{ };
CategoryId = userId, _itemRepository.Add(item);
ItemGlobalId = itemGlobal.Id,
};
_itemRepository.Add(item);
}
item.ItemGlobal = itemGlobal;
return result.Set(item);
} }
item.ItemGlobal = itemGlobal;
return result.Set(item);
}
public List<Item> FindItems(Guid userId, string term, int limit = 15)
{
if (term == null)
throw new ArgumentNullException(nameof(term));
return _itemRepository.Find(userId, term, limit);
} }
} }
@@ -11,4 +11,8 @@
<ProjectReference Include="..\MyOffice.Data.Repositories\MyOffice.Data.Repositories.csproj" /> <ProjectReference Include="..\MyOffice.Data.Repositories\MyOffice.Data.Repositories.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Dashboard\" />
</ItemGroup>
</Project> </Project>
+42 -1
View File
@@ -6,9 +6,11 @@ using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Models.Account; using Models.Account;
using Models.Item;
using Models.Motion; using Models.Motion;
using Services.Account; using Services.Account;
using Services.Account.Domain; using Services.Account.Domain;
using Services.Item;
[Authorize] [Authorize]
[ApiController] [ApiController]
@@ -17,14 +19,17 @@ public class AccountController : BaseApiController
{ {
private readonly ILogger<AccountController> _logger; private readonly ILogger<AccountController> _logger;
private readonly AccountService _accountService; private readonly AccountService _accountService;
private readonly ItemService _itemService;
public AccountController( public AccountController(
ILogger<AccountController> logger, ILogger<AccountController> logger,
AccountService accountService AccountService accountService,
ItemService itemService
) )
{ {
_logger = logger; _logger = logger;
_accountService = accountService; _accountService = accountService;
_itemService = itemService;
} }
[HttpGet("~/api/accounts")] [HttpGet("~/api/accounts")]
@@ -131,4 +136,40 @@ public class AccountController : BaseApiController
throw new NotSupportedException(exec.Status.ToString()); throw new NotSupportedException(exec.Status.ToString());
} }
} }
[HttpGet("~/api/items")]
public object FindItems(string term)
{
var items = _itemService
.FindItems(UserId, term)
.Select(x => x.ToModel())
.ToList();
if (term.StartsWith("+") && term.Length > 1)
{
var accounts = _accountService.FindAccounts(UserId, term.Substring(1));
foreach (var account in accounts)
{
var accountName = $"+{account.Name}";
var item = items.FirstOrDefault(x => x.Name == accountName);
if (item == null)
{
items.Add(new ItemViewModel
{
Name = accountName,
AccountId = account.Id.ToShort(),
});
}
else
{
item.AccountId = account.Id.ToShort();
}
}
}
return items
.OrderBy(x => x.AccountId)
.ThenBy(x => x.Name);
}
} }
@@ -0,0 +1,34 @@
namespace MyOffice.Web.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyOffice.Services.Account;
using MyOffice.Services.Item;
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class DashboardController : BaseApiController
{
private readonly ILogger<DashboardController> _logger;
public DashboardController(
ILogger<DashboardController> logger
)
{
_logger = logger;
}
[HttpGet("~/api/accounts")]
public object Index()
{
return new
{
IncomeLastWeek = 100m,
IncomePreviousWeek = 100m,
OutcomeLastWeek = 100m,
OutcomePreviousWeek = 100m,
};
}
}
@@ -17,13 +17,17 @@ using Services.Item.Domain;
[Route("api/[controller]")] [Route("api/[controller]")]
public class SettingsItemController : BaseApiController public class SettingsItemController : BaseApiController
{ {
private ILogger<SettingsItemController> _logger;
private ItemService _itemService; private ItemService _itemService;
public SettingsItemController( public SettingsItemController(
ILogger<SettingsItemController> logger,
ItemService itemService ItemService itemService
) )
{ {
_itemService = itemService; _itemService = itemService;
_logger = logger;
} }
[HttpGet("~/api/settings/item-categories")] [HttpGet("~/api/settings/item-categories")]
@@ -40,7 +44,8 @@ public class SettingsItemController : BaseApiController
[HttpPost("~/api/settings/item-categories")] [HttpPost("~/api/settings/item-categories")]
public object ItemCategoriesAdd(ItemCategoryViewModel request) public object ItemCategoriesAdd(ItemCategoryViewModel request)
{ {
var exec = _itemService.CategoryAdd(UserId, new ItemCategory { Name = request.Name! }); var exec = _itemService.CategoryAdd(UserId, request.FromModel());
switch (exec.Status) switch (exec.Status)
{ {
case GeneralExecStatus.success: case GeneralExecStatus.success:
@@ -58,7 +63,8 @@ public class SettingsItemController : BaseApiController
[HttpPut("~/api/settings/item-categories/{id}")] [HttpPut("~/api/settings/item-categories/{id}")]
public object ItemCategoriesEdit(string id, ItemCategoryViewModel request) public object ItemCategoriesEdit(string id, ItemCategoryViewModel request)
{ {
var exec = _itemService.CategoryUpdate(UserId, id.AsGuid(), new ItemCategory { Name = request.Name! }); var exec = _itemService.CategoryUpdate(UserId, id.AsGuid(), request.FromModel());
switch (exec.Status) switch (exec.Status)
{ {
case GeneralExecStatus.success: case GeneralExecStatus.success:
@@ -3,16 +3,18 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using MyOffice.Core.Extensions; using MyOffice.Core.Extensions;
using MyOffice.Data.Models.Items; using MyOffice.Data.Models.Items;
using MyOffice.Migrations.Postgres.Migrations;
public class ItemCategoryViewModel public class ItemCategoryViewModel
{ {
public string? Id { get; set; } public string? Id { get; set; }
[Required] [Required]
public string? Name { get; set; } public string Name { get; set; } = null!;
public bool AllowDelete { get; set; } public bool AllowDelete { get; set; }
public int SortOrder { get; set; } public int SortOrder { get; set; }
public bool IsInternal { get; set; }
} }
public static class ItemCategoryViewModelExtensions public static class ItemCategoryViewModelExtensions
@@ -24,8 +26,21 @@
Id = input.Id.ToShort(), Id = input.Id.ToShort(),
Name = input.Name, Name = input.Name,
AllowDelete = !input.Items.Any() && input.Id != input.UserId, AllowDelete = !input.Items.Any() && input.Id != input.UserId,
IsInternal = input.IsInternal,
SortOrder = input.Id == input.UserId ? 1 : 0 SortOrder = input.Id == input.UserId ? 1 : 0
}; };
} }
public static ItemCategory FromModel(this ItemCategoryViewModel input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return new ItemCategory
{
Name = input.Name,
IsInternal = input.IsInternal,
};
}
} }
} }
+9 -6
View File
@@ -1,6 +1,7 @@
namespace MyOffice.Web.Models.Item namespace MyOffice.Web.Models.Item
{ {
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using Data.Models.Accounts;
using MyOffice.Core.Extensions; using MyOffice.Core.Extensions;
using MyOffice.Data.Models.Items; using MyOffice.Data.Models.Items;
@@ -9,24 +10,26 @@
public string? Id { get; set; } public string? Id { get; set; }
public string CategoryId { get; set; } = null!; public string CategoryId { get; set; } = null!;
public string Category { get; set; } = null!; public string? Category { get; set; } = null!;
[Required] [Required]
public string? Name { get; set; } public string? Name { get; set; }
public bool AllowDelete { get; set; } public bool AllowDelete { get; set; }
public string? AccountId { get; set; }
} }
public static class ItemViewModelExtensions public static class ItemViewModelExtensions
{ {
public static ItemViewModel ToModel(this Item input) public static ItemViewModel ToModel(this Item input, Account? account = null)
{ {
return new ItemViewModel return new ItemViewModel
{ {
Id = input.ItemGlobalId.ToShort(), Id = input.ItemGlobal.Id.ToShort(),
CategoryId = input.Category.Id.ToShort(), CategoryId = input.CategoryId.ToShort(),
Category = input.Category.Name, Category = input.Category?.Name,
Name = input.ItemGlobal.Name, Name = input.ItemGlobal.Name,
AllowDelete = !input.Motions.Any(), AllowDelete = input.Motions != null && !input.Motions.Any(),
AccountId = account?.Id.ToShort(),
}; };
} }
} }
+2 -2
View File
@@ -5,7 +5,7 @@ using MyOffice.Services.Account.Domain;
public class MotionRequest public class MotionRequest
{ {
public DateTime Date { get; set; } public DateTime Date { get; set; }
public string Motion { get; set; } = null!; public string Item { get; set; } = null!;
public string? Description { get; set; } public string? Description { get; set; }
public decimal? Plus { get; set; } public decimal? Plus { get; set; }
public decimal? Minus { get; set; } public decimal? Minus { get; set; }
@@ -18,7 +18,7 @@ public static class MotionRequestExtension
return new MotionAddUpdate return new MotionAddUpdate
{ {
Date = input.Date, Date = input.Date,
Motion = input.Motion, Item = input.Item,
Minus = input.Minus ?? 0, Minus = input.Minus ?? 0,
Plus = input.Plus ?? 0, Plus = input.Plus ?? 0,
Description = input.Description, Description = input.Description,
@@ -7,7 +7,7 @@
{ {
public string Id { get; set; } = null!; public string Id { get; set; } = null!;
public DateTime Date { get; set; } public DateTime Date { get; set; }
public string Motion { get; set; } = null!; public string Item { get; set; } = null!;
public string? Description { get; set; } public string? Description { get; set; }
public decimal Plus { get; set; } public decimal Plus { get; set; }
public decimal Minus { get; set; } public decimal Minus { get; set; }
@@ -21,7 +21,7 @@
{ {
Id = input.Id.ToShort(), Id = input.Id.ToShort(),
Date = input.DateTime, Date = input.DateTime,
Motion = input.Item.ItemGlobal.Name, Item = input.Item.ItemGlobal.Name,
Description = input.Description, Description = input.Description,
Plus = input.AmountPlus, Plus = input.AmountPlus,
Minus = input.AmountMinus, Minus = input.AmountMinus,