Compare commits

...

13 Commits

Author SHA1 Message Date
da7b320032 tiskanje bulk + vrsni red opreacij na tiskanju 2026-03-19 19:31:24 +01:00
43efa11d9c ce je project part item na invocu null vrze error 2026-03-12 15:52:05 +01:00
5d492de137 Opomba 2026-03-12 15:46:27 +01:00
8349ce5b41 styling 2026-03-04 20:28:19 +01:00
aa85143ff3 brisanje pobrise se operacije 2026-03-04 20:27:54 +01:00
99d61af1a1 tiskanje opombe, poti nacrtov
stolpec naslednja operacija,
popravljeno brisanje
popravljeno da nafila samo privzete operacije in ne vec doda v kooepracije
posiljanje dodano skp
2026-03-04 20:19:23 +01:00
73e41cc3a3 Only warn 2026-03-03 20:46:26 +01:00
5ed4ca19fc double click edit + tooltips 2026-03-03 14:45:53 +01:00
4cdfbace03 tiskanje in posiljanje po mailo 2026-03-03 09:16:17 +01:00
1da4b1e751 import excel na novo z izpiso napak 2026-02-28 12:25:39 +01:00
3d4bb077cc print 2026-02-28 11:46:09 +01:00
e29fd39e39 iskanje 2026-02-28 10:05:32 +01:00
9d0fb30bf0 - Dodati operacije na pozicijo dela projekta
- Dodatna tabela z operacijami in stanjem (končano/nekončano)
  - šifrant operacij - možnost določevanje privzetih operacij

- Opombe na pozicij dela projekta

- Pogled kooperacij na poziciji dela projekta
  - Izpisano številka kooperacije in kooperant
2026-02-28 09:37:13 +01:00
32 changed files with 4779 additions and 386 deletions

View File

@@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -52,6 +52,8 @@ namespace EveryThing.Data
public DbSet<CodeTableItem> CodeTableItems { get; set; } public DbSet<CodeTableItem> CodeTableItems { get; set; }
public DbSet<Invoice> Invoices { get; set; } public DbSet<Invoice> Invoices { get; set; }
public DbSet<InvoiceItem> InvoiceItems { get; set; } public DbSet<InvoiceItem> InvoiceItems { get; set; }
public DbSet<CodeTableOperation> CodeTableOperations { get; set; }
public DbSet<ProjectPartItemOperation> ProjectPartItemOperations { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
@@ -125,6 +127,20 @@ namespace EveryThing.Data
modelBuilder.Entity<CodeTableItem>().HasMany(t => t.ItemProjectPartItemMaterial).WithOne(t => t.Material).OnDelete(DeleteBehavior.Restrict); modelBuilder.Entity<CodeTableItem>().HasMany(t => t.ItemProjectPartItemMaterial).WithOne(t => t.Material).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Invoice>().HasMany(t => t.InvoiceInvoiceItem).WithOne(t => t.Invoice).OnDelete(DeleteBehavior.Restrict); modelBuilder.Entity<Invoice>().HasMany(t => t.InvoiceInvoiceItem).WithOne(t => t.Invoice).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Project>().HasMany(t => t.Invoices).WithOne(t => t.Project).OnDelete(DeleteBehavior.Restrict); modelBuilder.Entity<Project>().HasMany(t => t.Invoices).WithOne(t => t.Project).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<ProjectPartItemOperation>()
.HasOne(t => t.Operation)
.WithMany(t => t.ProjectPartItemOperation)
.HasForeignKey(t => t.IdCodeTableOperationFk)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<ProjectPartItemOperation>()
.HasOne(t => t.ProjectPartItem)
.WithMany(t => t.ProjectPartItemOperation)
.HasForeignKey(t => t.IdProjectPartItemFk)
.OnDelete(DeleteBehavior.Restrict);
//modelBuilder.Entity<CodeTableOperation>().HasMany(t => t.ProjectPartItemOperations).WithMany(t => t.Operation).OnDelete(DeleteBehavior.Restrict);
} }
} }
} }

View File

@@ -34,6 +34,7 @@
<PackageReference Include="Htmx" Version="0.0.15" /> <PackageReference Include="Htmx" Version="0.0.15" />
<PackageReference Include="Htmx.TagHelpers" Version="0.0.15" /> <PackageReference Include="Htmx.TagHelpers" Version="0.0.15" />
<PackageReference Include="LettuceEncrypt" Version="1.1.2" /> <PackageReference Include="LettuceEncrypt" Version="1.1.2" />
<PackageReference Include="MailKit" Version="3.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="6.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.Negotiate" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.1" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.1" />

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,140 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace EveryThing.Migrations
{
public partial class _17 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Invoices_Projects_ProjectIdProject",
table: "Invoices");
migrationBuilder.DropIndex(
name: "IX_Invoices_ProjectIdProject",
table: "Invoices");
migrationBuilder.DropColumn(
name: "ProjectIdProject",
table: "Invoices");
migrationBuilder.AddColumn<string>(
name: "Note",
table: "ProjectPartItems",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "CodeTableOperations",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
Title = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Default = table.Column<bool>(type: "tinyint(1)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CodeTableOperations", x => x.Id);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateTable(
name: "ProjectPartItemOperations",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
IdProjectPartItemFk = table.Column<int>(type: "int", nullable: false),
IdCodeTableOperationFk = table.Column<int>(type: "int", nullable: false),
Finished = table.Column<bool>(type: "tinyint(1)", nullable: false),
Order = table.Column<short>(type: "smallint", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProjectPartItemOperations", x => x.Id);
table.ForeignKey(
name: "FK_ProjectPartItemOperations_CodeTableOperations_IdCodeTableOpe~",
column: x => x.IdCodeTableOperationFk,
principalTable: "CodeTableOperations",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_ProjectPartItemOperations_ProjectPartItems_IdProjectPartItem~",
column: x => x.IdProjectPartItemFk,
principalTable: "ProjectPartItems",
principalColumn: "IdProjectPartItem",
onDelete: ReferentialAction.Restrict);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_Invoices_IdProjectFk",
table: "Invoices",
column: "IdProjectFk");
migrationBuilder.CreateIndex(
name: "IX_ProjectPartItemOperations_IdCodeTableOperationFk",
table: "ProjectPartItemOperations",
column: "IdCodeTableOperationFk");
migrationBuilder.CreateIndex(
name: "IX_ProjectPartItemOperations_IdProjectPartItemFk",
table: "ProjectPartItemOperations",
column: "IdProjectPartItemFk");
migrationBuilder.AddForeignKey(
name: "FK_Invoices_Projects_IdProjectFk",
table: "Invoices",
column: "IdProjectFk",
principalTable: "Projects",
principalColumn: "IdProject",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Invoices_Projects_IdProjectFk",
table: "Invoices");
migrationBuilder.DropTable(
name: "ProjectPartItemOperations");
migrationBuilder.DropTable(
name: "CodeTableOperations");
migrationBuilder.DropIndex(
name: "IX_Invoices_IdProjectFk",
table: "Invoices");
migrationBuilder.DropColumn(
name: "Note",
table: "ProjectPartItems");
migrationBuilder.AddColumn<int>(
name: "ProjectIdProject",
table: "Invoices",
type: "int",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Invoices_ProjectIdProject",
table: "Invoices",
column: "ProjectIdProject");
migrationBuilder.AddForeignKey(
name: "FK_Invoices_Projects_ProjectIdProject",
table: "Invoices",
column: "ProjectIdProject",
principalTable: "Projects",
principalColumn: "IdProject",
onDelete: ReferentialAction.Restrict);
}
}
}

View File

@@ -318,6 +318,24 @@ namespace EveryThing.Migrations
b.ToTable("CodeTableJobs"); b.ToTable("CodeTableJobs");
}); });
modelBuilder.Entity("EveryThing.Models.CodeTable.CodeTableOperation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<bool>("Default")
.HasColumnType("tinyint(1)");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.ToTable("CodeTableOperations");
});
modelBuilder.Entity("EveryThing.Models.CodeTable.CodeTablePartner", b => modelBuilder.Entity("EveryThing.Models.CodeTable.CodeTablePartner", b =>
{ {
b.Property<int>("IdPartner") b.Property<int>("IdPartner")
@@ -713,9 +731,6 @@ namespace EveryThing.Migrations
b.Property<string>("PreText") b.Property<string>("PreText")
.HasColumnType("longtext"); .HasColumnType("longtext");
b.Property<int?>("ProjectIdProject")
.HasColumnType("int");
b.Property<int>("State") b.Property<int>("State")
.HasColumnType("int"); .HasColumnType("int");
@@ -728,7 +743,7 @@ namespace EveryThing.Migrations
b.HasIndex("IdPartnerFk"); b.HasIndex("IdPartnerFk");
b.HasIndex("ProjectIdProject"); b.HasIndex("IdProjectFk");
b.ToTable("Invoices"); b.ToTable("Invoices");
}); });
@@ -900,6 +915,9 @@ namespace EveryThing.Migrations
b.Property<float>("MaterialPrice") b.Property<float>("MaterialPrice")
.HasColumnType("float"); .HasColumnType("float");
b.Property<string>("Note")
.HasColumnType("longtext");
b.Property<float>("NumberOfItems") b.Property<float>("NumberOfItems")
.HasColumnType("float"); .HasColumnType("float");
@@ -937,6 +955,33 @@ namespace EveryThing.Migrations
b.ToTable("ProjectPartItems"); b.ToTable("ProjectPartItems");
}); });
modelBuilder.Entity("EveryThing.Models.Project.ProjectPartItemOperation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<bool>("Finished")
.HasColumnType("tinyint(1)");
b.Property<int>("IdCodeTableOperationFk")
.HasColumnType("int");
b.Property<int>("IdProjectPartItemFk")
.HasColumnType("int");
b.Property<short>("Order")
.HasColumnType("smallint");
b.HasKey("Id");
b.HasIndex("IdCodeTableOperationFk");
b.HasIndex("IdProjectPartItemFk");
b.ToTable("ProjectPartItemOperations");
});
modelBuilder.Entity("EveryThing.Models.Transport.TransportLoadingOrder", b => modelBuilder.Entity("EveryThing.Models.Transport.TransportLoadingOrder", b =>
{ {
b.Property<int>("IdTransportLoadingOrder") b.Property<int>("IdTransportLoadingOrder")
@@ -1823,7 +1868,7 @@ namespace EveryThing.Migrations
b.HasOne("EveryThing.Models.Project.Project", "Project") b.HasOne("EveryThing.Models.Project.Project", "Project")
.WithMany("Invoices") .WithMany("Invoices")
.HasForeignKey("ProjectIdProject") .HasForeignKey("IdProjectFk")
.OnDelete(DeleteBehavior.Restrict); .OnDelete(DeleteBehavior.Restrict);
b.Navigation("Company"); b.Navigation("Company");
@@ -1925,6 +1970,25 @@ namespace EveryThing.Migrations
b.Navigation("ProjectPart"); b.Navigation("ProjectPart");
}); });
modelBuilder.Entity("EveryThing.Models.Project.ProjectPartItemOperation", b =>
{
b.HasOne("EveryThing.Models.CodeTable.CodeTableOperation", "Operation")
.WithMany("ProjectPartItemOperation")
.HasForeignKey("IdCodeTableOperationFk")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("EveryThing.Models.Project.ProjectPartItem", "ProjectPartItem")
.WithMany("ProjectPartItemOperation")
.HasForeignKey("IdProjectPartItemFk")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Operation");
b.Navigation("ProjectPartItem");
});
modelBuilder.Entity("EveryThing.Models.Transport.TransportLoadingOrder", b => modelBuilder.Entity("EveryThing.Models.Transport.TransportLoadingOrder", b =>
{ {
b.HasOne("EveryThing.Models.CodeTable.CodeTableCompany", "Company") b.HasOne("EveryThing.Models.CodeTable.CodeTableCompany", "Company")
@@ -2354,6 +2418,11 @@ namespace EveryThing.Migrations
b.Navigation("JobEmployee"); b.Navigation("JobEmployee");
}); });
modelBuilder.Entity("EveryThing.Models.CodeTable.CodeTableOperation", b =>
{
b.Navigation("ProjectPartItemOperation");
});
modelBuilder.Entity("EveryThing.Models.CodeTable.CodeTablePartner", b => modelBuilder.Entity("EveryThing.Models.CodeTable.CodeTablePartner", b =>
{ {
b.Navigation("Invoice"); b.Navigation("Invoice");
@@ -2394,6 +2463,8 @@ namespace EveryThing.Migrations
modelBuilder.Entity("EveryThing.Models.Project.ProjectPartItem", b => modelBuilder.Entity("EveryThing.Models.Project.ProjectPartItem", b =>
{ {
b.Navigation("InvoiceItem"); b.Navigation("InvoiceItem");
b.Navigation("ProjectPartItemOperation");
}); });
modelBuilder.Entity("EveryThing.Models.Transport.TransportLoadingOrder", b => modelBuilder.Entity("EveryThing.Models.Transport.TransportLoadingOrder", b =>

View File

@@ -0,0 +1,23 @@
using EveryThing.Models.Project;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EveryThing.Models.CodeTable
{
public class CodeTableOperation
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Naziv")]
public string Title { get; set; }
[Display(Name = "Privzeta operacija")]
public bool Default { get; set; }
[InverseProperty("Operation")]
public virtual ICollection<ProjectPartItemOperation> ProjectPartItemOperation { get; set; }
}
}

View File

@@ -77,7 +77,7 @@ namespace EveryThing.Models.Invoice
[Display(Name = "Partner")] [Display(Name = "Partner")]
public int? IdPartnerFk { get; set; } public int? IdPartnerFk { get; set; }
[ForeignKey("Projekt")] [ForeignKey("Project")]
[Display(Name = "Projekt")] [Display(Name = "Projekt")]
public int? IdProjectFk { get; set; } public int? IdProjectFk { get; set; }
@@ -146,7 +146,7 @@ namespace EveryThing.Models.Invoice
public CodeTableCompany Company { get; set; } public CodeTableCompany Company { get; set; }
public CodeTablePartner Partner { get; set; } public CodeTablePartner Partner { get; set; }
public Project.Project Project{ get; set; } public Project.Project Project { get; set; }
// InvoicePart // InvoicePart
[InverseProperty("Invoice")] [InverseProperty("Invoice")]

View File

@@ -6,6 +6,7 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using EveryThing.Models.CodeTable; using EveryThing.Models.CodeTable;
using EveryThing.Models.Invoice; using EveryThing.Models.Invoice;
using JetBrains.Annotations;
namespace EveryThing.Models.Project namespace EveryThing.Models.Project
{ {
@@ -161,6 +162,9 @@ namespace EveryThing.Models.Project
[Display(Name = "Spremenjeno")] [Display(Name = "Spremenjeno")]
public DateTime DateModified { get; set; } = DateTime.Now; public DateTime DateModified { get; set; } = DateTime.Now;
[Display(Name = "Opomba")]
public string Note { get; set; } = "";
[Required] [Required]
public int ProjectPartItemNumber { get; set; } = 0; public int ProjectPartItemNumber { get; set; } = 0;
@@ -177,5 +181,8 @@ namespace EveryThing.Models.Project
//Invoice item //Invoice item
[InverseProperty("ProjectPartItem")] [InverseProperty("ProjectPartItem")]
public virtual ICollection<InvoiceItem> InvoiceItem { get; set; } public virtual ICollection<InvoiceItem> InvoiceItem { get; set; }
[InverseProperty("ProjectPartItem")]
public virtual ICollection<ProjectPartItemOperation> ProjectPartItemOperation { get; set; }
} }
} }

View File

@@ -0,0 +1,31 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using EveryThing.Models.CodeTable;
namespace EveryThing.Models.Project
{
public class ProjectPartItemOperation
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("ProjectPartItem")]
public int IdProjectPartItemFk { get; set; }
[Required]
[ForeignKey("Operation")]
public int IdCodeTableOperationFk { get; set; }
[Required]
public bool Finished { get; set; }
[Required]
public short Order { get; set; }
public CodeTableOperation Operation { get; set; }
public ProjectPartItem ProjectPartItem { get; set; }
}
}

View File

@@ -112,7 +112,7 @@ namespace EveryThing.Pages.CodeTableItems
sellingPrice = projectPartItem.SellingPrice; sellingPrice = projectPartItem.SellingPrice;
differenceInPricePercentage = projectPartItem.DifferenceInPricePercentage; differenceInPricePercentage = projectPartItem.DifferenceInPricePercentage;
materialDimensions = projectPartItem.MaterialDimensions; materialDimensions = projectPartItem.MaterialDimensions;
material = projectPartItem.Material.Title; material = projectPartItem?.Material?.Title;
} }
} }

View File

@@ -0,0 +1,32 @@
@model EveryThing.Pages.CodeTableOperations.IndexModel.AddEditCodeTableOperation
<div class="modal" tabindex="-1" role="dialog" id="divModalAddEditCodeTableOperation">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalAddEditCodeTableOperationTitle">Dodajanje nove operacije</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<input id="inpModalAddEditCodeTableOperationIdCodeTableOperation" type="hidden" asp-for="@Model.IdCodeTableOperation" />
<input id="inpModalAddEditCodeTableOperationEdit" type="hidden" asp-for="@Model.Edit" />
<div class="form-group">
<label asp-for="Operation.Title" class="control-label"></label>
<input id="inpModalAddEditCodeTableOperationTitle" asp-for="Operation.Title" class="form-control" />
<span asp-validation-for="Operation.Title" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input id="inpModalAddEditCodeTableOperationDefault" class="form-check-input" asp-for="Operation.Default" /> @Html.DisplayNameFor(model => model.Operation.Default)
</label>
</div>
</div>
<div class="modal-footer">
<button id="btnModalAddEditCodeTableOperationConfirm" type="button" class="btn btn-primary">Shrani</button>
<button id="btnModalAddEditCodeTableOperationCancel" type="button" class="btn btn-secondary">Prekliči</button>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,112 @@
@page
@model EveryThing.Pages.CodeTableOperations.IndexModel
@{
ViewData["Title"] = "Index";
Layout = "~/Pages/Layouts/_Layout.cshtml";
}
<h4 class="d-flex justify-content-between align-items-center w-100 font-weight-bold py-1 mb-4">
<span>
<span class="text-muted font-weight-light">Operacije /</span> Pregled
</span>
</h4>
<div class="row">
<div class="col-12 mb-2 text-right">
<form method="get">
<div class="btn-group">
<input class="form-control" type="text" name="searchString" value="@ViewData["SearchString"]" placeholder="Iskanje..." autocomplete="off">
<button id="btnSubmit" type="submit" class="btn btn-secondary" aria-label="Osveži" title="Osveži">
<i class="opacity-75 ion ion-md-refresh"></i>
</button>
<div class="btn-group" title="Columns">
<button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-label="Nastavitve" title="Nastavitve">
<i class="opacity-75 ion ion-md-apps"></i>
<span class="caret"></span>
</button>
@* <div class="dropdown-menu dropdown-menu-right">
<label class="dropdown-item">
<input type="checkbox" name="finishedProjects" @ViewData["FinishedProjects"]> <span>Aktivni artikli</span>
</label>
</div>*@
</div>
</div>
</form>
</div>
</div>
<div class="card">
<h6 class="card-header">
Seznam operacij
</h6>
<table class="table">
<thead>
<tr>
<th class="w-100">
@Html.DisplayNameFor(model => model.Operation[0].Title)
</th>
<th class="text-right" style="white-space: nowrap; width: 1%;">
@Html.DisplayNameFor(model => model.Operation[0].Default)
</th>
<th class="text-right" style="white-space: nowrap; width: 1%;"></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Operation)
{
<tr data-idCodeTableOperation="@item.Id">
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
@Html.DisplayFor(modelItem => item.Default)
</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" href="javascript:;" onclick="editCodeTableOperation(this);" data-toggle="tooltip" data-placement="top" title="Urejanje" data-state="secondary"><i class="fas fa-pencil-alt"></i></a>
<a class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" href='javascript:;' onclick="deleteCodeTableOperation(this)"><i class="fas fa-times"></i></a>
</td>
</tr>
}
</tbody>
</table>
<div class="card-footer py-3 text-right">
<button type="button" class="btn btn-primary" onclick="addNewCodeTableOperation();" >Vnos operacije</button>
</div>
<div id="divModalCodeTableOperationAddEditPlaceholder"></div>
</div>
@Html.AntiForgeryToken()
@section Scripts {
<script src="~/js/codeTableOperationHelper.js" asp-append-version="true"></script>
<script>
$('[data-toggle="tooltip"]').tooltip({container: 'table'});
function addNewCodeTableOperation() {
codeTableOperationAddEdit('#divModalCodeTableOperationAddEditPlaceholder', false, null, (idCodeTableOperation) => {
document.getElementById('btnSubmit').click();
});
}
function editCodeTableOperation(element) {
let idCodeTableOperation = parseInt($(element).parent().parent().attr('data-idCodeTableOperation'));
codeTableOperationAddEdit('#divModalCodeTableOperationAddEditPlaceholder', true, idCodeTableOperation, (idCodeTableOperation) => {
document.getElementById('btnSubmit').click();
});
}
function deleteCodeTableOperation(element) {
let row = $(element).parent().parent();
let idCodeTableOperation = parseInt(row.attr('data-idCodeTableOperation'));
codeTableOperationDelete(idCodeTableOperation, (idCodeTableOperation) => {
row.remove();
});
}
</script>
}

View File

@@ -0,0 +1,168 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using EveryThing.Data;
using EveryThing.Models;
using EveryThing.Models.CodeTable;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.VisualStudio.Debugger.Contracts;
using System.Globalization;
namespace EveryThing.Pages.CodeTableOperations
{
[Authorize(Roles = "Administrator,InvoicingUser,ProjecThingUser")]
public class IndexModel : PageModel
{
public class AddEditCodeTableOperation
{
public CodeTableOperation Operation { get; set; }
public bool Edit { get; set; }
public int IdCodeTableOperation { get; set; }
}
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityApplicationUser> _userManager;
private readonly SignInManager<IdentityApplicationUser> _loginManager;
private readonly RoleManager<IdentityApplicationRole> _roleManager;
public IndexModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager, SignInManager<IdentityApplicationUser> loginManager, RoleManager<IdentityApplicationRole> roleManager)
{
_context = context;
_userManager = userManager;
_loginManager = loginManager;
_roleManager = roleManager;
}
public IList<CodeTableOperation> Operation { get; set; }
public async Task OnGetAsync(string searchString)
{
var user = _userManager.GetUserAsync(User).Result;
ViewData["SearchString"] = searchString ?? "";
var search = !string.IsNullOrEmpty(searchString);
var query = _context.CodeTableOperations.AsQueryable();
if (search)
{
query = query.Where(x => EF.Functions.Like(x.Title, $"%{searchString}%"));
}
Operation = await query
.OrderByDescending(x => x.Id)
.Take(100)
.ToListAsync();
}
public IActionResult OnGetCodeTableOperationModal(bool edit, int idCodeTableOperation)
{
CodeTableOperation operation = null;
if (edit)
{
operation = _context.CodeTableOperations
.FirstOrDefault(x => x.Id == idCodeTableOperation);
}
operation ??= new CodeTableOperation();
return Partial("AddEditOperationModal", new AddEditCodeTableOperation
{
Operation = operation,
Edit = edit,
IdCodeTableOperation = idCodeTableOperation
});
}
public IActionResult OnPostCodeTableOperation(string title, bool defaultValue, bool edit, int idCodeTableOperation)
{
var successful = true;
var error = "";
if (edit)
{
var operation = _context.CodeTableOperations
.FirstOrDefault(x => x.Id == idCodeTableOperation);
if (operation != null)
{
operation.Title = title;
operation.Default = defaultValue;
_context.SaveChanges();
}
else
{
successful = false;
error = $"Code-table operation with ID: {idCodeTableOperation} not found";
}
}
else
{
var operation = new CodeTableOperation
{
Title = title,
Default = defaultValue
};
_context.CodeTableOperations.Add(operation);
_context.SaveChanges();
idCodeTableOperation = operation.Id;
}
return new JsonResult(new { idCodeTableOperation, error, successful });
}
public IActionResult OnGetCodeTableOperation(int idCodeTableOperation)
{
var successful = true;
var error = "";
var inUse = false;
var operation = _context.CodeTableOperations
.Include(x => x.ProjectPartItemOperation)
.FirstOrDefault(x => x.Id == idCodeTableOperation);
if (operation == null)
{
successful = false;
error = $"Code-table operation with ID: {idCodeTableOperation} not found";
}
else
{
inUse = operation.ProjectPartItemOperation != null && operation.ProjectPartItemOperation.Count > 0;
operation.ProjectPartItemOperation = null;
}
return new JsonResult(new { operation, error, successful, inUse });
}
public IActionResult OnDeleteCodeTableOperation(int idCodeTableOperation)
{
var successful = true;
var error = "";
var operation = _context.CodeTableOperations
.FirstOrDefault(x => x.Id == idCodeTableOperation);
if (operation != null)
{
_context.CodeTableOperations.Remove(operation);
_context.SaveChanges();
}
else
{
successful = false;
error = $"Code-table operation with ID: {idCodeTableOperation} not found";
}
return new JsonResult(new { idCodeTableOperation, error, successful });
}
}
}

View File

@@ -61,6 +61,29 @@
</span> </span>
</h4> </h4>
<div class="card pt-2" style="width: 595pt; margin-bottom:10px;">
<div class="card-body">
<div class="row">
<div class="col-6">
<div class="d-flex align-items-center">
<select id="selTranslationLangue" asp-items="Html.GetEnumSelectList<PrintModel.PrintTranslationLanguage>()" class="form-control form-control-sm" style="width: 200px;">
</select>
<button id="btnTranslate" type="button" class="btn btn-sm btn-success ml-2" data-style="zoom-out" onclick="setLanguage();return false;">Prevedi</button>
</div>
</div>
<div class="col-6 text-right">
@if (Model.Invoice.State == Models.Invoice.Invoice.InvoiceState.New)
{
<button id="btnPrintAndConfirm" type="button" class="btn btn-sm btn-success btn-print ladda-button pull-right" data-style="zoom-out" data-confirm="true"><i class="ion ion-md-print"></i>&nbsp; Natisni in potrdi</button>
}
<button id="btnPrint" type="button" class="btn btn-sm btn-primary btn-print ladda-button pull-right" data-style="zoom-out"><i class="ion ion-md-print"></i>&nbsp; Natisni</button>
<button id="btnSend" type="button" class="btn btn-sm btn-secondary ladda-button pull-right" data-style="zoom-out"><i class="far fa-envelope"></i>&nbsp; Pošlji</button>
</div>
</div>
</div>
</div>
<div class="card pt-2" style="width: 595pt"> <div class="card pt-2" style="width: 595pt">
<div id="print-content" class="card-body pb-4 pl-4 pt-0" style="padding-right: 2rem !important"> <div id="print-content" class="card-body pb-4 pl-4 pt-0" style="padding-right: 2rem !important">
@@ -150,6 +173,9 @@
<th class="py-1 text-right"> <th class="py-1 text-right">
@Model.Translation.Price @Model.Translation.Price
</th> </th>
<th class="py-1 text-right">
@Model.Translation.Discount
</th>
<th class="py-1 text-right"> <th class="py-1 text-right">
@Model.Translation.Amount @Model.Translation.Amount
</th> </th>
@@ -199,6 +225,7 @@
|| Model.Invoice.Type == Models.Invoice.Invoice.InvoiceType.BuyersOrder) || Model.Invoice.Type == Models.Invoice.Invoice.InvoiceType.BuyersOrder)
{ {
<td class="text-right">@Html.DisplayFor(x => item.Price)</td> <td class="text-right">@Html.DisplayFor(x => item.Price)</td>
<td class="text-right">@Html.DisplayFor(x => item.Discount)%</td>
<td class="text-right">@Html.DisplayFor(x => item.TotalValue)</td> <td class="text-right">@Html.DisplayFor(x => item.TotalValue)</td>
} }
else if (Model.Invoice.Type == Models.Invoice.Invoice.InvoiceType.Order) else if (Model.Invoice.Type == Models.Invoice.Invoice.InvoiceType.Order)
@@ -253,23 +280,6 @@
<div style="display: none" id="footer2">Tel.: @Html.DisplayFor(modelItem => Model.Invoice.Company.Phone), @Html.DisplayFor(modelItem => Model.Invoice.Company.Bank); IBAN: @Html.DisplayFor(modelItem => Model.Invoice.Company.Iban); SWIFT/BIC: @Html.DisplayFor(modelItem => Model.Invoice.Company.SwiftBic)</div> <div style="display: none" id="footer2">Tel.: @Html.DisplayFor(modelItem => Model.Invoice.Company.Phone), @Html.DisplayFor(modelItem => Model.Invoice.Company.Bank); IBAN: @Html.DisplayFor(modelItem => Model.Invoice.Company.Iban); SWIFT/BIC: @Html.DisplayFor(modelItem => Model.Invoice.Company.SwiftBic)</div>
</div> </div>
<div class="card-footer">
<div class="row">
<div class="col-6">
<select id="selTranslationLangue" asp-items="Html.GetEnumSelectList<PrintModel.PrintTranslationLanguage>()" class="form-control" style="width: 200px;">
</select>
<button id="btnTranslate" type="button" class="btn btn-success pull-right" data-style="zoom-out" onclick="setLanguage();return false;">Prevedi</button>
</div>
<div class="col-6 text-right">
@if (Model.Invoice.State == Models.Invoice.Invoice.InvoiceState.New)
{
<button id="btnPrintAndConfirm" type="button" class="btn btn-success btn-print ladda-button pull-right" data-style="zoom-out" data-confirm="true"><i class="ion ion-md-print"></i>&nbsp; Natisni in potrdi</button>
}
<button id="btnPrint" type="button" class="btn btn-primary btn-print ladda-button pull-right" data-style="zoom-out"><i class="ion ion-md-print"></i>&nbsp; Natisni</button>
</div>
</div>
</div>
</div> </div>
@Html.AntiForgeryToken() @Html.AntiForgeryToken()
@@ -281,6 +291,7 @@
<script> <script>
var laddaPrint = Ladda.create(document.querySelector('#btnPrint')); var laddaPrint = Ladda.create(document.querySelector('#btnPrint'));
var laddaSend = Ladda.create(document.querySelector('#btnSend'));
var laddaPrintAndConfirm = document.querySelector('#btnPrintAndConfirm') == null ? null : Ladda.create(document.querySelector('#btnPrintAndConfirm')); var laddaPrintAndConfirm = document.querySelector('#btnPrintAndConfirm') == null ? null : Ladda.create(document.querySelector('#btnPrintAndConfirm'));
var element = document.getElementById('print-content'); var element = document.getElementById('print-content');
@@ -300,43 +311,40 @@
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' } jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
}; };
function print(confirm) { function buildPdf(callback) {
laddaPrint.start();
if (laddaPrintAndConfirm != null) {
laddaPrintAndConfirm.start();
}
html2pdf().set(opt).from(element).toPdf().get('pdf').then(function (pdf) { html2pdf().set(opt).from(element).toPdf().get('pdf').then(function (pdf) {
var totalPages = pdf.internal.getNumberOfPages(); var totalPages = pdf.internal.getNumberOfPages();
for (i = 1; i <= totalPages; i++) { for (var i = 1; i <= totalPages; i++) {
pdf.setPage(i); pdf.setPage(i);
pdf.setFontSize(8); pdf.setFontSize(8);
pdf.setTextColor(0); pdf.setTextColor(0);
var fontSize = pdf.internal.getFontSize(); var fontSize = pdf.internal.getFontSize();
var pageWidth = pdf.internal.pageSize.width; var pageWidth = pdf.internal.pageSize.width;
var txt = $('#footer1').text(); var txt = $('#footer1').text();
var txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor; var txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
var x = (pageWidth - txtWidth) / 2; var x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 8, txt); pdf.text(x, pdf.internal.pageSize.getHeight() - 8, txt);
txt = $('#footer2').text(); txt = $('#footer2').text();
txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor; txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
x = (pageWidth - txtWidth) / 2; x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 5, txt); pdf.text(x, pdf.internal.pageSize.getHeight() - 5, txt);
//pdf.addImage("YOUR_IMAGE", 'JPEG', pdf.internal.pageSize.getWidth() - 1.1, pdf.internal.pageSize.getHeight() - 0.25, 1, 0.2);
} }
callback(pdf);
});
}
function print(confirm) {
laddaPrint.start();
if (laddaPrintAndConfirm != null) {
laddaPrintAndConfirm.start();
}
buildPdf(function (pdf) {
laddaPrint.stop(); laddaPrint.stop();
if (laddaPrintAndConfirm != null) { if (laddaPrintAndConfirm != null) {
laddaPrintAndConfirm.stop(); laddaPrintAndConfirm.stop();
} }
//window.open(pdf.output('bloburl'), '_blank');
let link = document.createElement('a'); let link = document.createElement('a');
link.target = '_blank'; link.target = '_blank';
link.href = pdf.output('bloburl'); link.href = pdf.output('bloburl');
@@ -346,7 +354,6 @@
if (confirm) { if (confirm) {
confirmInvoice(); confirmInvoice();
} }
}); });
} }
@@ -358,6 +365,85 @@
print($(this).attr("data-confirm") === 'true'); print($(this).attr("data-confirm") === 'true');
}); });
$('#btnSend').click(function () {
send();
});
function send() {
var partnerEmail = '@Html.Raw(Model.Invoice.Partner?.Email ?? "")';
var partnerTitle = '@Html.Raw(Model.Invoice.Partner?.Title ?? "")';
var emailInput = document.createElement('input');
emailInput.type = 'email';
emailInput.value = partnerEmail;
if (!partnerEmail || !emailInput.checkValidity()) {
Swal.fire('Napaka', `Partner nima veljavnega e-poštnega naslova (${partnerEmail}).`, 'error');
return;
}
Swal.fire({
title: 'Pošlji dokument',
html: 'Dokument bo poslan na:<br>' + partnerTitle + ' (' + partnerEmail + ')',
icon: 'question',
showCancelButton: true,
showDenyButton: true,
confirmButtonText: 'Pošlji s prilogo',
denyButtonText: 'Pošlji',
cancelButtonText: 'Prekliči',
denyButtonColor: '#007bff'
}).then(function (result) {
if (result.isConfirmed) {
laddaSend.start();
buildPdf(function (pdf) {
var formData = new FormData();
formData.append('pdfFile', pdf.output('blob'), '@(Model.Invoice.InvoiceNumberFull.Replace("-", "_"))' + '.pdf');
formData.append('idInvoice', @Model.Invoice.IdInvoice);
formData.append('withAttachment', 'true');
sendDocument(formData);
});
} else if (result.isDenied) {
laddaSend.start();
buildPdf(function (pdf) {
var formData = new FormData();
formData.append('pdfFile', pdf.output('blob'), '@(Model.Invoice.InvoiceNumberFull.Replace("-", "_"))' + '.pdf');
formData.append('idInvoice', @Model.Invoice.IdInvoice);
formData.append('withAttachment', 'false');
sendDocument(formData);
});
}
});
}
function sendDocument(formData) {
$.blockUI();
$.ajax({
type: 'POST',
beforeSend: function (xhr) {
xhr.setRequestHeader('XSRF-TOKEN',
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: 'Print/?handler=SendDocument',
data: formData,
processData: false,
contentType: false,
success: function (data) {
laddaSend.stop();
if (data.successful) {
Swal.fire('Dokument poslan', '', 'success');
} else {
Swal.fire('Napaka pri pošiljanju dokumenta', data.error, 'error');
}
$.unblockUI();
},
error: function (xhr, ajaxOptions, thrownError) {
laddaSend.stop();
console.log(xhr);
alert(xhr.responseText);
$.unblockUI();
}
});
}
function confirmInvoice() { function confirmInvoice() {
$.blockUI(); $.blockUI();
$.ajax({ $.ajax({
@@ -378,7 +464,7 @@
data.error, data.error,
'error'); 'error');
} }
$.unblockUI(); $.unblockUI();
}, },
error: function (xhr, ajaxOptions, thrownError) { error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr); console.log(xhr);

View File

@@ -3,10 +3,16 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using EveryThing.Data; using EveryThing.Data;
using EveryThing.Models; using EveryThing.Models;
using EveryThing.Models.Invoice; using EveryThing.Models.Invoice;
@@ -36,6 +42,7 @@ namespace EveryThing.Pages.Invoices
public string Article { get; set; } = "Artikel"; public string Article { get; set; } = "Artikel";
public string Quantity { get; set; } = "Količina"; public string Quantity { get; set; } = "Količina";
public string Price { get; set; } = "Cena"; public string Price { get; set; } = "Cena";
public string Discount { get; set; } = "Rabat";
public string Amount { get; set; } = "Znesek"; public string Amount { get; set; } = "Znesek";
public string Dimensions { get; set; } = "Dimenzije"; public string Dimensions { get; set; } = "Dimenzije";
public string Total { get; set; } = "Skupaj"; public string Total { get; set; } = "Skupaj";
@@ -55,16 +62,20 @@ namespace EveryThing.Pages.Invoices
private readonly ApplicationDbContext _context; private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityApplicationUser> _userManager; private readonly UserManager<IdentityApplicationUser> _userManager;
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _environment;
public Models.Invoice.Invoice Invoice { get; set; } public Models.Invoice.Invoice Invoice { get; set; }
public PrintTranslation Translation { get; set; } public PrintTranslation Translation { get; set; }
public IList<Models.Invoice.InvoiceItem> InvoiceItems { get; set; } public IList<Models.Invoice.InvoiceItem> InvoiceItems { get; set; }
public string ProjectNumber { get; set; } public string ProjectNumber { get; set; }
public PrintModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager) public PrintModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager, IConfiguration configuration, IWebHostEnvironment environment)
{ {
_context = context; _context = context;
_userManager = userManager; _userManager = userManager;
_configuration = configuration;
_environment = environment;
} }
public async Task<IActionResult> OnGetAsync(int id, int? printTranslationLanguage) public async Task<IActionResult> OnGetAsync(int id, int? printTranslationLanguage)
@@ -112,6 +123,97 @@ namespace EveryThing.Pages.Invoices
return NotFound(); return NotFound();
} }
public async Task<IActionResult> OnPostSendDocumentAsync(IFormFile pdfFile, int idInvoice, bool withAttachment)
{
if (pdfFile == null || pdfFile.Length == 0)
return new JsonResult(new { successful = false, error = "PDF datoteka je obvezna." });
var user = await _userManager.GetUserAsync(User);
try
{
var invoice = await _context.Invoices
.Include(x => x.Partner)
.Include(x => x.Company)
.FirstOrDefaultAsync(x => x.IdInvoice == idInvoice && x.IdCompanyFk == user.IdCompanyFk);
if (invoice == null)
return new JsonResult(new { successful = false, error = "Invoice not found." });
using var stream = pdfFile.OpenReadStream();
var pdfBytes = new byte[pdfFile.Length];
await stream.ReadAsync(pdfBytes, 0, (int)pdfFile.Length);
var attachments = new List<Models.File>();
if (withAttachment)
{
var itemIds = await _context.InvoiceItems
.Where(x => x.IdInvoiceFk == idInvoice && x.IdItemFk != null)
.Select(x => x.IdItemFk.Value)
.Distinct()
.ToListAsync();
if (itemIds.Any())
{
attachments = await _context.Files
.Where(x => x.IdCompanyFk == user.IdCompanyFk
&& itemIds.Contains(x.IdReferenceFk)
&& x.FileType == FileType.CodeTableItem)
.ToListAsync();
}
}
var emailSettings = _configuration.GetSection("EmailSettings");
var host = emailSettings["Host"];
var port = int.Parse(emailSettings["Port"] ?? "587");
var secureSocketOptions = Enum.Parse<SecureSocketOptions>(emailSettings["SecureSocketOptions"] ?? "StartTls");
var username = emailSettings["Username"];
var password = emailSettings["Password"];
var fromEmail = emailSettings["FromEmail"];
var fromName = emailSettings["FromName"];
var bcc = emailSettings["Bcc"];
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(fromName, fromEmail));
mimeMessage.To.Add(new MailboxAddress(invoice.Partner.Title, invoice.Partner.Email));
if (!string.IsNullOrWhiteSpace(bcc))
mimeMessage.Bcc.Add(MailboxAddress.Parse(bcc));
mimeMessage.Subject = invoice.InvoiceNumberFull;
var bodyBuilder = new BodyBuilder
{
TextBody = $"Spoštovani,\n\nv prilogi vam pošiljamo dokument {invoice.InvoiceNumberFull}.\n\nLep pozdrav,\n{invoice.Company.Title}"
};
bodyBuilder.Attachments.Add(invoice.InvoiceNumberFull + ".pdf", pdfBytes, new ContentType("application", "pdf"));
var filesFolder = System.IO.Path.Combine(_environment.WebRootPath, "Uploads", "Files", ((int)FileType.CodeTableItem).ToString());
foreach (var file in attachments)
{
var filePath = System.IO.Path.Combine(filesFolder, file.Guid + file.Extension);
if (System.IO.File.Exists(filePath))
{
var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);
bodyBuilder.Attachments.Add(file.Title + file.Extension, fileBytes);
}
}
mimeMessage.Body = bodyBuilder.ToMessageBody();
using var smtpClient = new SmtpClient();
await smtpClient.ConnectAsync(host, port, secureSocketOptions);
await smtpClient.AuthenticateAsync(username, password);
await smtpClient.SendAsync(mimeMessage);
await smtpClient.DisconnectAsync(true);
}
catch (Exception ex)
{
return new JsonResult(new { successful = false, error = ex.Message });
}
return new JsonResult(new { successful = true });
}
public IActionResult OnPostConfirmInvoice(int idInvoice) public IActionResult OnPostConfirmInvoice(int idInvoice)
{ {
var user = _userManager.GetUserAsync(User).Result; var user = _userManager.GetUserAsync(User).Result;
@@ -200,6 +302,7 @@ namespace EveryThing.Pages.Invoices
OrderNumber = invoiceState == Invoice.InvoiceState.Offer ? "Anfrage No." : "Bestellnummer", OrderNumber = invoiceState == Invoice.InvoiceState.Offer ? "Anfrage No." : "Bestellnummer",
Price = "Preis(€)", Price = "Preis(€)",
Quantity = "Menge(Stk)", Quantity = "Menge(Stk)",
Discount = "Rabatt",
SwiftBic = "SWIFT/BIC", SwiftBic = "SWIFT/BIC",
Total = "Gesamtsumme", Total = "Gesamtsumme",
Project = "Projekt", Project = "Projekt",

View File

@@ -74,50 +74,12 @@
<a asp-page="/Invoices/Index" asp-route-type="4" class="sidenav-link"><i class="sidenav-icon fas fa-hands-helping"></i><div>Kooperacije </div></a> <a asp-page="/Invoices/Index" asp-route-type="4" class="sidenav-link"><i class="sidenav-icon fas fa-hands-helping"></i><div>Kooperacije </div></a>
</li> </li>
} }
@*<li class="sidenav-item">
<a asp-page="/Index" class="sidenav-link"><i class="sidenav-icon fas fa-ruler"></i><div>Planiranje</div></a>
</li>
<li class="sidenav-item">
<a asp-page="/Index" class="sidenav-link"><i class="sidenav-icon fas fa-dolly"></i><div>Prevoznice</div></a>
</li>*@
@*<li class="sidenav-divider mb-1"></li>
<li class="sidenav-header small font-weight-semibold">VOZNI PARK</li>
<li class="sidenav-item">
<a asp-page="/Index" class="sidenav-link"><i class="sidenav-icon fas fa-wrench"></i><div>Delovni nalogi</div></a>
</li>
<li class="sidenav-item">
<a asp-page="/Index" class="sidenav-link"><i class="sidenav-icon fas fa-cogs"></i><div>Servisi</div></a>
</li>
<li class="sidenav-item">
<a asp-page="/Index" class="sidenav-link"><i class="sidenav-icon fas fa-tasks"></i><div>Pregledi</div></a>
</li>
<li class="sidenav-item@(currentPage.StartsWith("/Management/Issues/") ? " active" : "")">
<a asp-page="/Management/Issues/Index" class="sidenav-link"><i class="sidenav-icon fas fa-exclamation-triangle"></i><div>Napake</div></a>
</li>
<li class="sidenav-item@(currentPage.StartsWith("/Vehicle/VehicleFueling/") ? " active" : "")">
<a asp-page="/Vehicle/VehicleFueling/Index" class="sidenav-link"><i class="sidenav-icon fas fa-gas-pump"></i><div>Gorivo</div></a>
</li>*@
@if (User.IsInRole("Administrator") || User.IsInRole("ProjecThingUser") || User.IsInRole("InvoicingUser") || User.IsInRole("TransportThingUser")) @if (User.IsInRole("Administrator") || User.IsInRole("ProjecThingUser") || User.IsInRole("InvoicingUser") || User.IsInRole("TransportThingUser"))
{ {
<li class="sidenav-divider mb-1"></li> <li class="sidenav-divider mb-1"></li>
<li class="sidenav-header small font-weight-semibold">ŠIFRANTI</li> <li class="sidenav-header small font-weight-semibold">ŠIFRANTI</li>
@*<li class="sidenav-item@(currentPage.StartsWith("/CodeTableEmployees/") ? " active" : "")">
<a asp-page="/CodeTableEmployees/Index" class="sidenav-link"><i class="sidenav-icon fas fa-users"></i><div>Zaposleni</div></a>
</li>*@
@*<li class="sidenav-item@(currentPage.StartsWith("/CodeTables/Vehicles/") ? " active" : "")">
<a asp-page="/Employees/Index" class="sidenav-link"><i class="sidenav-icon fas fa-truck"></i><div>Vozni park</div></a>
</li>*@
<li class="sidenav-item@(currentPage.StartsWith("/CodeTablePartners/") ? " active" : "")"> <li class="sidenav-item@(currentPage.StartsWith("/CodeTablePartners/") ? " active" : "")">
<a asp-page="/CodeTablePartners/Index" class="sidenav-link"><i class="sidenav-icon fas fa-handshake"></i><div>Partnerji</div></a> <a asp-page="/CodeTablePartners/Index" class="sidenav-link"><i class="sidenav-icon fas fa-handshake"></i><div>Partnerji</div></a>
</li> </li>
@@ -126,6 +88,9 @@
<li class="sidenav-item@(currentPage.StartsWith("/CodeTableItems/") ? " active" : "")"> <li class="sidenav-item@(currentPage.StartsWith("/CodeTableItems/") ? " active" : "")">
<a asp-page="/CodeTableItems/Index" class="sidenav-link"><i class="sidenav-icon fas fa-box"></i><div>Artikli</div></a> <a asp-page="/CodeTableItems/Index" class="sidenav-link"><i class="sidenav-icon fas fa-box"></i><div>Artikli</div></a>
</li> </li>
<li class="sidenav-item@(currentPage.StartsWith("/CodeTableOperations/") ? " active" : "")">
<a asp-page="/CodeTableOperations/Index" class="sidenav-link"><i class="sidenav-icon fas fa-wrench"></i><div>Operacije</div></a>
</li>
} }
@if (User.IsInRole("Administrator") || User.IsInRole("TransportThingUser")) @if (User.IsInRole("Administrator") || User.IsInRole("TransportThingUser"))
{ {

View File

@@ -13,7 +13,7 @@
<h4 class="d-flex justify-content-between align-items-center w-100 font-weight-bold py-1 mb-4"> <h4 class="d-flex justify-content-between align-items-center w-100 font-weight-bold py-1 mb-4">
<span> <span>
<span class="text-muted font-weight-light">Projekt /</span> <span class="text-muted font-weight-light">Projekt /</span>
@if ((bool)ViewData["Edit"]) @if ((bool)ViewData["Edit"])
{ {
<span>&nbsp;Urejanje pozicije dela projekta</span> <span>&nbsp;Urejanje pozicije dela projekta</span>
@@ -22,7 +22,7 @@
{ {
<span>&nbsp;Nova pozicija dela projekta</span> <span>&nbsp;Nova pozicija dela projekta</span>
} }
</span> </span>
</h4> </h4>
@@ -46,9 +46,11 @@
<div class="col-12"> <div class="col-12">
<div class="form-group"> <div class="form-group">
<label asp-for="ProjectPartItem.IdItemFk" class="form-label"></label> <label asp-for="ProjectPartItem.IdItemFk" class="form-label"></label>
<div class="form-row"> <div class="form-row align-items-end">
<div class="col-12"> <div class="col">
<select id="selCodeTableItem" asp-for="ProjectPartItem.IdItemFk" class="form-control select2" asp-items="ViewBag.IdItemFk"></select> <select id="selCodeTableItem" asp-for="ProjectPartItem.IdItemFk" class="form-control select2" asp-items="ViewBag.IdItemFk"></select>
</div>
<div class="col-auto">
<button class="btn btn-success" type="button" onclick="copyDataFromLastPartItem();">Napolni prejšnje</button> <button class="btn btn-success" type="button" onclick="copyDataFromLastPartItem();">Napolni prejšnje</button>
<button class="btn btn-primary" type="button" onclick="addNewCodeTableItem();">Novi artikel</button> <button class="btn btn-primary" type="button" onclick="addNewCodeTableItem();">Novi artikel</button>
</div> </div>
@@ -76,11 +78,11 @@
<div class="col-12"> <div class="col-12">
<div class="form-group"> <div class="form-group">
<label asp-for="ProjectPartItem.IdMaterialFk" class="form-label"></label> <label asp-for="ProjectPartItem.IdMaterialFk" class="form-label"></label>
<div class="form-row"> <div class="form-row align-items-end">
<div class="col-9"> <div class="col">
<select id="selCodeTableItemMaterial" asp-for="ProjectPartItem.IdMaterialFk" class="form-control select2" asp-items="ViewBag.IdMaterialFk"></select> <select id="selCodeTableItemMaterial" asp-for="ProjectPartItem.IdMaterialFk" class="form-control select2" asp-items="ViewBag.IdMaterialFk"></select>
</div> </div>
<div class="col-3"> <div class="col-auto">
<button class="btn btn-primary" type="button" onclick="addNewCodeTableItemMaterial();">Novi material</button> <button class="btn btn-primary" type="button" onclick="addNewCodeTableItemMaterial();">Novi material</button>
</div> </div>
</div> </div>
@@ -153,18 +155,112 @@
</div> </div>
</div> </div>
</div> </div>
<div class="row">
<div class="col-12">
<div class="form-group">
<label asp-for="ProjectPartItem.Note" class="form-label"></label>
<textarea asp-for="ProjectPartItem.Note" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
</div> </div>
<div class="card-footer py-3 text-right"> <div class="card-footer py-3 d-flex justify-content-between">
<div>
<a class="btn btn-outline-primary" asp-page="PrintPartItem" asp-route-id="@Model.ProjectPartItem.IdProjectPartItem" data-toggle="tooltip" data-placement="top" title="Tiskanje" data-state="primary"><i class="ion ion-md-print"></i>&nbsp;Natisni</a>
</div>
<div>
@if (ViewData["Edit"] != null && (bool)ViewData["Edit"])
{
<button type="submit" class="btn btn-primary">Shrani</button>
}
else
{
<button type="submit" class="btn btn-primary">Dodaj pozicijo dela projekta</button>
}
<a asp-page="Edit" asp-route-id="@ViewBag.IdProject" class="btn btn-default">Prekliči</a>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="card">
<h6 class="card-header">
Operacije
</h6>
<div class="card-body">
@if (ViewData["Edit"] != null && (bool)ViewData["Edit"]) @if (ViewData["Edit"] != null && (bool)ViewData["Edit"])
{ {
<button type="submit" class="btn btn-primary">Shrani</button> <div class="form-row align-items-end mb-3">
<div class="col">
<label class="form-label" for="selProjectPartItemOperation">Naziv</label>
<select id="selProjectPartItemOperation" class="form-control select2" asp-items="ViewBag.IdCodeTableOperationFk"></select>
</div>
<div class="col-auto">
<button type="button" class="btn btn-primary" onclick="addProjectPartItemOperation();">Dodaj</button>
<button type="button" class="btn btn-success" onclick="addDefaultOperations();">Dodaj privzete</button>
</div>
</div>
} }
else
{ <table id="tblOperations" class="table">
<button type="submit" class="btn btn-primary">Dodaj del projekta</button> <thead>
} <tr>
<th class="w-100">Naziv</th>
<a asp-page="Edit" asp-route-id="@ViewBag.IdProject" class="btn btn-default">Prekliči</a> <th class="text-right" style="white-space: nowrap; width: 1%;">Končano</th>
<th class="text-right" style="white-space: nowrap; width: 1%;"></th>
</tr>
</thead>
<tbody>
@foreach (var operation in Model.ProjectPartItemOperations)
{
<tr data-id="@operation.Id" data-id-code-table-operation="@operation.IdCodeTableOperationFk">
<td>
@Html.DisplayFor(modelItem => operation.Operation.Title)
</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<input type="checkbox" @(operation.Finished ? "checked" : "") onchange="toggleOperationFinished(@operation.Id, this);" />
</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" href="javascript:;" onclick="moveOperation(@operation.Id, 'up', this);" title="Gor"><i class="fas fa-arrow-up"></i></a>
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" href="javascript:;" onclick="moveOperation(@operation.Id, 'down', this);" title="Dol"><i class="fas fa-arrow-down"></i></a>
<a class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" href="javascript:;" onclick="deleteProjectPartItemOperation(@operation.Id, this);" title="Izbriši"><i class="fas fa-times"></i></a>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="card">
<h6 class="card-header">
Kooperacije
</h6>
<div class="card-body">
<table class="table">
<thead>
<tr>
<th style="white-space: nowrap; width: 1%;">Številka</th>
<th>Partner</th>
<th style="white-space: nowrap; width: 1%;"></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.CooperationInvoiceItems)
{
<tr>
<td style="white-space: nowrap;">@item.Invoice.InvoiceNumberFormatted</td>
<td>@item.Invoice.Partner?.Title</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<a class="btn btn-xs icon-btn btn-outline-primary borderless" asp-page="/Invoices/Print" asp-route-id="@item.Invoice.IdInvoice" data-toggle="tooltip" data-placement="top" title="Tiskanje" data-state="primary"><i class="ion ion-md-print"></i></a>
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" asp-page="/Invoices/Edit" asp-route-id="@item.Invoice.IdInvoice" data-toggle="tooltip" data-placement="top" title="Urejanje" data-state="secondary"><i class="fas fa-pencil-alt"></i></a>
</td>
</tr>
}
</tbody>
</table>
</div> </div>
</div> </div>
</div> </div>
@@ -246,5 +342,209 @@
location.replace(`CreateEditPartItem?idProjectPartItem=${idProjectPartItem}&idProject=${idProject}&idProjectPart=${idProjectPart}&edit=${edit}&idArticleCopyFrom=${idArticle}`); location.replace(`CreateEditPartItem?idProjectPartItem=${idProjectPartItem}&idProject=${idProject}&idProjectPart=${idProjectPart}&edit=${edit}&idArticleCopyFrom=${idArticle}`);
} }
function moveOperation(idProjectPartItemOperation, direction, element) {
let row = $(element).closest('tr');
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "CreateEditPartItem/?handler=MoveOperation",
data: {
idProjectPartItemOperation,
direction
},
success: function(data) {
if (data.successful) {
if (direction === 'up') {
let prev = row.prev('tr');
if (prev.length) {
row.insertBefore(prev);
}
} else {
let next = row.next('tr');
if (next.length) {
row.insertAfter(next);
}
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
}
});
}
function toggleOperationFinished(idProjectPartItemOperation, checkbox) {
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "CreateEditPartItem/?handler=ToggleProjectPartItemOperationFinished",
data: {
idProjectPartItemOperation
},
success: function(data) {
if (!data.successful) {
Swal.fire('Napaka pri posodabljanju operacije', data.error, 'error');
checkbox.checked = !checkbox.checked;
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
checkbox.checked = !checkbox.checked;
}
});
}
function deleteProjectPartItemOperation(idProjectPartItemOperation, element) {
let row = $(element).closest('tr');
Swal.fire({
title: 'Izbrišem operacijo?',
text: "Tega dejanja ni možno razveljaviti!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Da, izbriši!',
cancelButtonText: 'Prekliči!'
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
type: "DELETE",
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "CreateEditPartItem/?handler=ProjectPartItemOperation",
data: {
idProjectPartItemOperation
},
success: function(data) {
if (data.successful) {
let operationName = row.find('td:first').text().trim();
let operationId = row.data('idCodeTableOperation');
$('#selProjectPartItemOperation').append($('<option></option>').val(operationId).html(operationName));
row.remove();
$('#selProjectPartItemOperation').trigger('change');
} else {
Swal.fire('Napaka pri brisanju operacije', data.error, 'error');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
}
});
}
});
}
function addDefaultOperations() {
let idProjectPartItem = parseInt($('#ProjectPartItem_IdProjectPartItem').val());
if (isNaN(idProjectPartItem)) {
return;
}
$.blockUI();
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "CreateEditPartItem/?handler=AddDefaultOperations",
data: {
idProjectPartItem
},
success: function(data) {
$.unblockUI();
if (data.successful) {
$.each(data.operations, function(i, op) {
let row = `<tr data-id="${op.idProjectPartItemOperation}" data-id-code-table-operation="${op.idCodeTableOperation}">
<td>${op.title}</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<input type="checkbox" onchange="toggleOperationFinished(${op.idProjectPartItemOperation}, this);" />
</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" href="javascript:;" onclick="moveOperation(${op.idProjectPartItemOperation}, 'up', this);" title="Gor"><i class="fas fa-arrow-up"></i></a>
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" href="javascript:;" onclick="moveOperation(${op.idProjectPartItemOperation}, 'down', this);" title="Dol"><i class="fas fa-arrow-down"></i></a>
<a class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" href="javascript:;" onclick="deleteProjectPartItemOperation(${op.idProjectPartItemOperation}, this);" title="Izbriši"><i class="fas fa-times"></i></a>
</td>
</tr>`;
$('#tblOperations tbody').append(row);
$('#selProjectPartItemOperation option[value="' + op.idCodeTableOperation + '"]').remove();
});
$('#selProjectPartItemOperation').trigger('change');
} else {
Swal.fire('Napaka pri dodajanju privzetih operacij', data.error, 'error');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
$.unblockUI();
}
});
}
function addProjectPartItemOperation() {
let idProjectPartItem = parseInt($('#ProjectPartItem_IdProjectPartItem').val());
let idCodeTableOperation = parseInt($('#selProjectPartItemOperation').val());
if (isNaN(idProjectPartItem) || isNaN(idCodeTableOperation)) {
Swal.fire('Izberite operacijo.');
return;
}
$.blockUI();
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "CreateEditPartItem/?handler=ProjectPartItemOperation",
data: {
idProjectPartItem,
idCodeTableOperation
},
success: function(data) {
$.unblockUI();
if (data.successful){
let id = data.idProjectPartItemOperation;
let row = `<tr data-id="${id}" data-id-code-table-operation="${idCodeTableOperation}">
<td>${data.title}</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<input type="checkbox" onchange="toggleOperationFinished(${id}, this);" />
</td>
<td class="text-right" style="white-space: nowrap; width: 1%;">
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" href="javascript:;" onclick="moveOperation(${id}, 'up', this);" title="Gor"><i class="fas fa-arrow-up"></i></a>
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" href="javascript:;" onclick="moveOperation(${id}, 'down', this);" title="Dol"><i class="fas fa-arrow-down"></i></a>
<a class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" href="javascript:;" onclick="deleteProjectPartItemOperation(${id}, this);" title="Izbriši"><i class="fas fa-times"></i></a>
</td>
</tr>`;
$('#tblOperations tbody').append(row);
$('#selProjectPartItemOperation option[value="' + idCodeTableOperation + '"]').remove();
$('#selProjectPartItemOperation').trigger('change');
} else {
Swal.fire('Napaka pri dodajanju operacije',
data.error,
'error');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
$.unblockUI();
}
});
}
</script> </script>
} }

View File

@@ -11,6 +11,7 @@ using EveryThing.Data;
using EveryThing.Models; using EveryThing.Models;
using EveryThing.Models.CodeTable; using EveryThing.Models.CodeTable;
using EveryThing.Models.Project; using EveryThing.Models.Project;
using EveryThing.Models.Invoice;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace EveryThing.Pages.Projects namespace EveryThing.Pages.Projects
@@ -46,6 +47,8 @@ namespace EveryThing.Pages.Projects
ViewData["IdMaterialSupplierFk"] = new SelectList(_context.CodeTablePartners ViewData["IdMaterialSupplierFk"] = new SelectList(_context.CodeTablePartners
.Where(x => x.IdCompanyFk == user.IdCompanyFk && x.Active && x.Supplier) .Where(x => x.IdCompanyFk == user.IdCompanyFk && x.Active && x.Supplier)
.OrderBy(x => x.Title), "IdPartner", "Title"); .OrderBy(x => x.Title), "IdPartner", "Title");
ViewData["IdCodeTableOperationFk"] = new SelectList(_context.CodeTableOperations
.OrderBy(x => x.Title), "Id", "Title");
ViewData["Edit"] = edit; ViewData["Edit"] = edit;
@@ -55,11 +58,29 @@ namespace EveryThing.Pages.Projects
.Include(x => x.ProjectPart) .Include(x => x.ProjectPart)
.ThenInclude(x => x.Project) .ThenInclude(x => x.Project)
.FirstOrDefault(x => x.IdProjectPartItem == idProjectPartItem); .FirstOrDefault(x => x.IdProjectPartItem == idProjectPartItem);
if (ProjectPartItem == null) if (ProjectPartItem == null)
{ {
return NotFound(); return NotFound();
} }
ProjectPartItemOperations = _context.ProjectPartItemOperations
.Include(x => x.Operation)
.Where(x => x.IdProjectPartItemFk == ProjectPartItem.IdProjectPartItem)
.OrderBy(x => x.Order)
.ToList();
var usedOperationIds = ProjectPartItemOperations.Select(x => x.IdCodeTableOperationFk).ToList();
ViewData["IdCodeTableOperationFk"] = new SelectList(_context.CodeTableOperations
.Where(x => !usedOperationIds.Contains(x.Id))
.OrderBy(x => x.Title), "Id", "Title");
CooperationInvoiceItems = _context.InvoiceItems
.Include(x => x.Invoice)
.ThenInclude(x => x.Partner)
.Where(x => x.IdProjectPartItem == ProjectPartItem.IdProjectPartItem
&& x.Invoice.Type == Invoice.InvoiceType.Cooperation)
.ToList();
} }
else else
{ {
@@ -68,6 +89,8 @@ namespace EveryThing.Pages.Projects
NumberOfSets = 1, NumberOfSets = 1,
IdProjectPartFk = idProjectPart IdProjectPartFk = idProjectPart
}; };
ProjectPartItemOperations = new List<ProjectPartItemOperation>();
CooperationInvoiceItems = new List<InvoiceItem>();
} }
if (idArticleCopyFrom != null) if (idArticleCopyFrom != null)
@@ -101,6 +124,10 @@ namespace EveryThing.Pages.Projects
[BindProperty] [BindProperty]
public int IdProject { get; set; } public int IdProject { get; set; }
public IList<ProjectPartItemOperation> ProjectPartItemOperations { get; set; }
public IList<InvoiceItem> CooperationInvoiceItems { get; set; }
public async Task<IActionResult> OnPostAsync(bool edit) public async Task<IActionResult> OnPostAsync(bool edit)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
@@ -158,5 +185,149 @@ namespace EveryThing.Pages.Projects
return new JsonResult(new { items = items }); return new JsonResult(new { items = items });
} }
public IActionResult OnPostProjectPartItemOperation(int idProjectPartItem, int idCodeTableOperation)
{
var maxOrder = _context.ProjectPartItemOperations
.Where(x => x.IdProjectPartItemFk == idProjectPartItem)
.Select(x => (short?)x.Order)
.Max() ?? 0;
var operation = new ProjectPartItemOperation
{
IdProjectPartItemFk = idProjectPartItem,
IdCodeTableOperationFk = idCodeTableOperation,
Finished = false,
Order = (short)(maxOrder + 1)
};
_context.ProjectPartItemOperations.Add(operation);
_context.SaveChanges();
var title = _context.CodeTableOperations
.Where(x => x.Id == idCodeTableOperation)
.Select(x => x.Title)
.FirstOrDefault();
return new JsonResult(new { successful = true, idProjectPartItemOperation = operation.Id, title });
}
public IActionResult OnPostToggleProjectPartItemOperationFinished(int idProjectPartItemOperation)
{
var successful = true;
var error = "";
var operation = _context.ProjectPartItemOperations
.FirstOrDefault(x => x.Id == idProjectPartItemOperation);
if (operation != null)
{
operation.Finished = !operation.Finished;
_context.SaveChanges();
}
else
{
successful = false;
error = $"Operation with ID: {idProjectPartItemOperation} not found";
}
return new JsonResult(new { successful, error, finished = operation?.Finished });
}
public IActionResult OnDeleteProjectPartItemOperation(int idProjectPartItemOperation)
{
var successful = true;
var error = "";
var operation = _context.ProjectPartItemOperations
.FirstOrDefault(x => x.Id == idProjectPartItemOperation);
if (operation != null)
{
_context.ProjectPartItemOperations.Remove(operation);
_context.SaveChanges();
}
else
{
successful = false;
error = $"Operation with ID: {idProjectPartItemOperation} not found";
}
return new JsonResult(new { successful, error, idProjectPartItemOperation });
}
public IActionResult OnPostAddDefaultOperations(int idProjectPartItem)
{
var existingOperationIds = _context.ProjectPartItemOperations
.Where(x => x.IdProjectPartItemFk == idProjectPartItem)
.Select(x => x.IdCodeTableOperationFk)
.ToList();
var defaultOperations = _context.CodeTableOperations
.Where(x => x.Default && !existingOperationIds.Contains(x.Id))
.OrderBy(x => x.Title)
.ToList();
var added = new List<object>();
var maxOrder = _context.ProjectPartItemOperations
.Where(x => x.IdProjectPartItemFk == idProjectPartItem)
.Select(x => (short?)x.Order)
.Max() ?? 0;
foreach (var op in defaultOperations)
{
maxOrder++;
var newOp = new ProjectPartItemOperation
{
IdProjectPartItemFk = idProjectPartItem,
IdCodeTableOperationFk = op.Id,
Finished = false,
Order = maxOrder
};
_context.ProjectPartItemOperations.Add(newOp);
_context.SaveChanges();
added.Add(new { idProjectPartItemOperation = newOp.Id, idCodeTableOperation = op.Id, title = op.Title });
}
return new JsonResult(new { successful = true, operations = added });
}
public IActionResult OnPostMoveOperation(int idProjectPartItemOperation, string direction)
{
var operation = _context.ProjectPartItemOperations
.FirstOrDefault(x => x.Id == idProjectPartItemOperation);
if (operation == null)
return new JsonResult(new { successful = false, error = "Operation not found" });
ProjectPartItemOperation neighbor;
if (direction == "up")
{
neighbor = _context.ProjectPartItemOperations
.Where(x => x.IdProjectPartItemFk == operation.IdProjectPartItemFk && x.Order < operation.Order)
.OrderByDescending(x => x.Order)
.FirstOrDefault();
}
else
{
neighbor = _context.ProjectPartItemOperations
.Where(x => x.IdProjectPartItemFk == operation.IdProjectPartItemFk && x.Order > operation.Order)
.OrderBy(x => x.Order)
.FirstOrDefault();
}
if (neighbor == null)
return new JsonResult(new { successful = true });
var temp = operation.Order;
operation.Order = neighbor.Order;
neighbor.Order = temp;
_context.SaveChanges();
return new JsonResult(new { successful = true });
}
} }
} }

View File

@@ -7,65 +7,200 @@
Layout = "~/Pages/Layouts/_Layout.cshtml"; Layout = "~/Pages/Layouts/_Layout.cshtml";
} }
<form method="post"> <h4 class="d-flex justify-content-between align-items-center w-100 font-weight-bold py-1 mb-4">
<span>
<span class="text-muted font-weight-light">Projekt /</span> Uvoz pozicij dela projekta
</span>
</h4>
<h4 class="d-flex justify-content-between align-items-center w-100 font-weight-bold py-1 mb-4"> <div class="row">
<span> <div class="col-6">
<span class="text-muted font-weight-light">Projekt /</span> Uvoz pozicij dela projekta <div class="card">
</span> <!-- Step 1: Upload -->
</h4> <div id="step-upload">
<div class="row">
<div class="col-6">
<div class="card">
<h6 class="card-header"> <h6 class="card-header">
Povezovanje @Model.FileName z pozicijo Podatki pozicije
</h6> </h6>
<div class="card-body"> <div class="card-body">
<input type="hidden" asp-for="IdProjectPart" />
<input type="hidden" asp-for="IdProject" />
<input type="hidden" asp-for="FileName" />
<input type="hidden" asp-for="SelectedItems" name="selectedItems" class="inp-selected-items" />
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
@{ <div class="form-group">
foreach (var item in Model.ExcelItems) <input type="file" id="fileInput" name="postedFiles" />
{ </div>
<div class="form-group">
<label class="control-label">@item.Name</label>
<select data-index="@item.CellIndex" class="form-control select-item" asp-items="ViewBag.ProjectPartItems"></select>
</div>
}
}
</div> </div>
</div> </div>
</div> </div>
<div class="card-footer py-3 text-right"> <div class="card-footer py-3 text-right">
<button type="submit" class="btn btn-primary" onclick="prepareData(); return true;">Potrdi</button> <button type="button" id="btnUpload" class="btn btn-primary">Naloži excel</button>
<a asp-page="Edit" asp-route-id="IdProject" class="btn btn-default">Prekliči</a> <a asp-page="Edit" asp-route-id="@Model.IdProject" class="btn btn-default">Prekliči</a>
</div>
</div>
<!-- Step 2: Mapping -->
<div id="step-mapping" style="display: none;">
<h6 class="card-header">
Povezovanje <span id="mappingFileName"></span> z pozicijo
</h6>
<div class="card-body">
<div class="row">
<div class="col-12" id="mappingFields">
</div>
</div>
</div>
<div class="card-footer py-3 text-right">
<button type="button" id="btnImport" class="btn btn-primary">Potrdi</button>
<a asp-page="Edit" asp-route-id="@Model.IdProject" class="btn btn-default">Prekliči</a>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="col-6">
<div id="validation-errors" style="display: none;">
<div class="card border-danger">
<h6 class="card-header bg-danger text-white">Napake pri uvozu</h6>
<div class="card-body p-0">
<table class="table table-sm table-bordered m-0">
<thead>
<tr>
<th>Vrstica</th>
<th>Polje</th>
<th>Vrednost</th>
<th>Napaka</th>
</tr>
</thead>
<tbody id="validation-errors-body">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div> @Html.AntiForgeryToken()
</form>
@section Scripts { @section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");} @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript"> <script type="text/javascript">
function prepareData(){ var uploadedFileName = '';
let data = "";
$('.select-item').each(function(index, element) { $('#btnUpload').click(function () {
let value = $(element).val(); var fileInput = document.getElementById('fileInput');
if (value !== '') { if (fileInput.files.length === 0) {
let dataIndex = $(element).attr("data-index"); Swal.fire('Izberite datoteko.');
data += `${dataIndex};${value}#`; return;
}
var formData = new FormData();
formData.append('postedFiles', fileInput.files[0]);
formData.append('idProject', '@Model.IdProject');
formData.append('idProjectPart', '@Model.IdProjectPart');
$.blockUI();
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "CreatePartItemImportExcel?handler=Upload",
data: formData,
processData: false,
contentType: false,
success: function (data) {
$.unblockUI();
if (data.successful) {
uploadedFileName = data.fileName;
$('#mappingFileName').text(data.fileName);
var container = $('#mappingFields');
container.empty();
$.each(data.excelItems, function (i, item) {
var group = $('<div class="form-group"></div>');
group.append('<label class="control-label">' + item.name + '</label>');
var select = $('<select class="form-control select-item" data-index="' + item.cellIndex + '"></select>');
select.append('<option value="">Ni izbrano</option>');
$.each(data.mappingOptions, function (j, opt) {
select.append('<option value="' + opt.name + '">' + opt.display + '</option>');
});
group.append(select);
container.append(group);
});
$('#step-upload').hide();
$('#step-mapping').show();
} else {
Swal.fire('Napaka', data.error, 'error');
}
},
error: function (xhr) {
$.unblockUI();
console.log(xhr);
alert(xhr.responseText);
} }
}); });
$('.inp-selected-items').val(data); });
}
$('#btnImport').click(function () {
var data = "";
$('.select-item').each(function (index, element) {
var value = $(element).val();
if (value !== '') {
var dataIndex = $(element).attr("data-index");
data += dataIndex + ";" + value + "#";
}
});
if (data === '') {
Swal.fire('Izberite vsaj eno polje.');
return;
}
$.blockUI();
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "CreatePartItemImportExcel?handler=Import",
data: {
selectedItems: data,
fileName: uploadedFileName,
idProjectPart: '@Model.IdProjectPart',
idProject: '@Model.IdProject'
},
success: function (data) {
$.unblockUI();
if (data.successful) {
window.location.href = data.redirectUrl;
} else if (data.validationErrors && data.validationErrors.length > 0) {
var tbody = $('#validation-errors-body');
tbody.empty();
$.each(data.validationErrors, function (i, err) {
tbody.append('<tr>' +
'<td>' + err.row + '</td>' +
'<td>' + err.property + '</td>' +
'<td><code>' + (err.value || '') + '</code></td>' +
'<td class="text-danger">' + err.message + '</td>' +
'</tr>');
});
$('#validation-errors').show();
Swal.fire('Napaka pri uvozu', 'Podatki vsebujejo ' + data.validationErrors.length + ' napak. Preglejte tabelo napak.', 'error');
} else {
Swal.fire('Napaka', data.error, 'error');
}
},
error: function (xhr) {
$.unblockUI();
console.log(xhr);
alert(xhr.responseText);
}
});
});
</script> </script>
} }

View File

@@ -48,31 +48,48 @@ namespace EveryThing.Pages.Projects
public string SelectedItems { get; set; } public string SelectedItems { get; set; }
public IActionResult OnGet(int idProject, int idProjectPart, string fileName) public IActionResult OnGet(int idProject, int idProjectPart)
{ {
var user = _userManager.GetUserAsync(User).Result;
IdProject = idProject; IdProject = idProject;
IdProjectPart = idProjectPart; IdProjectPart = idProjectPart;
FileName = fileName;
var tmpList = typeof(Models.Project.ProjectPartItem).GetProperties()
.Where(x => x.GetCustomAttributes(true).Length > 0 && x.GetCustomAttributes(true).Any(y => y.GetType() == typeof(System.ComponentModel.DataAnnotations.DisplayAttribute)))
.Select(x => new
{
Name = x.Name,
Display = ((System.ComponentModel.DataAnnotations.DisplayAttribute)x.GetCustomAttributes(true).First(y => y.GetType() == typeof(System.ComponentModel.DataAnnotations.DisplayAttribute))).Name
}).ToList();
tmpList.Insert(0, new { Name = "", Display = "Ni izbrano" });
ViewData["ProjectPartItems"] = new SelectList(tmpList, "Name", "Display");
ExcelItems = new List<ExcelItem>(); ExcelItems = new List<ExcelItem>();
var path = Path.Combine(_hostingEnvironment.WebRootPath, "Uploads", "TempExcelImport", fileName);
var xlWorkbook = new XLWorkbook(path); return Page();
}
//ONLY FIRST LIST
public async Task<IActionResult> OnPostUpload(int idProject, int idProjectPart, List<IFormFile> postedFiles)
{
if (postedFiles == null
|| postedFiles.Count != 1)
{
return new JsonResult(new { successful = false, error = "Izberite eno datoteko." });
}
var path = Path.Combine(_hostingEnvironment.WebRootPath, "Uploads", "TempExcelImport");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
else
{
//Pocistimo mapo
foreach (var fileInfo in new DirectoryInfo(path).GetFiles("*.*"))
{
fileInfo.Delete();
}
}
var postedFile = postedFiles[0];
var fileName = postedFile.FileName;
await using (var stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
await postedFile.CopyToAsync(stream);
}
// Read excel headers
var excelItems = new List<ExcelItem>();
var filePath = Path.Combine(path, fileName);
var xlWorkbook = new XLWorkbook(filePath);
var worksheet = xlWorkbook.Worksheet(1); var worksheet = xlWorkbook.Worksheet(1);
int i = 1; int i = 1;
@@ -82,26 +99,36 @@ namespace EveryThing.Pages.Projects
int j = 1; int j = 1;
while (!row.Cell(j).IsEmpty()) while (!row.Cell(j).IsEmpty())
{ {
var cellData = row.Cell(j).Value; excelItems.Add(new ExcelItem
ExcelItems.Add(new ExcelItem
{ {
CellIndex = j, CellIndex = j,
Name = cellData.ToString(), Name = row.Cell(j).Value.ToString(),
}); });
j++; j++;
} }
} }
return Page(); // Build mapping options
var mappingOptions = typeof(Models.Project.ProjectPartItem).GetProperties()
.Where(x => x.GetCustomAttributes(true).Length > 0 && x.GetCustomAttributes(true).Any(y => y.GetType() == typeof(System.ComponentModel.DataAnnotations.DisplayAttribute)))
.Select(x => new
{
name = x.Name,
display = ((System.ComponentModel.DataAnnotations.DisplayAttribute)x.GetCustomAttributes(true).First(y => y.GetType() == typeof(System.ComponentModel.DataAnnotations.DisplayAttribute))).Name
}).ToList();
return new JsonResult(new { successful = true, fileName, excelItems, mappingOptions });
} }
public async Task<IActionResult> OnPostAsync(string selectedItems) public async Task<IActionResult> OnPostImport(string selectedItems, string fileName, int idProjectPart, int idProject)
{ {
if (selectedItems == "") FileName = fileName;
IdProjectPart = idProjectPart;
IdProject = idProject;
if (string.IsNullOrEmpty(selectedItems))
{ {
return Page(); //TODO Error return new JsonResult(new { successful = false, error = "Izberite vsaj eno polje." });
} }
var user = _userManager.GetUserAsync(User).Result; var user = _userManager.GetUserAsync(User).Result;
@@ -128,6 +155,73 @@ namespace EveryThing.Pages.Projects
//ONLY FIRST LIST //ONLY FIRST LIST
var worksheet = xlWorkbook.Worksheet(1); var worksheet = xlWorkbook.Worksheet(1);
// Build display name lookup for properties
var propertyDisplayNames = typeof(Models.Project.ProjectPartItem).GetProperties()
.Where(x => x.GetCustomAttributes(true).Any(y => y is System.ComponentModel.DataAnnotations.DisplayAttribute))
.ToDictionary(
x => x.Name,
x => ((System.ComponentModel.DataAnnotations.DisplayAttribute)x.GetCustomAttributes(true).First(y => y is System.ComponentModel.DataAnnotations.DisplayAttribute)).Name
);
// Validation pass - check all rows before importing
var errors = new List<object>();
int validationRow = 2; // Skip header
while (!worksheet.Row(validationRow).IsEmpty())
{
IXLRow row = worksheet.Row(validationRow);
// Check if all mapped cells in the row are empty
bool allEmpty = excelItems.All(ei =>
row.Cell(ei.CellIndex) == null || string.IsNullOrWhiteSpace(row.Cell(ei.CellIndex).Value.ToString()));
if (allEmpty)
{
errors.Add(new { row = validationRow, property = "-", value = "", message = "Vsa polja v vrstici so prazna." });
validationRow++;
continue;
}
foreach (var excelItem in excelItems)
{
if (row.Cell(excelItem.CellIndex) == null)
continue;
string value = row.Cell(excelItem.CellIndex).Value.ToString();
string displayName = propertyDisplayNames.ContainsKey(excelItem.Name) ? propertyDisplayNames[excelItem.Name] : excelItem.Name;
// Empty individual cells are allowed - skip validation
if (string.IsNullOrWhiteSpace(value))
continue;
if (excelItem.Name is "IdItemFk" or "IdMaterialFk" or "IdMaterialSupplierFk")
{
// These are text lookups, no type conversion needed
continue;
}
// Validate type conversion for other properties
var propertyInfo = typeof(Models.Project.ProjectPartItem).GetProperties().FirstOrDefault(x => x.Name == excelItem.Name);
if (propertyInfo != null)
{
try
{
var targetType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
Convert.ChangeType(value, targetType);
}
catch
{
errors.Add(new { row = validationRow, property = displayName, value, message = $"Ni mogoče pretvoriti v tip {propertyInfo.PropertyType.Name}." });
}
}
}
validationRow++;
}
if (errors.Count > 0)
{
return new JsonResult(new { successful = false, validationErrors = errors });
}
var insertedParts = _context.ProjectPartItems.Where(x => x.IdProjectPartFk == IdProjectPart); var insertedParts = _context.ProjectPartItems.Where(x => x.IdProjectPartFk == IdProjectPart);
var currentPositionNumber = insertedParts.Any() var currentPositionNumber = insertedParts.Any()
@@ -158,6 +252,9 @@ namespace EveryThing.Pages.Projects
string value = row.Cell(excelItem.CellIndex).Value.ToString(); string value = row.Cell(excelItem.CellIndex).Value.ToString();
if (string.IsNullOrWhiteSpace(value))
continue;
if (excelItem.Name is "IdItemFk" or "IdMaterialFk") if (excelItem.Name is "IdItemFk" or "IdMaterialFk")
{ {
var completableItem = _context.CodeTableItems.FirstOrDefault(x => x.Title == value && x.Active == true); var completableItem = _context.CodeTableItems.FirstOrDefault(x => x.Title == value && x.Active == true);
@@ -218,7 +315,7 @@ namespace EveryThing.Pages.Projects
System.IO.File.Delete(path); System.IO.File.Delete(path);
return RedirectToPage("./Edit", new {id = IdProject}); return new JsonResult(new { successful = true, redirectUrl = Url.Page("./Edit", new { id = IdProject }) });
} }
public class ExcelItem public class ExcelItem

View File

@@ -1,50 +0,0 @@
@page
@using EveryThing.Models.Project
@model EveryThing.Pages.Projects.CreatePartItemUploadExcelModel
@{
ViewData["Title"] = "Uvoz pozicij dela projekta";
Layout = "~/Pages/Layouts/_Layout.cshtml";
}
<form method="post" enctype="multipart/form-data">
<h4 class="d-flex justify-content-between align-items-center w-100 font-weight-bold py-1 mb-4">
<span>
<span class="text-muted font-weight-light">Projekt /</span> Uvoz pozicij dela projekta
</span>
</h4>
<div class="row">
<div class="col-6">
<div class="card">
<h6 class="card-header">
Podatki pozicije
</h6>
<div class="card-body">
<input type="hidden" asp-for="IdProjectPart" name="idProjectPart" />
<input type="hidden" asp-for="IdProject" name="idProject"/>
<div class="row">
<div class="col-12">
<div class="form-group">
<input type="file" name="postedFiles" multiple/>
</div>
</div>
</div>
</div>
<div class="card-footer py-3 text-right">
<input type="submit" class="btn btn-primary" value="Naloži excel" asp-page-handler="Upload" />
<a asp-page="Edit" asp-route-id="IdProject" class="btn btn-default">Prekliči</a>
</div>
</div>
</div>
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

View File

@@ -1,131 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using EveryThing.Data;
using EveryThing.Models;
using EveryThing.Models.Project;
using Microsoft.AspNetCore.Http;
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace EveryThing.Pages.Projects
{
[Authorize(Roles = "Administrator,ProjecThingUser")]
public class CreatePartItemUploadExcelModel : PageModel
{
private readonly IWebHostEnvironment _hostingEnvironment;
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityApplicationUser> _userManager;
private readonly SignInManager<IdentityApplicationUser> _loginManager;
private readonly RoleManager<IdentityApplicationRole> _roleManager;
public CreatePartItemUploadExcelModel(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager, SignInManager<IdentityApplicationUser> loginManager, RoleManager<IdentityApplicationRole> roleManager, IWebHostEnvironment environment)
{
_context = context;
_userManager = userManager;
_loginManager = loginManager;
_roleManager = roleManager;
_hostingEnvironment = environment;
}
[BindProperty]
public IFormFile File { get; set; }
[BindProperty]
public int IdProject { get; set; }
[BindProperty]
public int IdProjectPart { get; set; }
public IActionResult OnGet(int idProject, int idProjectPart)
{
var user = _userManager.GetUserAsync(User).Result;
IdProject = idProject;
IdProjectPart = idProjectPart;
return Page();
}
//public async Task<IActionResult> OnPostAsync()
//{
// if (!ModelState.IsValid)
// {
// return Page();
// }
// string uploads = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
// if (File.Length > 0)
// {
// string filePath = Path.Combine(uploads, File.FileName);
// using (Stream fileStream = new FileStream(filePath, FileMode.Create))
// {
// await File.CopyToAsync(fileStream);
// }
// }
// return RedirectToPage("./Edit");
//}
//public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files)
//{
// long size = files.Sum(f => f.Length);
// foreach (var formFile in files)
// {
// if (formFile.Length > 0)
// {
// var filePath = Path.GetTempFileName();
// System.Diagnostics.Debug.WriteLine(filePath);
// using (var stream = System.IO.File.Create(filePath))
// {
// await formFile.CopyToAsync(stream);
// }
// }
// }
// // Process uploaded files
// // Don't rely on or trust the FileName property without validation.
// return RedirectToPage("./Edit");
//}
public async Task<IActionResult> OnPostUpload(int idProject, int idProjectPart, List<IFormFile> postedFiles)
{
if (postedFiles == null
|| postedFiles.Count != 1)
{
return Page();//TODO return error
}
var path = Path.Combine(_hostingEnvironment.WebRootPath, "Uploads", "TempExcelImport");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
else
{
//Pocistimo mapo
foreach (var fileInfo in new DirectoryInfo(path).GetFiles("*.*"))
{
fileInfo.Delete();
}
}
var postedFile = postedFiles[0];
var fileName = postedFile.FileName;//Guid.NewGuid().ToString().Replace("-", "_") + Path.GetExtension(postedFile.FileName);
await using (var stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
await postedFile.CopyToAsync(stream);
}
return RedirectToPage("./CreatePartItemImportExcel", new { idProject = idProject, idProjectPart = idProjectPart, fileName = fileName});
}
}
}

View File

@@ -1,7 +1,11 @@
@using System.Globalization @using System.Globalization
@model EveryThing.Models.Project.ProjectPartItem @model EveryThing.Models.Project.ProjectPartItem
<tr data-idpartitem="@Model.IdProjectPartItem"> @{
var hasNote = !string.IsNullOrWhiteSpace(Model.Note);
}
<tr data-idpartitem="@Model.IdProjectPartItem" class="@(hasNote ? "project-part-item-has-note" : "")" style="cursor: pointer;" ondblclick="if(!$(event.target).closest('a,button,input').length) { $('[data-toggle=tooltip]').tooltip('hide'); $(this).find('.btn-tbl-inline-edit').click(); }">
<td style="width: 20px;"> <td style="width: 20px;">
@if(Model.Status != Models.Project.ProjectPartItemStatus.Shipped) @if(Model.Status != Models.Project.ProjectPartItemStatus.Shipped)
{ {
@@ -18,6 +22,10 @@
@Html.DisplayFor(modelItem => Model.IdItemFk) @Html.DisplayFor(modelItem => Model.IdItemFk)
} }
<br/> <br/>
@if (hasNote)
{
<i class="fas fa-sticky-note text-warning mr-1" data-toggle="tooltip" data-placement="top" title="@Model.Note"></i>
}
@(Model.ProjectPartNumberFormatted) @(Model.ProjectPartNumberFormatted)
</td> </td>
<td> <td>
@@ -35,6 +43,20 @@
<br/> <br/>
@Html.DisplayFor(modelItem => Model.MaterialDimensions) @Html.DisplayFor(modelItem => Model.MaterialDimensions)
</td> </td>
<td>
@{
var ops = Model.ProjectPartItemOperation;
var nextOp = ops?.Where(x => !x.Finished).OrderBy(x => x.Order).FirstOrDefault();
}
@if (ops != null && ops.Any() && nextOp == null)
{
<span class="badge badge-success"><i class="fas fa-check"></i>&nbsp;Vse zaključeno</span>
}
else
{
@(nextOp?.Operation?.Title ?? "")
}
</td>
<td class="table-number"> <td class="table-number">
@(Model.NumberOfItems.ToString("0.00", new CultureInfo("sl-SI"))) @(Model.NumberOfItems.ToString("0.00", new CultureInfo("sl-SI")))
<br/> <br/>
@@ -71,9 +93,9 @@
@Html.DisplayFor(modelItem => Model.DeliveryDate) @Html.DisplayFor(modelItem => Model.DeliveryDate)
</td> </td>
<td class="text-right" style="width: 90px;"> <td class="text-right" style="width: 90px;">
<a asp-page="CreateEditPartItem" asp-route-idProjectPartItem="@Model.IdProjectPartItem" asp-route-idProject="@Model.ProjectPart.IdProjectFk" asp-route-idProjectPart="@Model.IdProjectPartFk" asp-route-edit="@true" class="btn btn-xs icon-btn btn-outline-secondary borderless" data-state="secondary"><i class="far fa-edit"></i></a> <a asp-page="CreateEditPartItem" asp-route-idProjectPartItem="@Model.IdProjectPartItem" asp-route-idProject="@Model.ProjectPart.IdProjectFk" asp-route-idProjectPart="@Model.IdProjectPartFk" asp-route-edit="@true" class="btn btn-xs icon-btn btn-outline-secondary borderless" data-state="secondary" data-toggle="tooltip" data-placement="top" title="Urejanje"><i class="far fa-edit"></i></a>
<a class="btn btn-xs icon-btn btn-outline-secondary borderless" data-state="secondary" href='javascript:;'><i class="fas fa-pencil-alt" hx-get="@Url.Page("Edit", "EditPartItem", new {id = Model.IdProjectPartItem})" hx-swap="outerHTML" hx-target="closest tr"></i></a> <a class="btn btn-xs icon-btn btn-outline-secondary borderless" data-state="secondary" href='javascript:;' data-toggle="tooltip" data-placement="top" title="Hitro urejanje"><i class="fas fa-pencil-alt btn-tbl-inline-edit" hx-get="@Url.Page("Edit", "EditPartItem", new {id = Model.IdProjectPartItem})" hx-swap="outerHTML" hx-target="closest tr"></i></a>
<a class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" href='javascript:;' onclick="deletePartItem(this)"><i class="fas fa-times"></i></a> <a class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" href='javascript:;' onclick="deletePartItem(this)" data-toggle="tooltip" data-placement="top" title="Izbriši"><i class="fas fa-times"></i></a>
<a style="display: none;" id="btnTblCancel_@(Model.IdProjectPartItem.ToString())" href='javascript:;' class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" hx-get="@Url.Page("Edit", "DetailPartItem", new { id = Model.IdProjectPartItem })" hx-swap="outerHTML" hx-target="closest tr"><i class="fas fa-ban"></i></a> <a style="display: none;" id="btnTblCancel_@(Model.IdProjectPartItem.ToString())" href='javascript:;' class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" data-toggle="tooltip" data-placement="top" title="Prekliči" hx-get="@Url.Page("Edit", "DetailPartItem", new { id = Model.IdProjectPartItem })" hx-swap="outerHTML" hx-target="closest tr"><i class="fas fa-ban"></i></a>
</td> </td>
</tr> </tr>

View File

@@ -13,6 +13,10 @@
border-top: none; border-top: none;
} }
.project-part-item-has-note {
background-color: #fff8e1;
}
.tab-panel-invoices{ .tab-panel-invoices{
height: 490px; height: 490px;
overflow-y: auto; overflow-y: auto;
@@ -195,7 +199,7 @@
<tbody> <tbody>
@foreach (var invoice in Model.Invoices.Where(x => x.Type == Models.Invoice.Invoice.InvoiceType.Order)) @foreach (var invoice in Model.Invoices.Where(x => x.Type == Models.Invoice.Invoice.InvoiceType.Order))
{ {
<tr class="invoice-row" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem.IdProjectPartFk) ?? Array.Empty<int>())"> <tr class="invoice-row" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem?.IdProjectPartFk ?? 0) ?? Array.Empty<int>())">
<td> <td>
@Html.DisplayFor(modelItem => invoice.InvoiceYear) - @Html.DisplayFor(modelItem => invoice.InvoiceNumber) @Html.DisplayFor(modelItem => invoice.InvoiceYear) - @Html.DisplayFor(modelItem => invoice.InvoiceNumber)
</td> </td>
@@ -261,7 +265,7 @@
<tbody> <tbody>
@foreach (var invoice in Model.Invoices.Where(x => x.Type == Models.Invoice.Invoice.InvoiceType.DeliveryNote)) @foreach (var invoice in Model.Invoices.Where(x => x.Type == Models.Invoice.Invoice.InvoiceType.DeliveryNote))
{ {
<tr class="invoice-row" data-idinvoice="@invoice.IdInvoice" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem.IdProjectPartFk) ?? Array.Empty<int>())"> <tr class="invoice-row" data-idinvoice="@invoice.IdInvoice" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem?.IdProjectPartFk ?? 0) ?? Array.Empty<int>())">
<td style="width: 20px;"> <td style="width: 20px;">
@if (invoice.State == Invoice.InvoiceState.Confirmed) @if (invoice.State == Invoice.InvoiceState.Confirmed)
{ {
@@ -331,7 +335,7 @@
<tbody> <tbody>
@foreach (var invoice in Model.Invoices.Where(x => x.Type == Models.Invoice.Invoice.InvoiceType.Invoice)) @foreach (var invoice in Model.Invoices.Where(x => x.Type == Models.Invoice.Invoice.InvoiceType.Invoice))
{ {
<tr class="invoice-row" data-idinvoice="@invoice.IdInvoice" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem.IdProjectPartFk) ?? Array.Empty<int>())"> <tr class="invoice-row" data-idinvoice="@invoice.IdInvoice" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem?.IdProjectPartFk ?? 0) ?? Array.Empty<int>())">
<td> <td>
@Html.DisplayFor(modelItem => invoice.InvoiceYear) - @Html.DisplayFor(modelItem => invoice.InvoiceNumber) @Html.DisplayFor(modelItem => invoice.InvoiceYear) - @Html.DisplayFor(modelItem => invoice.InvoiceNumber)
</td> </td>
@@ -533,7 +537,7 @@
<tbody> <tbody>
@foreach (var invoice in Model.Invoices.Where(x => x.Type == Invoice.InvoiceType.Cooperation)) @foreach (var invoice in Model.Invoices.Where(x => x.Type == Invoice.InvoiceType.Cooperation))
{ {
<tr class="invoice-row" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem.IdProjectPartFk) ?? Array.Empty<int>())"> <tr class="invoice-row" data-idparts="@string.Join(",", invoice.InvoiceInvoiceItem?.Select(x => x.ProjectPartItem?.IdProjectPartFk ?? 0) ?? Array.Empty<int>())">
<td> <td>
@Html.DisplayFor(modelItem => invoice.InvoiceYear) - @Html.DisplayFor(modelItem => invoice.InvoiceNumber) @Html.DisplayFor(modelItem => invoice.InvoiceYear) - @Html.DisplayFor(modelItem => invoice.InvoiceNumber)
</td> </td>
@@ -614,6 +618,7 @@
} }
<div style="float: right"> <div style="float: right">
<input type="text" class="form-control form-control-sm d-inline-block" style="width: 150px; vertical-align: middle;" placeholder="Iskanje..." oninput="searchPartItems(this, @part.IdProjectPart);" />
<a class="btn btn-xs icon-btn btn-outline-primary borderless" asp-page="/Projects/PrintProjectPartPaths" asp-route-id="@part.IdProjectPart" data-toggle="tooltip" data-placement="top" title="Tiskanje" data-state="primary"><i class="ion ion-md-print"></i></a> <a class="btn btn-xs icon-btn btn-outline-primary borderless" asp-page="/Projects/PrintProjectPartPaths" asp-route-id="@part.IdProjectPart" data-toggle="tooltip" data-placement="top" title="Tiskanje" data-state="primary"><i class="ion ion-md-print"></i></a>
<a asp-page="/Files/Upload" asp-route-idReferenceFk="@part.IdProjectPart" asp-route-fileType="@Models.FileType.ProjectPart" class="btn btn-xs icon-btn btn-outline-secondary borderless" data-toggle="tooltip" data-placement="top" title="Priloži datoteko" data-state="secondary"><i class="fas fa-upload"></i></a> <a asp-page="/Files/Upload" asp-route-idReferenceFk="@part.IdProjectPart" asp-route-fileType="@Models.FileType.ProjectPart" class="btn btn-xs icon-btn btn-outline-secondary borderless" data-toggle="tooltip" data-placement="top" title="Priloži datoteko" data-state="secondary"><i class="fas fa-upload"></i></a>
<a data-idprojectpart="@part.IdProjectPart" class="btn btn-xs icon-btn btn-outline-secondary borderless" data-toggle="tooltip" data-placement="top" title="Kopiraj del projekta" data-state="secondary" href="javascript:;" onclick="copyProjectPart(this);"><i class="far fa-copy"></i></a> <a data-idprojectpart="@part.IdProjectPart" class="btn btn-xs icon-btn btn-outline-secondary borderless" data-toggle="tooltip" data-placement="top" title="Kopiraj del projekta" data-state="secondary" href="javascript:;" onclick="copyProjectPart(this);"><i class="far fa-copy"></i></a>
@@ -643,6 +648,9 @@
<br/> <br/>
Dimenzije surovca Dimenzije surovca
</th> </th>
<th>
Naslednja operacija
</th>
<th class="table-header-number"> <th class="table-header-number">
<div data-toggle="tooltip" data-placement="top" title="Število kosov<br/>Število kompletov" data-html="true"> <div data-toggle="tooltip" data-placement="top" title="Število kosov<br/>Število kompletov" data-html="true">
Kos Kos
@@ -726,7 +734,7 @@
</div> </div>
<div class="col-6" style="text-align: right"> <div class="col-6" style="text-align: right">
<a asp-page="CreateEditPartItem" asp-route-idProject="@Model.Project.IdProject" asp-route-idProjectPart="@part.IdProjectPart" asp-route-edit="@false" class="btn btn-sm btn-primary">Dodaj pozicijo</a> <a asp-page="CreateEditPartItem" asp-route-idProject="@Model.Project.IdProject" asp-route-idProjectPart="@part.IdProjectPart" asp-route-edit="@false" class="btn btn-sm btn-primary">Dodaj pozicijo</a>
<a asp-page="CreatePartItemUploadExcel" asp-route-idProject="@Model.Project.IdProject" asp-route-idProjectPart="@part.IdProjectPart" class="btn btn-sm btn-success">Uvozi kosovnico</a> <a asp-page="CreatePartItemImportExcel" asp-route-idProject="@Model.Project.IdProject" asp-route-idProjectPart="@part.IdProjectPart" class="btn btn-sm btn-success">Uvozi kosovnico</a>
</div> </div>
</div> </div>
</div> </div>
@@ -738,14 +746,16 @@
</div> </div>
<div class="card-footer py-3"> <div class="card-footer py-3">
<div class="row"> <div class="row">
<div class="col-6"> <div class="col-9">
<button class="btn btn-success" onclick="createOrderSelectPartner(false); return false;">Kreiraj naročilo</button> <button class="btn btn-success" onclick="createOrderSelectPartner(false); return false;">Kreiraj naročilo</button>
<button class="btn btn-success" onclick="createOrderSelectPartner(true); return false;">Kreiraj povpraševanje</button> <button class="btn btn-success" onclick="createOrderSelectPartner(true); return false;">Kreiraj povpraševanje materiala</button>
<button class="btn btn-secondary" onclick="createOrderSelectPartner(true, 2); return false;">Kreiraj povpraševanje izdelka</button>
<button class="btn btn-info" onclick="createCooperationSelectPartner(); return false;">Kreiraj kooperacijo</button> <button class="btn btn-info" onclick="createCooperationSelectPartner(); return false;">Kreiraj kooperacijo</button>
<button class="btn btn-primary" onclick="createInvoice(); return false;">Kreiraj dobavnico</button> <button class="btn btn-primary" onclick="createInvoice(); return false;">Kreiraj dobavnico</button>
<button class="btn btn-secondary" onclick="bulkPrintPartItems(); return false;"><i class="ion ion-md-print"></i> Natisni naloge</button>
</div> </div>
<div class="col-6 text-right"> <div class="col-3 text-right">
<a asp-page="CreatePart" asp-route-idProject="@Model.Project.IdProject" class="btn btn-primary pull-right">Nov del projekta</a> <a asp-page="CreatePart" asp-route-idProject="@Model.Project.IdProject" class="btn btn-primary pull-right">Nov del projekta</a>
</div> </div>
</div> </div>
@@ -773,9 +783,15 @@
<script> <script>
const openProjectPartCookieName = 'openProjectPart' + @Html.Raw(Model.Project.IdProject); const openProjectPartCookieName = 'openProjectPart' + @Html.Raw(Model.Project.IdProject);
$(document).ready(function() { $(document).ready(function() {
document.body.addEventListener('htmx:beforeRequest',
function(evt) {
$('[data-toggle=tooltip]').tooltip('hide');
});
document.body.addEventListener('htmx:afterSettle', document.body.addEventListener('htmx:afterSettle',
function(evt) { function(evt) {
$('.select2').select2(); $('.select2').select2();
tooltips();
$('.inp-tbl-edit-calculate-price').on("input", $('.inp-tbl-edit-calculate-price').on("input",
function() { function() {
@@ -849,6 +865,14 @@
refreshPrices(); refreshPrices();
}); });
function searchPartItems(input, idProjectPart) {
let filter = $(input).val().toLowerCase();
$('#accordion-' + idProjectPart + ' tbody tr').each(function() {
let text = $(this).text().toLowerCase();
$(this).toggle(text.indexOf(filter) > -1);
});
}
function showAllInvoices() { function showAllInvoices() {
$(".invoice-row").each(function() { $(".invoice-row").each(function() {
$(this).show(); $(this).show();
@@ -858,7 +882,17 @@
function tooltips() { function tooltips() {
$('[data-toggle="tooltip"]').tooltip(); $('[data-toggle="tooltip"]').tooltip();
} }
function createOrderSelectPartner(inquiry) {
function bulkPrintPartItems() {
let ids = getSelectedPartItems();
if (ids.length <= 0) {
alert("Izberi pozicije!");
return;
}
window.open('/Projects/PrintPartItem?ids=' + ids.join(','), '_blank');
}
function createOrderSelectPartner(inquiry, positionsType) {
$.blockUI(); $.blockUI();
$.ajax({ $.ajax({
type: "GET", type: "GET",
@@ -886,7 +920,7 @@
} }
}).then((result) => { }).then((result) => {
if (result.isConfirmed) { if (result.isConfirmed) {
createOrder(inquiry, result.value); createOrder(inquiry, result.value, positionsType);
} }
}); });
} else { } else {
@@ -905,10 +939,14 @@
}); });
} }
function createOrder(inquiry, idPartner) { function createOrder(inquiry, idPartner, positionsType) {
if (idPartner == null || idPartner == undefined || isNaN(idPartner)) if (idPartner == null || idPartner == undefined || isNaN(idPartner))
idPartner = 0; idPartner = 0;
if (isNaN(positionsType) || positionsType == null || positionsType == undefined){
positionsType = 1;
}
let object = getSelectedPartItems(); let object = getSelectedPartItems();
if (object.length <= 0) { if (object.length <= 0) {
@@ -923,7 +961,7 @@
$('input:hidden[name="__RequestVerificationToken"]').val()); $('input:hidden[name="__RequestVerificationToken"]').val());
}, },
url: "Edit/?handler=CreateOrder", url: "Edit/?handler=CreateOrder",
data: { itemsJson: JSON.stringify(object), inquiry: inquiry, idPartner: idPartner }, data: { itemsJson: JSON.stringify(object), inquiry: inquiry, idPartner: idPartner, positionsType: positionsType },
success: function(data) { success: function(data) {
if (data.successful) { if (data.successful) {
if (inquiry) { if (inquiry) {

View File

@@ -91,6 +91,9 @@ namespace EveryThing.Pages.Projects
.ThenInclude(x => x.Material) .ThenInclude(x => x.Material)
.Include(c => c.ProjectPartProjectPartItem) .Include(c => c.ProjectPartProjectPartItem)
.ThenInclude(x => x.Item) .ThenInclude(x => x.Item)
.Include(c => c.ProjectPartProjectPartItem)
.ThenInclude(x => x.ProjectPartItemOperation)
.ThenInclude(x => x.Operation)
.Where(x => x.IdProjectFk == id) .Where(x => x.IdProjectFk == id)
.OrderBy(x => x.ProjectPartNumber).ThenBy(x => x.IdProjectPart) .OrderBy(x => x.ProjectPartNumber).ThenBy(x => x.IdProjectPart)
.ToListAsync(); .ToListAsync();
@@ -192,6 +195,8 @@ namespace EveryThing.Pages.Projects
.Include(x => x.Material) .Include(x => x.Material)
.Include(x => x.ProjectPart) .Include(x => x.ProjectPart)
.ThenInclude(x => x.Project) .ThenInclude(x => x.Project)
.Include(x => x.ProjectPartItemOperation)
.ThenInclude(x => x.Operation)
.First(x => x.IdProjectPartItem == id); .First(x => x.IdProjectPartItem == id);
return Partial("DetailsPartItem", item); return Partial("DetailsPartItem", item);
@@ -272,7 +277,7 @@ namespace EveryThing.Pages.Projects
return new JsonResult(new { error = "", successful = true, idInvoice }); return new JsonResult(new { error = "", successful = true, idInvoice });
} }
public IActionResult OnPostCreateOrder(string itemsJson, bool inquiry, int idPartner) public IActionResult OnPostCreateOrder(string itemsJson, bool inquiry, int idPartner, int positionsType)
{ {
var user = _userManager.GetUserAsync(User).Result; var user = _userManager.GetUserAsync(User).Result;
@@ -330,16 +335,24 @@ namespace EveryThing.Pages.Projects
{ {
var newInvoiceItem = new Models.Invoice.InvoiceItem var newInvoiceItem = new Models.Invoice.InvoiceItem
{ {
Discount = 0, Discount = 0,
IdInvoiceFk = idInvoice, IdInvoiceFk = idInvoice,
IdProjectPartItem = projectPartItem.IdProjectPartItem, IdProjectPartItem = projectPartItem.IdProjectPartItem,
IdItemFk = projectPartItem.IdMaterialFk, Note = "",
ItemDescription = projectPartItem.MaterialDimensions, Price = projectPartItem.MaterialPrice,
Note = "", Quantity = projectPartItem.NumberOfItems
Price = projectPartItem.MaterialPrice,
//Quantity = projectPartItem.NumberOfItems * projectPartItem.NumberOfSets
Quantity = projectPartItem.NumberOfItems
}; };
if (positionsType == 2)
{
newInvoiceItem.IdItemFk = projectPartItem.IdItemFk;
}
else
{
newInvoiceItem.IdItemFk = projectPartItem.IdMaterialFk;
newInvoiceItem.ItemDescription = projectPartItem.MaterialDimensions;
}
_context.InvoiceItems.Add(newInvoiceItem); _context.InvoiceItems.Add(newInvoiceItem);
} }
_context.SaveChanges(); _context.SaveChanges();
@@ -631,14 +644,19 @@ namespace EveryThing.Pages.Projects
if (projectPart != null) if (projectPart != null)
{ {
foreach (var projectPartItem in _context.ProjectPartItems.Where(x => x.IdProjectPartFk == projectPart.IdProjectPart).ToList()) foreach (var projectPartItem in _context.ProjectPartItems.Where(x => x.IdProjectPartFk == projectPart.IdProjectPart).ToList())
{ {
_context.ProjectPartItems.Remove(projectPartItem); var operations = _context.ProjectPartItemOperations
} .Where(x => x.IdProjectPartItemFk == projectPartItem.IdProjectPartItem)
_context.ProjectParts.Remove(projectPart); .ToList();
_context.ProjectPartItemOperations.RemoveRange(operations);
_context.ProjectPartItems.Remove(projectPartItem);
}
_context.ProjectParts.Remove(projectPart);
_context.SaveChanges(); _context.SaveChanges();
projectPart.Project = null; projectPart.Project = null;
projectPart.ProjectPartProjectPartItem = null;
} }
else else
{ {

View File

@@ -21,6 +21,7 @@
</div> </div>
<input id="inpTblMaterialDimensions_@(Model.Item.IdProjectPartItem.ToString())" asp-for="Item.MaterialDimensions" class="form-control" style="width: 100%"/> <input id="inpTblMaterialDimensions_@(Model.Item.IdProjectPartItem.ToString())" asp-for="Item.MaterialDimensions" class="form-control" style="width: 100%"/>
</td> </td>
<td class="table-eddit"></td>
<td class="table-eddit table-number-edit"> <td class="table-eddit table-number-edit">
<input id="inpTblNumberOfItems_@(Model.Item.IdProjectPartItem.ToString())" asp-for="Item.NumberOfItems" class="form-control" style="width: 100%" /> <input id="inpTblNumberOfItems_@(Model.Item.IdProjectPartItem.ToString())" asp-for="Item.NumberOfItems" class="form-control" style="width: 100%" />
<input id="inpTblNumberOfSets_@(Model.Item.IdProjectPartItem.ToString())" asp-for="Item.NumberOfSets" class="form-control" style="width: 100%" /> <input id="inpTblNumberOfSets_@(Model.Item.IdProjectPartItem.ToString())" asp-for="Item.NumberOfSets" class="form-control" style="width: 100%" />
@@ -46,8 +47,8 @@
@Html.TextBoxFor(m => m.Item.DeliveryDate, "{0:yyyy-MM-dd}", new { @class = "form-control", type = "date", id = "inpTblDeliveryDate_" + Model.Item.IdProjectPartItem.ToString() }) @Html.TextBoxFor(m => m.Item.DeliveryDate, "{0:yyyy-MM-dd}", new { @class = "form-control", type = "date", id = "inpTblDeliveryDate_" + Model.Item.IdProjectPartItem.ToString() })
</td> </td>
<td class="text-right table-eddit" style="width: 70px;"> <td class="text-right table-eddit" style="width: 70px;">
<a class="btn btn-xs icon-btn btn-outline-success borderless" href='javascript:;' data-state="success" data-iditem="@(Model.Item.IdProjectPartItem)" onclick="updatePartItem(this)"><i class="fas fa-check"></i></a> <a class="btn btn-xs icon-btn btn-outline-success borderless" href='javascript:;' data-state="success" data-iditem="@(Model.Item.IdProjectPartItem)" onclick="updatePartItem(this)" data-toggle="tooltip" data-placement="top" title="Shrani"><i class="fas fa-check"></i></a>
<a id="btnTblCancel_@(Model.Item.IdProjectPartItem.ToString())" href='javascript:;' class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" hx-get="@Url.Page("Edit", "DetailPartItem", new { id = Model.Item.IdProjectPartItem })" hx-swap="outerHTML" hx-target="closest tr"><i class="fas fa-ban"></i></a> <a id="btnTblCancel_@(Model.Item.IdProjectPartItem.ToString())" href='javascript:;' class="btn btn-xs icon-btn btn-outline-danger borderless" data-state="danger" data-toggle="tooltip" data-placement="top" title="Prekliči" hx-get="@Url.Page("Edit", "DetailPartItem", new { id = Model.Item.IdProjectPartItem })" hx-swap="outerHTML" hx-target="closest tr"><i class="fas fa-ban"></i></a>
</td> </td>
} }
</tr> </tr>

View File

@@ -80,7 +80,7 @@
<tbody> <tbody>
@foreach (var item in Model.Project) @foreach (var item in Model.Project)
{ {
<tr data-idproject="@item.IdProject" data-title="@item.Title"> <tr data-idproject="@item.IdProject" data-title="@item.Title" data-href="@Url.Page("Edit", new { id = item.IdProject })" style="cursor:pointer;">
<td> <td>
@Html.DisplayFor(modelItem => item.ProjectNumberFormatted) @Html.DisplayFor(modelItem => item.ProjectNumberFormatted)
</td> </td>
@@ -133,6 +133,10 @@
<script> <script>
$('[data-toggle="tooltip"]').tooltip({container: 'table'}); $('[data-toggle="tooltip"]').tooltip({container: 'table'});
$('table tbody tr').on('dblclick', function () {
window.location.href = $(this).data('href');
});
function deleteProject(element) { function deleteProject(element) {
let row = $(element).parent().parent(); let row = $(element).parent().parent();
let idProject = $(row).attr('data-idproject'); let idProject = $(row).attr('data-idproject');

View File

@@ -0,0 +1,240 @@
@page
@using System.Web
@using EveryThing.Models.Invoice
@using Org.BouncyCastle.Asn1
@model EveryThing.Pages.Projects.PrintPartItem
@{
ViewData["Title"] = "Izpis";
Layout = "~/Pages/Layouts/_Layout.cshtml";
}
<style type="text/css">
table {
page-break-inside: auto;
color: black !important;
}
tr {
page-break-inside: avoid;
page-break-after: auto
}
thead {
display: table-header-group
}
tfoot {
display: table-footer-group
}
body {
color: black !important;
}
</style>
<h4 class="d-flex justify-content-between align-items-center w-100 font-weight-bold py-1 mb-4">
<span>
<span class="text-muted font-weight-light">Projekti / </span> Izpis
</span>
</h4>
<div class="card pt-2" style="width: 595pt; margin-bottom:10px;">
<div class="card-body">
<div class="row">
<div class="col-12 text-right">
<button id="btnPrint" type="button" class="btn btn-sm btn-primary btn-print ladda-button pull-right" data-style="zoom-out"><i class="ion ion-md-print"></i>&nbsp; Natisni</button>
</div>
</div>
</div>
</div>
<div class="card pt-2" style="width: 595pt">
<div id="print-content" class="card-body pb-4 pl-4 pt-0" style="padding-right: 2rem !important">
@for (int i = 0; i < Model.Items.Count; i++)
{
var item = Model.Items[i];
<div style="@(i > 0 ? "page-break-before: always;" : "")">
<div class="row">
<div class="col-12">
<address class="mb-0">
<strong>@Html.DisplayFor(modelItem => item.PartItem.ProjectPart.Project.Company.Title)</strong> <br/>
</address>
</div>
</div>
<hr/>
<h4 class="font-weight-bold mb-3">
Projekt št.: @Html.DisplayFor(modelItem => item.PartItem.ProjectPart.Project.ProjectNumberFormatted)
</h4>
<div class="text-big mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
@Html.DisplayFor(modelItem => item.PartItem.ProjectPart.Project.Title)
</div>
<div class="mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
<label style="margin-top: 0 !important; margin-bottom: 0 !important;">Del projekta</label>:&nbsp;
<strong class="font-weight-semibold">@Html.DisplayFor(modelItem => item.PartItem.ProjectPartNumberFormatted)</strong>
</div>
<div class="mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
<label style="margin-top: 0 !important; margin-bottom: 0 !important;">Artikel</label>:&nbsp;
<strong class="font-weight-semibold">@Html.DisplayFor(modelItem => item.PartItem.Item.Title)</strong>
</div>
<div class="mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
<label style="margin-top: 0 !important; margin-bottom: 0 !important;">Material</label>:&nbsp;
<strong class="font-weight-semibold">@Html.DisplayFor(modelItem => item.PartItem.Material.Title)</strong>
</div>
<div class="mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
<label style="margin-top: 0 !important; margin-bottom: 0 !important;">Dimenzije surovca</label>:&nbsp;
<strong class="font-weight-semibold">@Html.DisplayFor(modelItem => item.PartItem.MaterialDimensions)</strong>
</div>
<div class="mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
<label style="margin-top: 0 !important; margin-bottom: 0 !important;">Število kosov</label>:&nbsp;
<strong class="font-weight-semibold">@Html.DisplayFor(modelItem => item.PartItem.NumberOfItems)</strong>
</div>
@if (!string.IsNullOrEmpty(item.PartItem.ProjectPart.PathOfPlans))
{
<div class="mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
<label style="margin-top: 0 !important; margin-bottom: 0 !important;">Pot načrtov</label>:&nbsp;
<strong class="font-weight-semibold">@Html.DisplayFor(modelItem => item.PartItem.ProjectPart.PathOfPlans)</strong>
</div>
}
@if (!string.IsNullOrEmpty(item.PartItem.Note))
{
<div class="mb-3" style="margin-top: 0 !important; margin-bottom: 0 !important;">
<br />
<i class="">@Html.DisplayFor(modelItem => item.PartItem.Note)</i>
</div>
}
<br/>
<h6>Operacije</h6>
<div class="table-responsive mb-4">
<table class="table m-0 table-bordered">
<thead style="font-size: 0.75rem">
<tr>
<th style="width: 30px">#</th>
<th class="py-1">
Operacija
</th>
<th class="py-1" style="width: 150px">
Čas
</th>
</tr>
</thead>
<tbody style="font-size: 0.75rem">
@{ var opIndex = 0; }
@foreach (var op in item.Operations)
{
opIndex++;
<tr>
<td>@opIndex</td>
<td>@Html.DisplayFor(x => op.Operation.Title)</td>
<td></td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
</div>
</div>
@Html.AntiForgeryToken()
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<!-- PDF -->
<script src="~/vendor/libs/html2pdf.js/dist/html2pdf.bundle.min.js" asp-append-version="true"></script>
<script>
var laddaPrint = Ladda.create(document.querySelector('#btnPrint'));
var laddaPrintAndConfirm = document.querySelector('#btnPrintAndConfirm') == null ? null : Ladda.create(document.querySelector('#btnPrintAndConfirm'));
var element = document.getElementById('print-content');
var opt = {
//pagebreak: { mode: 'avoid-all' },
filename: 'nalog.pdf',
image: { type: 'png' },
enableLinks: false,
margin: [5, 0, 13, 0],
html2canvas: {
scale: 1.2,
scrollX: 0,
scrollY: 0,
dpi: 300,
letterRendering: true
},
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
function print(confirm) {
laddaPrint.start();
if (laddaPrintAndConfirm != null) {
laddaPrintAndConfirm.start();
}
html2pdf().set(opt).from(element).toPdf().get('pdf').then(function (pdf) {
var totalPages = pdf.internal.getNumberOfPages();
for (i = 1; i <= totalPages; i++) {
pdf.setPage(i);
pdf.setFontSize(8);
pdf.setTextColor(0);
var fontSize = pdf.internal.getFontSize();
var pageWidth = pdf.internal.pageSize.width;
var txt = $('#footer1').text();
var txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
var x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 8, txt);
txt = $('#footer2').text();
txtWidth = pdf.getStringUnitWidth(txt) * fontSize / pdf.internal.scaleFactor;
x = (pageWidth - txtWidth) / 2;
pdf.text(x, pdf.internal.pageSize.getHeight() - 5, txt);
//pdf.addImage("YOUR_IMAGE", 'JPEG', pdf.internal.pageSize.getWidth() - 1.1, pdf.internal.pageSize.getHeight() - 0.25, 1, 0.2);
}
laddaPrint.stop();
if (laddaPrintAndConfirm != null) {
laddaPrintAndConfirm.stop();
}
//window.open(pdf.output('bloburl'), '_blank');
let link = document.createElement('a');
link.target = '_blank';
link.href = pdf.output('bloburl');
link.download = '@Model.PartItem.ProjectPartNumberFormatted.Replace("-", "_")';
link.click();
link.remove();
if (confirm) {
confirmInvoice();
}
});
}
$(document).ready(function () {
//print();
});
$(".btn-print").click(function () {
print($(this).attr("data-confirm") === 'true');
});
</script>
}

View File

@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using EveryThing.Data;
using EveryThing.Models;
using EveryThing.Models.Project;
using EveryThing.Models.Transport;
using DocumentFormat.OpenXml.Wordprocessing;
using System.ComponentModel.DataAnnotations;
namespace EveryThing.Pages.Projects
{
[Authorize(Roles = "Administrator,InvoicingUser,ProjecThingUser")]
public class PrintPartItem : PageModel
{
public class PrintPartItemData
{
public ProjectPartItem PartItem { get; set; }
public IList<ProjectPartItemOperation> Operations { get; set; }
}
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityApplicationUser> _userManager;
public ProjectPartItem PartItem { get; set; }
public IList<ProjectPartItemOperation> Operations { get; set; }
public IList<PrintPartItemData> Items { get; set; } = new List<PrintPartItemData>();
public PrintPartItem(ApplicationDbContext context, UserManager<IdentityApplicationUser> userManager)
{
_context = context;
_userManager = userManager;
}
public async Task<IActionResult> OnGetAsync(int? id, string ids)
{
var user = _userManager.GetUserAsync(User).Result;
var itemIds = new List<int>();
if (!string.IsNullOrEmpty(ids))
{
itemIds = ids.Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(x => int.TryParse(x.Trim(), out var v) ? v : 0)
.Where(x => x > 0)
.ToList();
}
else if (id.HasValue)
{
itemIds.Add(id.Value);
}
if (!itemIds.Any())
return NotFound();
var partItems = await _context.ProjectPartItems
.Include(x => x.ProjectPart)
.ThenInclude(x => x.Project)
.ThenInclude(x => x.Company)
.Include(x => x.Material)
.Include(x => x.Item)
.Where(x => itemIds.Contains(x.IdProjectPartItem) && x.ProjectPart.Project.Company.IdCompany == user.IdCompanyFk)
.ToListAsync();
if (!partItems.Any())
return NotFound();
var allOperations = await _context.ProjectPartItemOperations
.Include(x => x.Operation)
.Where(x => itemIds.Contains(x.IdProjectPartItemFk))
.OrderBy(x => x.Order)
.ToListAsync();
foreach (var partItem in partItems.OrderBy(x => itemIds.IndexOf(x.IdProjectPartItem)))
{
Items.Add(new PrintPartItemData
{
PartItem = partItem,
Operations = allOperations.Where(x => x.IdProjectPartItemFk == partItem.IdProjectPartItem).ToList()
});
}
// Keep backward compatibility for single-item references
PartItem = Items.First().PartItem;
Operations = Items.First().Operations;
return Page();
}
}
}

View File

@@ -2,6 +2,16 @@
"ConnectionStrings": { "ConnectionStrings": {
"DataConnection": "server=192.168.1.12;user=everything;password=EveryThing2022!;database=EveryThingDev" "DataConnection": "server=192.168.1.12;user=everything;password=EveryThing2022!;database=EveryThingDev"
}, },
"EmailSettings": {
"Host": "mail.no-reply.si",
"Port": 465,
"SecureSocketOptions": "SslOnConnect",
"Username": "cnc-paradiz@no-reply.si",
"Password": "52svchwokzce#ss",
"FromEmail": "cnc-paradiz@no-reply.si",
"FromName": "CNC - Paradiž",
"Bcc": "david.staleker@gmail.com"
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",

View File

@@ -13,8 +13,8 @@
</targets> </targets>
<rules> <rules>
<logger name="*" minlevel="Trace" writeTo="logFile" /> <logger name="*" minlevel="Warn" writeTo="logFile" />
<logger name="*" minlevel="Trace" writeTo="console" /> <logger name="*" minlevel="Warn" writeTo="console" />
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <logger name="Microsoft.*" maxlevel="Info" final="true" />
<logger name="System.Net.Http.*" maxlevel="Info" final="true" /> <logger name="System.Net.Http.*" maxlevel="Info" final="true" />

View File

@@ -0,0 +1,162 @@
//ce jamra da ne najde post je treba dati @Html.AntiForgeryToken() v page
function codeTableOperationAddEdit(placeholderSelector, edit, idCodeTableOperation, onAddEdit, onCancel){
$.blockUI();
$.ajax({
type: "GET",
url: "/CodeTableOperations/Index/?handler=CodeTableOperationModal",
data: { edit: edit, idCodeTableOperation: edit ? idCodeTableOperation : -1 },
success: function(data) {
$.unblockUI();
$(placeholderSelector).html(data);
if (edit){
$('#modalAddEditCodeTableOperationTitle').html(`Urejanje operacije: ${$('#inpModalAddEditCodeTableOperationTitle').val()}`);
$('#btnModalAddEditCodeTableOperationConfirm').html('Shrani');
} else {
$('#modalAddEditCodeTableOperationTitle').html('Dodajanje nove operacije');
$('#btnModalAddEditCodeTableOperationConfirm').html('Dodaj');
}
$('#btnModalAddEditCodeTableOperationConfirm').off();
$('#btnModalAddEditCodeTableOperationCancel').off();
//Save to db
$('#btnModalAddEditCodeTableOperationConfirm').on('click', () =>{
let title = $('#inpModalAddEditCodeTableOperationTitle').val();
let defaultValue = $('#inpModalAddEditCodeTableOperationDefault').is(':checked');
let edit = $('#inpModalAddEditCodeTableOperationEdit').val() === 'true';
let idCodeTableOperation = parseInt($('#inpModalAddEditCodeTableOperationIdCodeTableOperation').val());
if (title === '' || title === null){
Swal.fire('Zahtevano polje naziv!');
return;
}
$.blockUI();
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/CodeTableOperations/Index/?handler=CodeTableOperation",
data: {
title,
defaultValue,
edit,
idCodeTableOperation
},
success: function(data) {
$.unblockUI();
if (data.successful){
$("#divModalAddEditCodeTableOperation").modal('hide');
if (onAddEdit != null){
onAddEdit(data.idCodeTableOperation);
}
} else {
Swal.fire('Napaka pri dodajanju/posodabljanju',
data.error,
'error');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
$.unblockUI();
}
});
});
//Cancel
$('#btnModalAddEditCodeTableOperationCancel').on('click', () =>{
$("#divModalAddEditCodeTableOperation").modal('hide');
if (onCancel != null){
onCancel();
}
});
$("#divModalAddEditCodeTableOperation").modal('show');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
$.unblockUI();
}
});
}
function codeTableOperationDelete(idCodeTableOperation, onDelete, onCancel){
$.blockUI();
$.ajax({
type: "GET",
url: "/CodeTableOperations/Index/?handler=CodeTableOperation",
data: {
idCodeTableOperation
},
success: function(data) {
$.unblockUI();
if (data.successful){
if (data.inUse){
Swal.fire('Operacija je v uporabi!',
'Brisanje ni možno!',
'warning');
return;
}
Swal.fire({
title: `Izbrišem operacijo ${data.operation.title}?`,
text: "Tega dejanja ni možno razveljaviti!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Da, izbriši!',
cancelButtonText: 'Prekliči!'
}).then((result) => {
if (result.isConfirmed) {
$.blockUI();
$.ajax({
type: "DELETE",
beforeSend: function(xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
url: "/CodeTableOperations/Index/?handler=CodeTableOperation",
data: {
idCodeTableOperation
},
success: function(data) {
$.unblockUI();
if (data.successful){
if (onDelete != null){
onDelete(data.idCodeTableOperation);
}
} else {
Swal.fire('Napaka pri brisanju operacije',
data.error,
'error');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
$.unblockUI();
}
});
} else{
if (onCancel != null){
onCancel();
}
}
});
} else {
Swal.fire('Napaka pri branju operacije',
data.error,
'error');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
alert(xhr.responseText);
$.unblockUI();
}
});
}