Compare commits

..
10 Commits
Author SHA1 Message Date
poprhythm e472004211 Uncommitted Updates 2024-02-22 08:24:33 -05:00
poprhythm 3caf0bd766 Add administrator editing 2016-09-27 11:56:10 -04:00
poprhythm 75b7c02979 User profile editing and password 2016-09-26 11:13:59 -04:00
poprhythm 6789c1b3b5 Update automapper 2016-09-24 00:06:34 -04:00
poprhythm f473c64540 Configure tolken provider 2016-09-23 21:23:33 -04:00
poprhythm 0b5dde065a Add user management 2016-09-23 15:12:46 -04:00
poprhythm 9f50a4635c Inventory and Type reports 2016-09-22 14:14:12 -04:00
poprhythm 02555eba7e Export Distribution report 2016-09-22 08:49:24 -04:00
poprhythm 206a3f2def Export Monthly Inventory 2016-09-21 11:55:06 -04:00
poprhythm 4f561dac11 Rename Monthly Inventory to Movement 2016-09-20 09:31:56 -04:00
121 changed files with 3847 additions and 1100 deletions
+1
View File
@@ -30,3 +30,4 @@ _ReSharper*/
packages/**/
**/App_Data/*
*/Logs/*
logs/*
File diff suppressed because it is too large Load Diff
Binary file not shown.
@@ -1,19 +0,0 @@
using Heroic.AutoMapper;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(InventoryTraker.Web.Tests.AutoMapperConfig), "Configure")]
namespace InventoryTraker.Web.Tests
{
public static class AutoMapperConfig
{
public static void Configure()
{
//NOTE: By default, the current project and all referenced projects will be scanned.
// You can customize this by passing in a lambda to filter the assemblies by name,
// like so:
//HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies(x => x.Name.StartsWith("YourPrefix"));
HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies();
//If you run into issues with the maps not being located at runtime, try using this method instead:
//HeroicAutoMapperConfigurator.LoadMapsFromAssemblyContainingTypeAndReferencedAssemblies<SomeControllerOrTypeInYourWebProject>();
}
}
}
@@ -0,0 +1,14 @@
using NUnit.Framework;
namespace InventoryTraker.Web.Tests
{
[SetUpFixture]
public class Setup
{
[OneTimeSetUp]
public void S()
{
AutoMapperConfig.Configure();
}
}
}
@@ -30,20 +30,16 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="AutoMapper, Version=4.2.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005, processorArchitecture=MSIL">
<HintPath>..\packages\AutoMapper.4.2.0\lib\net45\AutoMapper.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Heroic.AutoMapper, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Heroic.AutoMapper.2.0.0\lib\net45\Heroic.AutoMapper.dll</HintPath>
<Reference Include="AutoMapper, Version=5.1.1.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005, processorArchitecture=MSIL">
<HintPath>..\packages\AutoMapper.5.1.1\lib\net45\AutoMapper.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nunit.framework, Version=3.4.1.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.4.1\lib\net45\nunit.framework.dll</HintPath>
<Reference Include="nunit.framework, Version=3.4.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.4.0\lib\net45\nunit.framework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
@@ -60,9 +56,12 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\AutoMapperConfig.cs" />
<Compile Include="Models\InventoryAddForm.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="App_Start\Setup.cs" />
<Compile Include="Utilities\InventoryReportWriterTests.cs" />
<Compile Include="Utilities\DistributionReportWriterTests.cs" />
<Compile Include="Utilities\MovementReportWriterTests.cs" />
<Compile Include="Utilities\InventoryTypeParserTests.cs" />
</ItemGroup>
<ItemGroup>
@@ -1,6 +1,5 @@
using System;
using AutoMapper;
using Heroic.AutoMapper;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Models;
using NUnit.Framework;
@@ -10,10 +9,12 @@ namespace InventoryTraker.Web.Tests.Models
[TestFixture]
public class InventoryAddFormTests
{
private IMapper _mapper;
[OneTimeSetUp]
public void StartUp()
{
HeroicAutoMapperConfigurator.LoadMapsFromAssemblyContainingTypeAndReferencedAssemblies<Inventory>();
_mapper = AutoMapperConfig.Config.CreateMapper();
}
[Test]
@@ -28,7 +29,7 @@ namespace InventoryTraker.Web.Tests.Models
Quantity = 32
};
var inventory = Mapper.Map<Inventory>(form);
var inventory = _mapper.Map<Inventory>(form);
Assert.That(inventory.AddedDate, Is.EqualTo(form.AddedDate));
Assert.That(inventory.ExpirationDate, Is.EqualTo(form.ExpirationDate));
@@ -0,0 +1,69 @@
using System;
using System.IO;
using AutoMapper;
using InventoryTraker.Web.Models;
using InventoryTraker.Web.Utilities;
using NUnit.Framework;
namespace InventoryTraker.Web.Tests.Utilities
{
[TestFixture]
public class DistributionReportWriterTests
{
private IMapper _mapper;
[OneTimeSetUp]
public void StartUp()
{
_mapper = AutoMapperConfig.Config.CreateMapper();
}
private readonly DistributionReport[] _distributionReports =
{
new DistributionReport
{
Destination = "First City",
Date = new DateTime(2016, 1, 1),
Transactions = new[]
{
new TransactionViewModel
{
Name = "Beans",
ContainerType = "#300 cans",
UnitsPerCase = 24,
Destination = "First City",
RemovedQuantity = 3
}
}
},
new DistributionReport
{
Destination = "Second City",
Date = new DateTime(2016, 2, 1),
Transactions = new[]
{
new TransactionViewModel
{
Name = "Peanut Butter",
ContainerType = "Jars",
UnitsPerCase = 24,
Destination = "Second City",
RemovedQuantity = 4
}
}
}
};
[Test, Explicit]
public void Write()
{
using
(var outputFile
= new StreamWriter(Path.Combine(@"c:\temp", "DistributionReport.xlsx")))
{
var writer = new DistributionReportWriter(_mapper);
writer.WriteStream(_distributionReports, outputFile.BaseStream);
}
}
}
}
@@ -0,0 +1,41 @@
using System;
using System.IO;
using InventoryTraker.Web.Models;
using InventoryTraker.Web.Utilities;
using NUnit.Framework;
namespace InventoryTraker.Web.Tests.Utilities
{
[TestFixture]
public class InventoryReportWriterTests
{
private readonly InventoryViewModel[] _inventory =
{
new InventoryViewModel
{
Name = "Beans",
ContainerType = "#300 cans",
UnitsPerCase = 24,
AddedDate = new DateTime(2015,3,1),
ExpirationDate = new DateTime(2017,4,1),
Quantity = 20,
Memo = "my memo",
PricePerCase = 12.12M,
WeightPerCase = 20.1,
}
};
[Test, Explicit]
public void Write()
{
using
(var outputFile
= new StreamWriter(Path.Combine(@"c:\temp", "InventoryReport.xlsx")))
{
var writer = new InventoryReportWriter();
writer.WriteStream(_inventory, outputFile.BaseStream);
}
}
}
}
@@ -0,0 +1,76 @@
using System;
using System.IO;
using AutoMapper;
using InventoryTraker.Web.Models;
using InventoryTraker.Web.Utilities;
using NUnit.Framework;
namespace InventoryTraker.Web.Tests.Utilities
{
[TestFixture]
public class MovementReportWriterTests
{
private IMapper _mapper;
[OneTimeSetUp]
public void StartUp()
{
_mapper = AutoMapperConfig.Config.CreateMapper();
}
private readonly MovementReport _movementReport
= new MovementReport
{
Month = new DateTime(2016, 04, 1),
Items = new[]
{
new MovementReportItem
{
InventoryType = new InventoryTypeViewModel
{
Name = "Beans",
ContainerType = "#300 cans",
Id = 1,
Identifier = "10001",
UnitsPerCase = 24
},
BeginningQuantity = 7,
AddedQuantity = 5,
TotalAvailableQuantity = 12,
AdjustmentQuantity = 3,
DistributedQuantity = 1,
EndingQuantity = 8
},
new MovementReportItem
{
InventoryType = new InventoryTypeViewModel
{
Name = "Peanut Butter",
ContainerType = "16oz jars",
Id = 2,
Identifier = "20001",
UnitsPerCase = 12
},
BeginningQuantity = 5,
AddedQuantity = 11,
TotalAvailableQuantity = 16,
AdjustmentQuantity = 0,
DistributedQuantity = 2,
EndingQuantity = 14
}
}
};
[Test, Explicit]
public void Write()
{
using
(var outputFile
= new StreamWriter(Path.Combine(@"c:\temp", "MovementReport.xlsx")))
{
var writer = new MovementReportWriter(_mapper);
writer.WriteStream(_movementReport, outputFile.BaseStream);
}
}
}
}
+4
View File
@@ -38,6 +38,10 @@
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="AutoMapper" publicKeyToken="be96cd2c38ef1005" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.1.1.0" newVersion="5.1.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
+2 -3
View File
@@ -1,8 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AutoMapper" version="4.2.0" targetFramework="net452" />
<package id="Heroic.AutoMapper" version="2.0.0" targetFramework="net452" />
<package id="AutoMapper" version="5.1.1" targetFramework="net452" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net452" />
<package id="NUnit" version="3.4.1" targetFramework="net452" />
<package id="NUnit" version="3.4.0" targetFramework="net452" />
<package id="WebActivatorEx" version="2.1.0" targetFramework="net452" />
</packages>
@@ -9,7 +9,7 @@ namespace InventoryTraker.Web.ActionResults
{
public class BetterJsonResult : JsonResult
{
public IList<string> ErrorMessages { get; private set; }
public IList<string> ErrorMessages { get; }
public BetterJsonResult()
{
@@ -1,21 +1,18 @@
using Heroic.AutoMapper;
using AutoMapper;
using InventoryTraker.Web;
using InventoryTraker.Web.Controllers;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(AutoMapperConfig), "Configure")]
namespace InventoryTraker.Web
{
public static class AutoMapperConfig
{
public static MapperConfiguration Config { get; private set; }
public static void Configure()
{
//NOTE: By default, the current project and all referenced projects will be scanned.
// You can customize this by passing in a lambda to filter the assemblies by name,
// like so:
//HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies(x => x.Name.StartsWith("YourPrefix"));
//HeroicAutoMapperConfigurator.LoadMapsFromCallerAndReferencedAssemblies();
//If you run into issues with the maps not being located at runtime, try using this method instead:
HeroicAutoMapperConfigurator.LoadMapsFromAssemblyContainingTypeAndReferencedAssemblies<ControllerBase>();
Config = new MapperConfiguration(cfg =>
cfg.AddProfiles(typeof(Controllers.UserController))
);
}
}
}
@@ -23,6 +23,7 @@ namespace InventoryTraker.Web
.Include("~/Scripts/angular-strap.js")
.Include("~/Scripts/angular-strap.tpl.js")
.Include("~/Scripts/ui-grid.js")
.Include("~/Scripts/FileSaver.js")
.Include("~/js/app.js")
.IncludeDirectory("~/js/", "*.js", true)
);
+5 -1
View File
@@ -1,6 +1,8 @@
using Microsoft.AspNet.Identity;
using Heroic.Web.IoC;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.DataProtection;
using Owin;
namespace InventoryTraker.Web
@@ -9,6 +11,8 @@ namespace InventoryTraker.Web
{
public void Configuration(IAppBuilder app)
{
IoC.Container.Inject(app.GetDataProtectionProvider());
var authenticationOptions = new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
@@ -3,12 +3,12 @@ using System.Web;
using Heroic.Web.IoC;
using System.Web.Http;
using System.Web.Mvc;
using AutoMapper;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Data;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using StructureMap.Graph;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(InventoryTraker.Web.StructureMapConfig), "Configure")]
namespace InventoryTraker.Web
@@ -42,6 +42,8 @@ namespace InventoryTraker.Web
cfg.For<IAuthenticationManager>().Use(ctx => ctx.GetInstance<HttpRequestBase>().GetOwinContext().Authentication);
//TODO: Add other registries and configure your container (if needed)
var mapper = AutoMapperConfig.Config.CreateMapper();
cfg.For<IMapper>().Use(x => mapper);
});
var resolver = new StructureMapDependencyResolver();
@@ -1,6 +1,8 @@
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using InventoryTraker.Web.ActionResults;
using InventoryTraker.Web.Data;
using InventoryTraker.Web.Utilities;
using NLog;
@@ -8,16 +8,19 @@ using InventoryTraker.Web.Attributes;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Data;
using InventoryTraker.Web.Models;
using InventoryTraker.Web.Utilities;
namespace InventoryTraker.Web.Controllers
{
public class InventoryController : ControllerBase
{
private readonly AppDbContext _context;
private readonly IMapper _mapper;
public InventoryController(AppDbContext context)
public InventoryController(AppDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public ActionResult Index()
@@ -28,8 +31,8 @@ namespace InventoryTraker.Web.Controllers
public JsonResult All()
{
var viewModels =
AllInventory()
.ProjectTo<InventoryViewModel>()
CurrentInventory()
.ProjectTo<InventoryViewModel>(_mapper.ConfigurationProvider)
.ToArray();
return BetterJson(viewModels);
@@ -38,11 +41,11 @@ namespace InventoryTraker.Web.Controllers
public JsonResult Find(int id)
{
var inventory = _context.Inventories.Find(id);
var viewModel = Mapper.Map<InventoryViewModel>(inventory);
var viewModel = _mapper.Map<InventoryViewModel>(inventory);
return BetterJson(viewModel);
}
private IQueryable<Inventory> AllInventory()
private IQueryable<Inventory> CurrentInventory()
{
return _context
.Inventories
@@ -50,13 +53,33 @@ namespace InventoryTraker.Web.Controllers
.OrderBy(x => x.InventoryType.Name);
}
public ActionResult Export()
{
var writer = new InventoryReportWriter();
var viewModels =
CurrentInventory()
.ProjectTo<InventoryViewModel>(_mapper.ConfigurationProvider)
.ToArray();
var excel = writer.Write(viewModels);
var filename = $"Inventory{DateTime.Today:yyyyMMdd}.xlsx";
return
new FileContentResult(excel, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = filename
};
}
[ActionLog]
public JsonResult Add(InventoryAddForm form)
{
if (!ModelState.IsValid)
return GetModelStateErrorListJson();
var inventory = Mapper.Map<Inventory>(form);
var inventory = _mapper.Map<Inventory>(form);
inventory.InventoryType = _context.InventoryTypes.Find(form.InventoryTypeId);
if (inventory.InventoryType == null)
@@ -77,7 +100,7 @@ namespace InventoryTraker.Web.Controllers
};
_context.SaveChanges();
var model = Mapper.Map<InventoryViewModel>(inventory);
var model = _mapper.Map<InventoryViewModel>(inventory);
return BetterJson(model);
}
@@ -134,8 +157,8 @@ namespace InventoryTraker.Web.Controllers
_context.SaveChanges();
return BetterJson(AllInventory()
.ProjectTo<InventoryViewModel>()
return BetterJson(CurrentInventory()
.ProjectTo<InventoryViewModel>(_mapper.ConfigurationProvider)
.ToArray());
}
@@ -186,7 +209,14 @@ namespace InventoryTraker.Web.Controllers
_context.SaveChanges();
return BetterJson(Mapper.Map<InventoryViewModel>(inventory));
return BetterJson(_mapper.Map<InventoryViewModel>(inventory));
}
[ActionLog]
public JsonResult Update(InventoryTypeViewModel form)
{
// TODO: add update stuff
return BetterJson(true);
}
}
}
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
@@ -7,16 +6,19 @@ using AutoMapper.QueryableExtensions;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Data;
using InventoryTraker.Web.Models;
using InventoryTraker.Web.Utilities;
namespace InventoryTraker.Web.Controllers
{
public class InventoryTypeController : ControllerBase
{
private readonly AppDbContext _context;
private readonly IMapper _mapper;
public InventoryTypeController(AppDbContext context)
public InventoryTypeController(AppDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public ActionResult Index()
@@ -28,21 +30,42 @@ namespace InventoryTraker.Web.Controllers
{
var viewModels = _context.InventoryTypes
.OrderByDescending(x => x.Name)
.ProjectTo<InventoryTypeViewModel>();
.ProjectTo<InventoryTypeViewModel>(_mapper.ConfigurationProvider);
return BetterJson(viewModels.ToArray());
}
public ActionResult Export()
{
var writer = new InventoryTypeReportWriter();
var viewModels =
_context.InventoryTypes
.OrderByDescending(x => x.Name)
.ProjectTo<InventoryTypeViewModel>(_mapper.ConfigurationProvider)
.ToArray();
var excel = writer.Write(viewModels);
var filename = $"CommodityTypes{DateTime.Today:yyyyMMdd}.xlsx";
return
new FileContentResult(excel, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = filename
};
}
public JsonResult Add(InventoryTypeViewModel form)
{
if (!ModelState.IsValid)
return GetModelStateErrorListJson();
var inventoryType = Mapper.Map<InventoryType>(form);
var inventoryType = _mapper.Map<InventoryType>(form);
_context.InventoryTypes.Add(inventoryType);
_context.SaveChanges();
var model = Mapper.Map<InventoryTypeViewModel>(inventoryType);
var model = _mapper.Map<InventoryTypeViewModel>(inventoryType);
return BetterJson(model);
}
@@ -52,11 +75,11 @@ namespace InventoryTraker.Web.Controllers
return GetModelStateErrorListJson();
var inventoryType = _context.InventoryTypes.Find(form.Id);
Mapper.Map(form, inventoryType);
_mapper.Map(form, inventoryType);
_context.SaveChanges();
var model = Mapper.Map<InventoryTypeViewModel>(inventoryType);
var model = _mapper.Map<InventoryTypeViewModel>(inventoryType);
return BetterJson(model);
}
}
@@ -1,5 +1,8 @@
using System.Web.Mvc;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using AutoMapper;
using InventoryTraker.Web.Attributes;
using InventoryTraker.Web.Identity;
using InventoryTraker.Web.Models;
using Microsoft.AspNet.Identity;
@@ -9,27 +12,54 @@ namespace InventoryTraker.Web.Controllers
public class ProfileController : ControllerBase
{
private readonly ApplicationUserManager _userManager;
private readonly IMapper _mapper;
public ProfileController(ApplicationUserManager userManager)
public ProfileController(ApplicationUserManager userManager, IMapper mapper)
{
_userManager = userManager;
_mapper = mapper;
}
public ActionResult Index()
{
var user = _userManager.FindById(User.Identity.GetUserId());
var model = Mapper.Map<ProfileForm>(user);
return View(model);
return View();
}
public JsonResult Update(ProfileForm form)
public JsonResult Get()
{
var user = _userManager.FindById(User.Identity.GetUserId());
user.Email = form.EmailAddress;
user.UserName = form.FullName;
_userManager.Update(user);
var model = _mapper.Map<ProfileForm>(user);
return BetterJson(model);
}
return Json(true);
[ActionLog]
public async Task<JsonResult> Update(ProfileForm form)
{
if (!ModelState.IsValid)
return GetModelStateErrorListJson();
var user = _userManager.FindById(User.Identity.GetUserId());
user.Email = form.Email;
user.UserName = form.UserName;
if (!string.IsNullOrEmpty(form.NewPassword))
{
if (string.IsNullOrEmpty(form.CurrentPassword))
return GetErrorListJson("Current password required");
var result =
await _userManager.ChangePasswordAsync(
user.Id, form.CurrentPassword, form.NewPassword);
if (!result.Succeeded)
return GetErrorListJson(result.Errors.ToArray());
}
var identityResult = _userManager.Update(user);
if (!identityResult.Succeeded)
return GetErrorListJson(identityResult.Errors.ToArray());
return BetterJson(_mapper.Map<ProfileForm>(user));
}
}
}
@@ -1,23 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Data;
using InventoryTraker.Web.Models;
using InventoryTraker.Web.Services;
using InventoryTraker.Web.Utilities;
namespace InventoryTraker.Web.Controllers
{
public class ReportController : ControllerBase
{
private readonly AppDbContext _context;
private readonly ReportService _reportService;
private readonly DistributionReportWriter _distributionReportWriter;
private readonly MovementReportWriter _movementReportWriter;
public ReportController(AppDbContext context)
public ReportController(
ReportService reportService,
DistributionReportWriter distributionReportWriter,
MovementReportWriter movementReportWriter)
{
_context = context;
_reportService = reportService;
_distributionReportWriter = distributionReportWriter;
_movementReportWriter = movementReportWriter;
}
[HttpGet]
@@ -28,152 +30,52 @@ namespace InventoryTraker.Web.Controllers
public ActionResult Distribution(DateTime startDate, DateTime endDate)
{
var query =
from t in _context.Transactions
where
t.TransactionType == TransactionType.Distributed
&& t.TransactionDate >= startDate
&& t.TransactionDate < endDate
group t by new { t.TransactionDate, t.Destination }
into g
select new
{
Date = g.Key.TransactionDate,
Destination = g.Key.Destination,
Transactions = g.ToList()
};
var report =
from item in query.ToArray()
select new DistributionReport
{
Date = item.Date,
Destination = item.Destination,
Transactions =
Mapper.Map<IList<Transaction>, IList<TransactionViewModel>>
(item.Transactions).ToArray()
};
var report = _reportService.GetDistributionReport(startDate, endDate);
return BetterJson(report.ToArray());
}
public ActionResult DistributionExcel(DateTime startDate, DateTime endDate)
{
var report = _reportService.GetDistributionReport(startDate, endDate);
var excel = _distributionReportWriter.Write(report);
var filename = $"InventoryDistributionReport{startDate:yyyyMMdd}-{endDate:yyyyMMdd}.xlsx";
return
new FileContentResult(excel, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = filename
};
}
[HttpGet]
public ActionResult MonthlyInventory()
public ActionResult Movement()
{
return View();
}
public ActionResult MonthlyInventory(DateTime month)
public ActionResult Movement(DateTime month)
{
var startDate = month;
var endDate = startDate.AddMonths(1);
var report = _reportService.GetMovementReport(month);
var inventoryTypeReport
= new InventoryTypeReport
{
Items = GetInventoryTypeReportItems(startDate, endDate),
Month = month
};
return BetterJson(inventoryTypeReport);
return BetterJson(report);
}
private IEnumerable<InventoryTypeReportItem> GetInventoryTypeReportItems(DateTime startDate, DateTime endDate)
public ActionResult MovementExcel(DateTime month)
{
var transactionsMostRecentBefore =
(from transaction in _context.Transactions
where
transaction.TransactionDate < startDate
group transaction by transaction.Inventory
into g
let mostRecent =
g.OrderByDescending(t => t.TransactionDate)
.ThenBy(t => t.CurrentQuantity) // for days with multiple, assume it's the smallest
.FirstOrDefault()
where mostRecent.CurrentQuantity > 0
select mostRecent).ToList();
var report = _reportService.GetMovementReport(month);
var transactionSums =
(from transaction in _context.Transactions
where
transaction.TransactionDate >= startDate
&& transaction.TransactionDate < endDate
group transaction by transaction.Inventory
into g
let addedQty = g.Sum(t => t.AddedQuantity)
let distributed = g.Where(t => t.TransactionType == TransactionType.Distributed)
let distributedQty = distributed.Any() ? distributed.Sum(t => t.RemovedQuantity) : 0
let adjustment = g.Where(t =>
t.TransactionType == TransactionType.Expired
|| t.TransactionType == TransactionType.Loss)
let adjustmentQty = adjustment.Any() ? adjustment.Sum(t => t.RemovedQuantity) : 0
let endingQty =
g
.OrderByDescending(t => t.TransactionDate)
.ThenBy(t => t.CurrentQuantity)
.FirstOrDefault().CurrentQuantity
select new
{
Inventory = g.Key,
addedQty,
adjustmentQty,
distributedQty,
endingQty
}).ToList();
var excel = _movementReportWriter.Write(report);
var inventoryReportItems =
transactionsMostRecentBefore.FullOuterJoin( // source
transactionSums, // inner
before => before.Inventory.Id, // fk
sums => sums.Inventory.Id, // pk
(before, sums, r) =>
{
var item = new InventoryReportItem();
var filename = $"MonthlyInventoryReport{report.Month:MMMMyyyy}.xlsx";
if (before != null)
{
item.Inventory = before.Inventory;
item.BeginningQuantity = before.CurrentQuantity;
if (sums != null)
{
item.AddedQuantity = sums.addedQty;
item.DistributedQuantity = sums.distributedQty;
item.AdjustmentQuantity = sums.adjustmentQty;
item.EndingQuantity = sums.endingQty;
}
else // no change
{
item.EndingQuantity = item.BeginningQuantity;
}
}
else if (sums != null) // item was added in this time period
{
item.Inventory = sums.Inventory;
item.AddedQuantity = sums.addedQty;
item.DistributedQuantity = sums.distributedQty;
item.AdjustmentQuantity = sums.adjustmentQty;
item.EndingQuantity = sums.endingQty;
}
item.TotalAvailableQuantity = item.BeginningQuantity + item.AddedQuantity;
return item;
}).ToArray();
// group by inventory type
var inventoryTypeReportItems =
from item in inventoryReportItems
group item by item.Inventory.InventoryType
into grp
select new InventoryTypeReportItem
return
new FileContentResult(excel, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
InventoryType = Mapper.Map<InventoryTypeViewModel>(grp.Key),
BeginningQuantity = grp.Sum(g => g.BeginningQuantity),
AddedQuantity = grp.Sum(g => g.AddedQuantity),
TotalAvailableQuantity = grp.Sum(g => g.TotalAvailableQuantity),
DistributedQuantity = grp.Sum(g => g.DistributedQuantity),
AdjustmentQuantity = grp.Sum(g => g.AdjustmentQuantity),
EndingQuantity = grp.Sum(g => g.EndingQuantity)
FileDownloadName = filename
};
return inventoryTypeReportItems;
}
}
}
@@ -1,6 +1,6 @@
using System.Collections;
using System.Linq;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using InventoryTraker.Web.Attributes;
using InventoryTraker.Web.Core;
@@ -12,10 +12,12 @@ namespace InventoryTraker.Web.Controllers
public class TransactionController : ControllerBase
{
private readonly AppDbContext _context;
private readonly IMapper _mapper;
public TransactionController(AppDbContext context)
public TransactionController(AppDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public ActionResult Index()
@@ -27,7 +29,7 @@ namespace InventoryTraker.Web.Controllers
{
var viewModels =
_context.Transactions
.ProjectTo<TransactionViewModel>()
.ProjectTo<TransactionViewModel>(_mapper.ConfigurationProvider)
.ToArray();
return BetterJson(viewModels);
@@ -50,7 +52,7 @@ namespace InventoryTraker.Web.Controllers
var totalItems = _context.Transactions.Count();
var transactions = query
.ProjectTo<TransactionViewModel>()
.ProjectTo<TransactionViewModel>(_mapper.ConfigurationProvider)
.ToArray();
return BetterJson(new { totalItems, transactions });
}
@@ -0,0 +1,126 @@
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using AutoMapper;
using InventoryTraker.Web.Attributes;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Identity;
using InventoryTraker.Web.Models;
using Microsoft.AspNet.Identity;
namespace InventoryTraker.Web.Controllers
{
[Authorize(Roles = ApplicationRoleManager.AdminRoleName)]
public class UserController : ControllerBase
{
private readonly ApplicationUserManager _userManager;
private readonly IMapper _mapper;
public UserController(ApplicationUserManager userManager, IMapper mapper)
{
_userManager = userManager;
_mapper = mapper;
}
public ActionResult Index()
{
return View();
}
public JsonResult All()
{
var users =
from u in _userManager.Users.ToList()
let ad = _userManager.GetRoles(u.Id).Contains(ApplicationRoleManager.AdminRoleName)
orderby u.UserName
select new UserViewModel
{
UserName = u.UserName,
Email = u.Email,
Administrator = ad
};
return BetterJson(users.ToList());
}
[ActionLog]
[HttpPost]
public async Task<JsonResult> Create(UserEditForm form)
{
if (!ModelState.IsValid)
return GetModelStateErrorListJson();
var user =
new User
{
Email = form.Email,
UserName = form.UserName,
};
var identityResult = await _userManager.CreateAsync(user, form.Password);
if (!identityResult.Succeeded)
return GetErrorListJson(identityResult.Errors.ToArray());
user = _userManager.FindByEmail(form.Email);
if (form.Administrator)
{
var result = _userManager.AddToRole(user.Id, ApplicationRoleManager.AdminRoleName);
if (!result.Succeeded)
return GetErrorListJson(result.Errors.ToArray());
}
var userViewModel = _mapper.Map<UserViewModel>(user);
userViewModel.Administrator = _userManager.IsInRole(user.Id, ApplicationRoleManager.AdminRoleName);
return BetterJson(userViewModel);
}
[ActionLog]
[HttpPost]
public async Task<JsonResult> Edit(UserEditForm form)
{
if (!ModelState.IsValid)
return GetModelStateErrorListJson();
var user = _userManager.FindByEmail(form.Email);
user.UserName = form.UserName;
user.Email = form.Email;
if (!string.IsNullOrEmpty(form.Password))
{
var resetResult = await _userManager.ChangePasswordAsync(user, form.Password);
if (!resetResult.Succeeded)
return GetErrorListJson(resetResult.Errors.ToArray());
}
var rolesForUser = _userManager.GetRoles(user.Id);
if (rolesForUser.Contains(ApplicationRoleManager.AdminRoleName) && !form.Administrator)
{
var currentUser = _userManager.FindById(User.Identity.GetUserId());
if (currentUser == user)
return GetErrorListJson("Cannot remove admin from yourself");
var result = _userManager.RemoveFromRole(user.Id, ApplicationRoleManager.AdminRoleName);
if (!result.Succeeded)
return GetErrorListJson(result.Errors.ToArray());
}
else if (!rolesForUser.Contains(ApplicationRoleManager.AdminRoleName) && form.Administrator)
{
var result = _userManager.AddToRole(user.Id, ApplicationRoleManager.AdminRoleName);
if (!result.Succeeded)
return GetErrorListJson(result.Errors.ToArray());
}
var identityResult = _userManager.Update(user);
if (!identityResult.Succeeded)
return GetErrorListJson(identityResult.Errors.ToArray());
var userViewModel = _mapper.Map<UserViewModel>(user);
userViewModel.Administrator = _userManager.IsInRole(user.Id, ApplicationRoleManager.AdminRoleName);
return BetterJson(userViewModel);
}
}
}
+2
View File
@@ -2,6 +2,7 @@
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using InventoryTraker.Web.Migrations;
namespace InventoryTraker.Web
{
@@ -14,6 +15,7 @@ namespace InventoryTraker.Web
BundleConfig.RegisterBundles(BundleTable.Bundles);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
EFConfig.Initialize();
SeedData.AddAdminRole();
//SeedData.Init();
}
}
@@ -75,40 +75,68 @@ namespace InventoryTraker.Web.Helpers
var expression = ExpressionForInternal(property);
//Creates <div class="form-group has-feedback"
// form-group-validation="Name">
var formGroup = new HtmlTag("div")
.AddClasses("form-group", "has-feedback")
.Attr("form-group-validation", name);
var labelText = metadata.DisplayName ?? name.Humanize(LetterCasing.Title);
//Creates <label class="control-label" for="Name">Name</label>
var label = new HtmlTag("label")
.AddClass("control-label")
.Attr("for", name)
.Text(labelText);
var tagName = metadata.DataTypeName == "MultilineText"
? "textarea"
var tagName =
metadata.DataTypeName == "MultilineText"
? "textarea"
: "input";
var placeholder = metadata.Watermark ??
(labelText + "...");
//Creates <input ng-model="expression"
// class="form-control" name="Name" type="text" >
var input = new HtmlTag(tagName)
.AddClass("form-control")
.Attr("ng-model", expression)
.Attr("name", name)
.Attr("type", "text")
.Attr("placeholder", placeholder);
.Attr("name", name);
ApplyValidationToInput(input, metadata);
var formGroup = new HtmlTag("div");
return formGroup
.Append(label)
.Append(input);
if (metadata.ModelType != typeof(bool))
{
label.AddClass("control-label");
var placeholder = metadata.Watermark ??
labelText + "...";
input
.AddClass("form-control")
.Attr("type", "text")
.Attr("placeholder", placeholder);
ApplyValidationToInput(input, metadata);
//Creates <div class="form-group has-feedback"
// form-group-validation="Name">
formGroup
.AddClass("form-group")
.AddClass("has-feedback")
.Attr("form-group-validation", name)
.Append(label)
.Append(input);
}
else if (metadata.ModelType == typeof(bool))
{
label.AddClass("form-check-label");
input
.AddClass("form-check-input")
.Attr("type", "checkbox");
label.Text("")
.Append(input)
.AppendHtml("&nbsp;&nbsp;")
.Append(new HtmlTag("text").NoTag().Text(labelText));
formGroup
.AddClass("form-check")
.Append(label);
}
return formGroup;
}
private void ApplyValidationToInput(HtmlTag input, ModelMetadata metadata)
@@ -119,6 +147,9 @@ namespace InventoryTraker.Web.Helpers
if (metadata.DataTypeName == "EmailAddress")
input.Attr("type", "email");
if (metadata.DataTypeName == "Password")
input.Attr("type", "password");
if (metadata.ModelType == typeof(DateTime))
{
//input.Attr("type", "date");
@@ -1,11 +1,25 @@
using System;
using System.Threading.Tasks;
using InventoryTraker.Web.Core;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;
namespace InventoryTraker.Web.Identity
{
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public const string AdminRoleName = "Admin";
public ApplicationRoleManager(IRoleStore<IdentityRole, string> store) : base(store)
{
}
}
public class ApplicationUserManager : UserManager<User>
{
public ApplicationUserManager(IUserStore<User> store)
public ApplicationUserManager(IUserStore<User> store, IDataProtectionProvider dataProtectionProvider)
: base(store)
{
UserValidator = new UserValidator<User>(this)
@@ -13,6 +27,21 @@ namespace InventoryTraker.Web.Identity
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
if (dataProtectionProvider != null)
{
var dataProtector = dataProtectionProvider.Create("Protector");
UserTokenProvider = new DataProtectorTokenProvider<User, string>(dataProtector)
{
TokenLifespan = TimeSpan.FromHours(1),
};
}
}
public async Task<IdentityResult> ChangePasswordAsync(User user, string newPassword)
{
var resetToken = await GeneratePasswordResetTokenAsync(user.Id);
return await ResetPasswordAsync(user.Id, resetToken, newPassword);
}
}
}
+34 -15
View File
@@ -43,8 +43,8 @@
<HintPath>..\packages\Antlr.3.5.0.2\lib\Antlr3.Runtime.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="AutoMapper, Version=4.2.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005, processorArchitecture=MSIL">
<HintPath>..\packages\AutoMapper.4.2.0\lib\net45\AutoMapper.dll</HintPath>
<Reference Include="AutoMapper, Version=5.1.1.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005, processorArchitecture=MSIL">
<HintPath>..\packages\AutoMapper.5.1.1\lib\net45\AutoMapper.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="ClosedXML, Version=0.76.0.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b, processorArchitecture=MSIL">
@@ -71,10 +71,6 @@
<HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Heroic.AutoMapper, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Heroic.AutoMapper.2.0.0\lib\net45\Heroic.AutoMapper.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Heroic.Web.IoC, Version=4.1.2.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Heroic.Web.IoC.4.1.2\lib\net45\Heroic.Web.IoC.dll</HintPath>
<Private>True</Private>
@@ -232,6 +228,13 @@
<Content Include="Global.asax" />
<Content Include="js\app.js" />
<Content Include="js\authentication\LoginController.js" />
<Content Include="js\profile\profileSvc.js" />
<Content Include="js\profile\ProfileEditDirective.js" />
<Content Include="js\user\UserCreateDirective.js" />
<Content Include="js\user\UserController.js" />
<Content Include="js\user\UserEditDirective.js" />
<Content Include="js\user\UserListDirective.js" />
<Content Include="js\user\userSvc.js" />
<Content Include="js\inventoryType\InventoryTypeAddDirective.js" />
<Content Include="js\inventoryType\InventoryTypeListDirective.js" />
<Content Include="js\inventoryType\InventoryTypeEditDirective.js" />
@@ -245,9 +248,9 @@
<Content Include="js\inventory\inventorySvc.js" />
<Content Include="js\inventory\InventoryEditDirective.js" />
<Content Include="js\inventory\InventoryDistributeDirective.js" />
<Content Include="js\profile\EditProfileController.js" />
<Content Include="js\report\MonthlyInventoryReportDirective.js" />
<Content Include="js\report\MonthlyInventoryReportController.js" />
<Content Include="js\profile\ProfileController.js" />
<Content Include="js\report\MovementReportDirective.js" />
<Content Include="js\report\MovementReportController.js" />
<Content Include="js\report\DistributionReportDirective.js" />
<Content Include="js\utility\MonthQueryDirective.js" />
<Content Include="js\utility\DateRangeQueryDirective.js" />
@@ -263,7 +266,6 @@
<Content Include="js\utility\FormGroupValidationDirective.js" />
<Content Include="js\utility\HideZeroFilter.js" />
<Content Include="js\utility\InputValidationIconsDirective.js" />
<Content Include="js\utility\MvcGridDirective.js" />
<Content Include="js\utility\ParseDateFilter.js" />
<Content Include="Scripts\angular-animate.js" />
<Content Include="Scripts\angular-animate.min.js" />
@@ -309,7 +311,11 @@
<Content Include="js\report\templates\distributionReport.tmpl.cshtml" />
<Content Include="js\utility\templates\statusMessage.tmpl.cshtml" />
<Content Include="js\utility\templates\monthQuery.tmpl.cshtml" />
<Content Include="js\report\templates\monthlyInventoryReport.tmpl.cshtml" />
<Content Include="js\report\templates\movementReport.tmpl.cshtml" />
<Content Include="js\user\templates\userCreate.tmpl.cshtml" />
<Content Include="js\user\templates\userEdit.tmpl.cshtml" />
<Content Include="js\user\templates\userList.tmpl.cshtml" />
<Content Include="js\profile\templates\profileEdit.tmpl.cshtml" />
<None Include="NLog.xsd">
<SubType>Designer</SubType>
</None>
@@ -317,6 +323,8 @@
<None Include="Scripts\jquery-1.9.1.intellisense.js" />
<Content Include="Scripts\bootstrap.js" />
<Content Include="Scripts\bootstrap.min.js" />
<Content Include="Scripts\FileSaver.js" />
<Content Include="Scripts\FileSaver.min.js" />
<Content Include="Scripts\jquery-1.9.1.js" />
<Content Include="Scripts\jquery-1.9.1.min.js" />
<Content Include="Scripts\ui-grid.js" />
@@ -332,6 +340,8 @@
<Compile Include="App_Start\EFConfig.cs" />
<Compile Include="App_Start\FilterConfig.cs" />
<Compile Include="App_Start\RouteConfig.cs" />
<Content Include="js\utility\DownloadService.js" />
<Compile Include="Controllers\UserController.cs" />
<Compile Include="Migrations\SeedData.cs" />
<Compile Include="App_Start\Startup.cs" />
<Compile Include="App_Start\StructureMapConfig.cs" />
@@ -367,27 +377,34 @@
<DependentUpon>201609201242047_Initial.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\Configuration.cs" />
<Compile Include="Models\UserEditForm.cs" />
<Compile Include="Models\UserViewModel.cs" />
<Compile Include="Models\UserCreateForm.cs" />
<Compile Include="Models\DateRangeQuery.cs" />
<Compile Include="Models\DistributionReport.cs" />
<Compile Include="Models\InventoryDistributeForm.cs" />
<Compile Include="Models\InventoryAddForm.cs" />
<Compile Include="Models\InventoryQuantityForm.cs" />
<Compile Include="Models\InventoryRemoveForm.cs" />
<Compile Include="Models\InventoryReportItem.cs" />
<Compile Include="Models\InventoryTypeReport.cs" />
<Compile Include="Models\InventoryTypeReportItem.cs" />
<Compile Include="Models\MovementReport.cs" />
<Compile Include="Models\MovementReportItem.cs" />
<Compile Include="Models\InventoryTypeViewModel.cs" />
<Compile Include="Models\InventoryViewModel.cs" />
<Compile Include="Models\LoginForm.cs" />
<Compile Include="Models\ProfileForm.cs" />
<Compile Include="Models\TransactionViewModel.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\ReportService.cs" />
<Compile Include="Utilities\ControllerContextExtensions.cs" />
<Compile Include="Utilities\InventoryTypeReportWriter.cs" />
<Compile Include="Utilities\InventoryReportWriter.cs" />
<Compile Include="Utilities\ExcelParserBase.cs" />
<Compile Include="Utilities\IEnumerableExtensions.cs" />
<Compile Include="Utilities\InventoryTypeParser.cs" />
<Compile Include="Utilities\DateExtensions.cs" />
<Compile Include="Utilities\JsonExtensions.cs" />
<Compile Include="Utilities\DistributionReportWriter.cs" />
<Compile Include="Utilities\MovementReportWriter.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Views\web.config" />
@@ -410,7 +427,8 @@
<Content Include="Views\Transaction\Index.cshtml" />
<Content Include="Views\InventoryType\Index.cshtml" />
<Content Include="Views\Report\Distribution.cshtml" />
<Content Include="Views\Report\MonthlyInventory.cshtml" />
<Content Include="Views\Report\Movement.cshtml" />
<Content Include="Views\User\Index.cshtml" />
<None Include="Web.Debug.config">
<DependentUpon>Web.config</DependentUpon>
</None>
@@ -423,6 +441,7 @@
<DependentUpon>201609201242047_Initial.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup />
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
+29 -1
View File
@@ -14,6 +14,34 @@ namespace InventoryTraker.Web.Migrations
{
public static class SeedData
{
public static void AddAdminRole()
{
using (var context = new AppDbContext())
AddAdminRole(context);
}
private static void AddAdminRole(AppDbContext context)
{
var manager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context));
if (!manager.RoleExists(ApplicationRoleManager.AdminRoleName))
{
var result = manager.Create(new IdentityRole(ApplicationRoleManager.AdminRoleName));
}
// if no users are admins, make them all!
var adminRole = manager.Roles.First(r => r.Name == ApplicationRoleManager.AdminRoleName);
var userManager = new ApplicationUserManager(new UserStore<User>(context), null);
var admins = userManager.Users.Where(u => u.Roles.Any(r => r.RoleId == adminRole.Id));
if (!admins.Any())
{
foreach (var user in userManager.Users.ToList())
{
userManager.AddToRole(user.Id, ApplicationRoleManager.AdminRoleName);
}
}
}
public static void Init()
{
using (var context = new AppDbContext())
@@ -24,7 +52,7 @@ namespace InventoryTraker.Web.Migrations
{
if (!context.Users.Any())
{
var manager = new ApplicationUserManager(new UserStore<User>(context));
var manager = new ApplicationUserManager(new UserStore<User>(context), null);
manager.Create(new User
{
Email = "james.kolpack@gmail.com",
+10 -2
View File
@@ -1,12 +1,12 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Heroic.AutoMapper;
using AutoMapper;
using InventoryTraker.Web.Core;
namespace InventoryTraker.Web.Models
{
public class InventoryAddForm : IMapTo<Inventory>
public class InventoryAddForm
{
[HiddenInput(DisplayValue = false)]
[Required]
@@ -22,5 +22,13 @@ namespace InventoryTraker.Web.Models
public DateTime AddedDate { get; set; }
public string Memo { get; set; }
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<InventoryAddForm, Inventory>();
}
}
}
}
@@ -1,15 +0,0 @@
using InventoryTraker.Web.Core;
namespace InventoryTraker.Web.Models
{
public class InventoryReportItem
{
public Inventory Inventory { get; set; }
public int BeginningQuantity { get; set; }
public int AddedQuantity { get; set; }
public int TotalAvailableQuantity { get; set; }
public int DistributedQuantity { get; set; }
public int AdjustmentQuantity { get; set; }
public int EndingQuantity { get; set; }
}
}
@@ -1,11 +1,11 @@
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Heroic.AutoMapper;
using AutoMapper;
using InventoryTraker.Web.Core;
namespace InventoryTraker.Web.Models
{
public class InventoryTypeViewModel : IMapFrom<InventoryType>, IMapTo<InventoryType>
public class InventoryTypeViewModel
{
[HiddenInput]
public int Id { get; set; }
@@ -22,10 +22,25 @@ namespace InventoryTraker.Web.Models
[Required]
public string ContainerType { get; set; }
[HiddenInput]
public string UnitsPerCaseContainerType
{
get { return $"{UnitsPerCase} / {ContainerType}"; }
}
[Required]
public double WeightPerCase { get; set; }
[Required]
public decimal PricePerCase { get; set; }
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<InventoryType, InventoryTypeViewModel>();
CreateMap<InventoryTypeViewModel, InventoryType>();
}
}
}
}
@@ -1,11 +1,10 @@
using System;
using AutoMapper;
using Heroic.AutoMapper;
using InventoryTraker.Web.Core;
namespace InventoryTraker.Web.Models
{
public class InventoryViewModel : IMapFrom<Inventory>, IHaveCustomMappings
public class InventoryViewModel
{
public int Id { get; set; }
@@ -31,16 +30,19 @@ namespace InventoryTraker.Web.Models
public bool IsExpired => ExpirationDate < DateTime.Today;
public void CreateMappings(IMapperConfiguration configuration)
public class AutoMapperProfile : Profile
{
configuration.CreateMap<Inventory, InventoryViewModel>()
.ForMember(d => d.InventoryTypeId, opt => opt.MapFrom(s => s.InventoryType.Id))
.ForMember(d => d.Name, opt => opt.MapFrom(s => s.InventoryType.Name))
.ForMember(d => d.UnitsPerCase, opt => opt.MapFrom(s => s.InventoryType.UnitsPerCase))
.ForMember(d => d.ContainerType, opt => opt.MapFrom(s => s.InventoryType.ContainerType))
.ForMember(d => d.WeightPerCase, opt => opt.MapFrom(s => s.InventoryType.WeightPerCase))
.ForMember(d => d.PricePerCase, opt => opt.MapFrom(s => s.InventoryType.PricePerCase))
.ForMember(d => d.AddedDate, opt => opt.MapFrom(s => s.AddedDate));
public AutoMapperProfile()
{
CreateMap<Inventory, InventoryViewModel>()
.ForMember(d => d.InventoryTypeId, opt => opt.MapFrom(s => s.InventoryType.Id))
.ForMember(d => d.Name, opt => opt.MapFrom(s => s.InventoryType.Name))
.ForMember(d => d.UnitsPerCase, opt => opt.MapFrom(s => s.InventoryType.UnitsPerCase))
.ForMember(d => d.ContainerType, opt => opt.MapFrom(s => s.InventoryType.ContainerType))
.ForMember(d => d.WeightPerCase, opt => opt.MapFrom(s => s.InventoryType.WeightPerCase))
.ForMember(d => d.PricePerCase, opt => opt.MapFrom(s => s.InventoryType.PricePerCase))
.ForMember(d => d.AddedDate, opt => opt.MapFrom(s => s.AddedDate));
}
}
}
}
@@ -3,9 +3,9 @@ using System.Collections.Generic;
namespace InventoryTraker.Web.Models
{
public class InventoryTypeReport
public class MovementReport
{
public DateTime Month { get; set; }
public IEnumerable<InventoryTypeReportItem> Items { get; set; }
public IEnumerable<MovementReportItem> Items { get; set; }
}
}
@@ -1,6 +1,6 @@
namespace InventoryTraker.Web.Models
{
public class InventoryTypeReportItem
public class MovementReportItem
{
public InventoryTypeViewModel InventoryType { get; set; }
public int BeginningQuantity { get; set; }
+29 -10
View File
@@ -1,23 +1,42 @@
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using Heroic.AutoMapper;
using InventoryTraker.Web.Core;
namespace InventoryTraker.Web.Models
{
public class ProfileForm : IMapFrom<User>, IHaveCustomMappings
public class ProfileForm
{
[Required, Display(Name = "Full Name", Prompt = "Full Name (ex: John Doe)...")]
public string FullName { get; set; }
[Required]
[StringLength(128)]
[RegularExpression(@"[A-Za-z().]+(\s+[A-Za-z().]+)+", ErrorMessage = "Need complete name")]
public string UserName { get; set; }
[Required, DataType(DataType.EmailAddress), Display(Prompt = "your@email.com...")]
public string EmailAddress { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}", ErrorMessage = "Must be an email address")]
public string Email { get; set; }
public void CreateMappings(IMapperConfiguration configuration)
[DataType(DataType.Password)]
public string CurrentPassword { get; set; }
[DataType(DataType.Password)]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Compare("NewPassword")]
public string ConfirmPassword { get; set; }
public override string ToString()
{
configuration.CreateMap<User, ProfileForm>()
.ForMember(d => d.FullName, opt => opt.MapFrom(s => s.UserName))
.ForMember(d => d.EmailAddress, opt => opt.MapFrom(s => s.Email));
return $"UserName: {UserName}, email: {Email}";
}
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<User, ProfileForm>();
}
}
}
}
@@ -1,12 +1,11 @@
using System;
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using Heroic.AutoMapper;
using InventoryTraker.Web.Core;
namespace InventoryTraker.Web.Models
{
public class TransactionViewModel : IMapFrom<Transaction>, IHaveCustomMappings
public class TransactionViewModel
{
[Required]
public int Id { get; set; }
@@ -37,27 +36,30 @@ namespace InventoryTraker.Web.Models
public DateTime Timestamp { get; set; }
public void CreateMappings(IMapperConfiguration configuration)
public class AutoMapperProfile : Profile
{
configuration.CreateMap<Transaction, TransactionViewModel>()
.ForMember(d => d.InventoryId,
opt => opt.MapFrom(s => s.Inventory.Id))
.ForMember(d => d.Name,
opt => opt.MapFrom(s => s.Inventory.InventoryType.Name))
.ForMember(d => d.ExpirationDate,
opt => opt.MapFrom(s => s.Inventory.ExpirationDate))
.ForMember(d => d.AddedDate,
opt => opt.MapFrom(s => s.Inventory.AddedDate))
.ForMember(d => d.UnitsPerCase,
opt => opt.MapFrom(s => s.Inventory.InventoryType.UnitsPerCase))
.ForMember(d => d.ContainerType,
opt => opt.MapFrom(s => s.Inventory.InventoryType.ContainerType))
.ForMember(d => d.WeightPerCase,
opt => opt.MapFrom(s => s.Inventory.InventoryType.WeightPerCase))
.ForMember(d => d.TransactionType,
opt => opt.MapFrom(s => s.TransactionType.ToString()))
.ForMember(d => d.PreviousQuantity,
opt => opt.MapFrom(s => s.CurrentQuantity - s.AddedQuantity + s.RemovedQuantity));
public AutoMapperProfile()
{
CreateMap<Transaction, TransactionViewModel>()
.ForMember(d => d.InventoryId,
opt => opt.MapFrom(s => s.Inventory.Id))
.ForMember(d => d.Name,
opt => opt.MapFrom(s => s.Inventory.InventoryType.Name))
.ForMember(d => d.ExpirationDate,
opt => opt.MapFrom(s => s.Inventory.ExpirationDate))
.ForMember(d => d.AddedDate,
opt => opt.MapFrom(s => s.Inventory.AddedDate))
.ForMember(d => d.UnitsPerCase,
opt => opt.MapFrom(s => s.Inventory.InventoryType.UnitsPerCase))
.ForMember(d => d.ContainerType,
opt => opt.MapFrom(s => s.Inventory.InventoryType.ContainerType))
.ForMember(d => d.WeightPerCase,
opt => opt.MapFrom(s => s.Inventory.InventoryType.WeightPerCase))
.ForMember(d => d.TransactionType,
opt => opt.MapFrom(s => s.TransactionType.ToString()))
.ForMember(d => d.PreviousQuantity,
opt => opt.MapFrom(s => s.CurrentQuantity - s.AddedQuantity + s.RemovedQuantity));
}
}
}
}
@@ -0,0 +1,31 @@
using System.ComponentModel.DataAnnotations;
namespace InventoryTraker.Web.Models
{
public class UserCreateForm
{
[Required]
[StringLength(128)]
[RegularExpression(@"[A-Za-z().]+(\s+[A-Za-z().]+)+", ErrorMessage = "Need complete name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}", ErrorMessage = "Must be an email address")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "Confirm Password is required")]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }
public override string ToString()
{
return $"UserName: {UserName}, email: {Email}";
}
}
}
@@ -0,0 +1,32 @@
using System.ComponentModel.DataAnnotations;
namespace InventoryTraker.Web.Models
{
public class UserEditForm
{
[Required]
[StringLength(128)]
[RegularExpression(@"[A-Za-z().]+(\s+[A-Za-z().]+)+", ErrorMessage = "Need complete name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}", ErrorMessage = "Must be an email address")]
public string Email { get; set; }
//[Required]
public bool Administrator { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }
public override string ToString()
{
return $"UserName: {UserName}, email: {Email}";
}
}
}
@@ -0,0 +1,34 @@
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using InventoryTraker.Web.Core;
namespace InventoryTraker.Web.Models
{
public class UserViewModel
{
[Required]
[StringLength(128)]
[RegularExpression(@"[A-Za-z().]+(\s+[A-Za-z().]+)+", ErrorMessage = "Need complete name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[RegularExpression(@"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}", ErrorMessage = "Must be an email address")]
public string Email { get; set; }
public bool Administrator { get; set; }
public override string ToString()
{
return $"UserName: {UserName}, email: {Email}";
}
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<User, UserViewModel>();
}
}
}
}
@@ -13,7 +13,7 @@ by editing this MSBuild file. In order to learn more about this please visit htt
<ExcludeApp_Data>False</ExcludeApp_Data>
<DesktopBuildPackageLocation>C:\Users\poprhythm\Documents\code\PublishPackages\InventoryTraker.Web.zip</DesktopBuildPackageLocation>
<PackageAsSingleFile>true</PackageAsSingleFile>
<DeployIisAppPath>Default Web Site</DeployIisAppPath>
<DeployIisAppPath>InventoryTraker</DeployIisAppPath>
<PublishDatabaseSettings>
<Objects xmlns="">
<ObjectGroup Name="DefaultConnection" Order="1" Enabled="True">
+270
View File
@@ -0,0 +1,270 @@
/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20151003
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs || (function(view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var
doc = view.document
// only get URL when necessary in case Blob.js hasn't overridden it yet
, get_URL = function() {
return view.URL || view.webkitURL || view;
}
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = "download" in save_link
, click = function(node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
}
, is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent)
, webkit_req_fs = view.webkitRequestFileSystem
, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
, throw_outside = function(ex) {
(view.setImmediate || view.setTimeout)(function() {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
, fs_min_size = 0
// See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
// https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
// for the reasoning behind the timeout and revocation flow
, arbitrary_revoke_timeout = 500 // in ms
, revoke = function(file) {
var revoker = function() {
if (typeof file === "string") { // file is an object URL
get_URL().revokeObjectURL(file);
} else { // file is a File
file.remove();
}
};
if (view.chrome) {
revoker();
} else {
setTimeout(revoker, arbitrary_revoke_timeout);
}
}
, dispatch = function(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, auto_bom = function(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob(["\ufeff", blob], {type: blob.type});
}
return blob;
}
, FileSaver = function(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, blob_changed = false
, object_url
, target_view
, dispatch_all = function() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function() {
if (target_view && is_safari && typeof FileReader !== "undefined") {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function() {
var base64Data = reader.result;
target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
var new_tab = view.open(object_url, "_blank");
if (new_tab == undefined && is_safari) {
//Apple do not allow window.open, see http://bit.ly/1kZffRI
view.location.href = object_url
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
}
, abortable = function(func) {
return function() {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
}
, create_if_not_found = {create: true, exclusive: false}
, slice
;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
save_link.href = object_url;
save_link.download = name;
setTimeout(function() {
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
// Update: Google errantly closed 91158, I submitted it again:
// https://code.google.com/p/chromium/issues/detail?id=389642
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
if (webkit_req_fs && name !== "download") {
name += ".download";
}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
var save = function() {
dir.getFile(name, create_if_not_found, abortable(function(file) {
file.createWriter(abortable(function(writer) {
writer.onwriteend = function(event) {
target_view.location.href = file.toURL();
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
revoke(file);
};
writer.onerror = function() {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function(event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function() {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, {create: false}, abortable(function(file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function(ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
}
, FS_proto = FileSaver.prototype
, saveAs = function(blob, name, no_auto_bom) {
return new FileSaver(blob, name, no_auto_bom);
}
;
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name || "download");
};
}
FS_proto.abort = function() {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
return saveAs;
}(
typeof self !== "undefined" && self
|| typeof window !== "undefined" && window
|| this.content
));
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) {
define([], function() {
return saveAs;
});
}
+2
View File
@@ -0,0 +1,2 @@
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs=saveAs||function(e){"use strict";if(typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var t=e.document,n=function(){return e.URL||e.webkitURL||e},r=t.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in r,o=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},a=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),f=e.webkitRequestFileSystem,u=e.requestFileSystem||f||e.mozRequestFileSystem,s=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},c="application/octet-stream",d=0,l=500,w=function(t){var r=function(){if(typeof t==="string"){n().revokeObjectURL(t)}else{t.remove()}};if(e.chrome){r()}else{setTimeout(r,l)}},p=function(e,t,n){t=[].concat(t);var r=t.length;while(r--){var i=e["on"+t[r]];if(typeof i==="function"){try{i.call(e,n||e)}catch(o){s(o)}}}},v=function(e){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)){return new Blob(["\ufeff",e],{type:e.type})}return e},y=function(t,s,l){if(!l){t=v(t)}var y=this,m=t.type,S=false,h,R,O=function(){p(y,"writestart progress write writeend".split(" "))},g=function(){if(R&&a&&typeof FileReader!=="undefined"){var r=new FileReader;r.onloadend=function(){var e=r.result;R.location.href="data:attachment/file"+e.slice(e.search(/[,;]/));y.readyState=y.DONE;O()};r.readAsDataURL(t);y.readyState=y.INIT;return}if(S||!h){h=n().createObjectURL(t)}if(R){R.location.href=h}else{var i=e.open(h,"_blank");if(i==undefined&&a){e.location.href=h}}y.readyState=y.DONE;O();w(h)},b=function(e){return function(){if(y.readyState!==y.DONE){return e.apply(this,arguments)}}},E={create:true,exclusive:false},N;y.readyState=y.INIT;if(!s){s="download"}if(i){h=n().createObjectURL(t);r.href=h;r.download=s;setTimeout(function(){o(r);O();w(h);y.readyState=y.DONE});return}if(e.chrome&&m&&m!==c){N=t.slice||t.webkitSlice;t=N.call(t,0,t.size,c);S=true}if(f&&s!=="download"){s+=".download"}if(m===c||f){R=e}if(!u){g();return}d+=t.size;u(e.TEMPORARY,d,b(function(e){e.root.getDirectory("saved",E,b(function(e){var n=function(){e.getFile(s,E,b(function(e){e.createWriter(b(function(n){n.onwriteend=function(t){R.location.href=e.toURL();y.readyState=y.DONE;p(y,"writeend",t);w(e)};n.onerror=function(){var e=n.error;if(e.code!==e.ABORT_ERR){g()}};"writestart progress write abort".split(" ").forEach(function(e){n["on"+e]=y["on"+e]});n.write(t);y.abort=function(){n.abort();y.readyState=y.DONE};y.readyState=y.WRITING}),g)}),g)};e.getFile(s,{create:false},b(function(e){e.remove();n()}),b(function(e){if(e.code===e.NOT_FOUND_ERR){n()}else{g()}}))}),g)}),g)},m=y.prototype,S=function(e,t,n){return new y(e,t,n)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(e,t,n){if(!n){e=v(e)}return navigator.msSaveOrOpenBlob(e,t||"download")}}m.abort=function(){var e=this;e.readyState=e.DONE;p(e,"abort")};m.readyState=m.INIT=0;m.WRITING=1;m.DONE=2;m.error=m.onwritestart=m.onprogress=m.onwrite=m.onabort=m.onerror=m.onwriteend=null;return S}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!=null){define([],function(){return saveAs})}
@@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Data;
using InventoryTraker.Web.Models;
using InventoryTraker.Web.Utilities;
namespace InventoryTraker.Web.Services
{
public class ReportService
{
private readonly AppDbContext _context;
private readonly IMapper _mapper;
public ReportService(AppDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public DistributionReport[] GetDistributionReport(DateTime startDate, DateTime endDate)
{
var query =
from t in _context.Transactions
where
t.TransactionType == TransactionType.Distributed
&& t.TransactionDate >= startDate
&& t.TransactionDate < endDate
group t by new { t.TransactionDate, t.Destination }
into g
select new
{
Date = g.Key.TransactionDate,
Destination = g.Key.Destination,
Transactions = g.ToList()
};
var report =
from item in query.ToArray()
select new DistributionReport
{
Date = item.Date,
Destination = item.Destination,
Transactions =
_mapper.Map<IList<Transaction>, IList<TransactionViewModel>>
(item.Transactions).ToArray()
};
return report.ToArray();
}
public MovementReport GetMovementReport(DateTime month)
{
var startDate = month;
var endDate = startDate.AddMonths(1);
return
new MovementReport
{
Items = GetMovementReportItems(startDate, endDate),
Month = month
};
}
private IEnumerable<MovementReportItem> GetMovementReportItems(DateTime startDate, DateTime endDate)
{
var transactionsMostRecentBefore =
(from transaction in _context.Transactions
where
transaction.TransactionDate < startDate
group transaction by transaction.Inventory
into g
let mostRecent =
g.OrderByDescending(t => t.TransactionDate)
.ThenBy(t => t.CurrentQuantity) // for days with multiple, assume it's the smallest
.FirstOrDefault()
where mostRecent.CurrentQuantity > 0
select mostRecent).ToList();
var transactionSums =
(from transaction in _context.Transactions
where
transaction.TransactionDate >= startDate
&& transaction.TransactionDate < endDate
group transaction by transaction.Inventory
into g
let addedQty = g.Sum(t => t.AddedQuantity)
let distributed = g.Where(t => t.TransactionType == TransactionType.Distributed)
let distributedQty = distributed.Any() ? distributed.Sum(t => t.RemovedQuantity) : 0
let adjustment = g.Where(t =>
t.TransactionType == TransactionType.Expired
|| t.TransactionType == TransactionType.Loss)
let adjustmentQty = adjustment.Any() ? adjustment.Sum(t => t.RemovedQuantity) : 0
let endingQty =
g
.OrderByDescending(t => t.TransactionDate)
.ThenBy(t => t.CurrentQuantity)
.FirstOrDefault().CurrentQuantity
select new
{
Inventory = g.Key,
addedQty,
adjustmentQty,
distributedQty,
endingQty
}).ToList();
var inventoryReportItems =
transactionsMostRecentBefore.FullOuterJoin( // source
transactionSums, // inner
before => before.Inventory.Id, // fk
sums => sums.Inventory.Id, // pk
(before, sums, r) =>
{
var item = new MovementReportInventoryItem();
if (before != null)
{
item.Inventory = before.Inventory;
item.BeginningQuantity = before.CurrentQuantity;
if (sums != null)
{
item.AddedQuantity = sums.addedQty;
item.DistributedQuantity = sums.distributedQty;
item.AdjustmentQuantity = sums.adjustmentQty;
item.EndingQuantity = sums.endingQty;
}
else // no change
{
item.EndingQuantity = item.BeginningQuantity;
}
}
else if (sums != null) // item was added in this time period
{
item.Inventory = sums.Inventory;
item.AddedQuantity = sums.addedQty;
item.DistributedQuantity = sums.distributedQty;
item.AdjustmentQuantity = sums.adjustmentQty;
item.EndingQuantity = sums.endingQty;
}
item.TotalAvailableQuantity = item.BeginningQuantity + item.AddedQuantity;
return item;
}).ToArray();
// group by inventory type
var inventoryTypeReportItems =
from item in inventoryReportItems
group item by item.Inventory.InventoryType
into grp
select new MovementReportItem
{
InventoryType = _mapper.Map<InventoryTypeViewModel>(grp.Key),
BeginningQuantity = grp.Sum(g => g.BeginningQuantity),
AddedQuantity = grp.Sum(g => g.AddedQuantity),
TotalAvailableQuantity = grp.Sum(g => g.TotalAvailableQuantity),
DistributedQuantity = grp.Sum(g => g.DistributedQuantity),
AdjustmentQuantity = grp.Sum(g => g.AdjustmentQuantity),
EndingQuantity = grp.Sum(g => g.EndingQuantity)
};
return inventoryTypeReportItems;
}
private class MovementReportInventoryItem
{
public Inventory Inventory { get; set; }
public int BeginningQuantity { get; set; }
public int AddedQuantity { get; set; }
public int TotalAvailableQuantity { get; set; }
public int DistributedQuantity { get; set; }
public int AdjustmentQuantity { get; set; }
public int EndingQuantity { get; set; }
}
}
}
@@ -0,0 +1,97 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutoMapper;
using ClosedXML.Excel;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Excel;
using InventoryTraker.Web.Models;
namespace InventoryTraker.Web.Utilities
{
public class DistributionReportWriter
{
public class DistributionReportExportItem
{
public string Name { get; set; }
public string UnitsPerCaseContainerType { get; set; }
public string ExpirationDate { get; set; }
public string RemovedQuantity { get; set; }
public string UnitQuantity { get; set; }
public string Weight { get; set; }
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<TransactionViewModel, DistributionReportExportItem>()
.ForMember(d => d.Name, opt => opt.MapFrom(i => i.Name))
.ForMember(d => d.UnitsPerCaseContainerType,
opt => opt.MapFrom(i => $"{i.UnitsPerCase} / {i.ContainerType}"))
.ForMember(d => d.ExpirationDate,
opt => opt.MapFrom(i => i.ExpirationDate.ToShortDateString()))
.ForMember(d => d.UnitQuantity,
opt => opt.MapFrom(i => i.RemovedQuantity * i.UnitsPerCase))
.ForMember(d => d.Weight,
opt => opt.MapFrom(i => $"{i.WeightPerCase * i.RemovedQuantity:0} lbs"));
}
}
}
private sealed class DistributionReportMap : CsvClassMap<DistributionReportExportItem>
{
public DistributionReportMap()
{
Map(m => m.Name).Name("Name of Commodity");
Map(m => m.UnitsPerCaseContainerType).Name("Pack Size / Units per Case");
Map(m => m.ExpirationDate).Name("Expiration Date");
Map(m => m.RemovedQuantity).Name("Case Quantity");
Map(m => m.UnitQuantity).Name("Unit Quantity");
Map(m => m.Weight).Name("Weight");
}
}
private readonly IMapper _mapper;
public DistributionReportWriter(IMapper mapper)
{
_mapper = mapper;
}
public byte[] Write(IEnumerable<DistributionReport> reports)
{
using (var stream = new MemoryStream())
{
WriteStream(reports, stream);
return stream.ToArray();
}
}
public void WriteStream(IEnumerable<DistributionReport> reports, Stream stream)
{
using (var workbook = new XLWorkbook(XLEventTracking.Disabled))
{
var worksheet = workbook.AddWorksheet("Distribution Report");
using (var writer = new CsvWriter(new ExcelSerializer(worksheet)))
{
writer.Configuration.RegisterClassMap(new DistributionReportMap());
foreach (var report in reports)
{
writer.WriteField(report.Destination);
writer.NextRecord();
writer.WriteField(report.Date.ToShortDateString());
writer.NextRecord();
var items =
_mapper.Map<IEnumerable<TransactionViewModel>, IEnumerable<DistributionReportExportItem>>
(report.Transactions)
.OrderBy(i => i.Name);
writer.WriteRecords(items);
}
workbook.SaveAs(stream);
}
}
}
}
}
@@ -0,0 +1,53 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Excel;
using InventoryTraker.Web.Models;
namespace InventoryTraker.Web.Utilities
{
public class InventoryReportWriter
{
private sealed class InventoryViewModelMap : CsvClassMap<InventoryViewModel>
{
public InventoryViewModelMap()
{
Map(m => m.Name).Name("Name of Commodity");
Map(m => m.UnitsPerCase).Name("Units per Case");
Map(m => m.ContainerType).Name("Container Type");
Map(m => m.Quantity).Name("Case Quantity");
Map(m => m.ExpirationDate).Name("Expiration Date");
Map(m => m.AddedDate).Name("Added Date");
Map(m => m.Memo).Name("Memo");
Map(m => m.WeightPerCase).Name("Weight per Case");
Map(m => m.PricePerCase).Name("Price per Case");
}
}
public byte[] Write(IEnumerable<InventoryViewModel> items)
{
using (var stream = new MemoryStream())
{
WriteStream(items, stream);
return stream.ToArray();
}
}
public void WriteStream(IEnumerable<InventoryViewModel> items, Stream stream)
{
using (var workbook = new XLWorkbook(XLEventTracking.Disabled))
{
var worksheet = workbook.AddWorksheet("Current Inventory");
using (var writer = new CsvWriter(new ExcelSerializer(worksheet)))
{
writer.Configuration.RegisterClassMap(new InventoryViewModelMap());
writer.WriteRecords(items.OrderBy(i => i.Name));
workbook.SaveAs(stream);
}
}
}
}
}
@@ -0,0 +1,50 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ClosedXML.Excel;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Excel;
using InventoryTraker.Web.Models;
namespace InventoryTraker.Web.Utilities
{
public class InventoryTypeReportWriter
{
private sealed class InventoryTypeViewModelMap : CsvClassMap<InventoryTypeViewModel>
{
public InventoryTypeViewModelMap()
{
Map(m => m.Identifier).Name("Identifier");
Map(m => m.Name).Name("Name of Commodity");
Map(m => m.UnitsPerCase).Name("Units per Case");
Map(m => m.ContainerType).Name("Container Type");
Map(m => m.WeightPerCase).Name("Weight per Case");
Map(m => m.PricePerCase).Name("Price per Case");
}
}
public byte[] Write(IEnumerable<InventoryTypeViewModel> items)
{
using (var stream = new MemoryStream())
{
WriteStream(items, stream);
return stream.ToArray();
}
}
public void WriteStream(IEnumerable<InventoryTypeViewModel> items, Stream stream)
{
using (var workbook = new XLWorkbook(XLEventTracking.Disabled))
{
var worksheet = workbook.AddWorksheet("Commodity Types");
using (var writer = new CsvWriter(new ExcelSerializer(worksheet)))
{
writer.Configuration.RegisterClassMap(new InventoryTypeViewModelMap());
writer.WriteRecords(items.OrderBy(i => i.Name));
workbook.SaveAs(stream);
}
}
}
}
}
@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AutoMapper;
using ClosedXML.Excel;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Excel;
using InventoryTraker.Web.Models;
namespace InventoryTraker.Web.Utilities
{
public class MovementReportWriter
{
public class MovementReportExportItem
{
public string Name { get; set; }
public string UnitsPerCaseContainerType { get; set; }
public string BeginningQuantity { get; set; }
public string AddedQuantity { get; set; }
public string TotalAvailableQuantity { get; set; }
public string DistributedQuantity { get; set; }
public string AdjustmentQuantity { get; set; }
public string EndingQuantity { get; set; }
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
Func<int, int, string> formatCases =
(cases, unitsPerCase) => $"{cases * unitsPerCase} ({cases} cs)";
Func<int, int, string> hideEmptyCases =
(cases, unitsPerCase) =>
cases > 0
? formatCases(cases, unitsPerCase)
: "";
Func<int, int, string> negative =
(cases, unitsPerCase) =>
cases > 0
? "- " + hideEmptyCases(cases, unitsPerCase)
: "";
CreateMap<MovementReportItem, MovementReportExportItem>()
.ForMember(d => d.Name, opt => opt.MapFrom(i => i.InventoryType.Name))
.ForMember(d => d.UnitsPerCaseContainerType,
opt => opt.MapFrom(i => i.InventoryType.UnitsPerCaseContainerType))
.ForMember(d => d.BeginningQuantity,
opt => opt.MapFrom(i =>
formatCases(i.BeginningQuantity, i.InventoryType.UnitsPerCase)))
.ForMember(d => d.AddedQuantity,
opt => opt.MapFrom(i =>
hideEmptyCases(i.AddedQuantity, i.InventoryType.UnitsPerCase)))
.ForMember(d => d.TotalAvailableQuantity,
opt => opt.MapFrom(i =>
hideEmptyCases(i.TotalAvailableQuantity, i.InventoryType.UnitsPerCase)))
.ForMember(d => d.AdjustmentQuantity,
opt => opt.MapFrom(i =>
negative(i.AdjustmentQuantity, i.InventoryType.UnitsPerCase)))
.ForMember(d => d.DistributedQuantity,
opt => opt.MapFrom(i =>
hideEmptyCases(i.DistributedQuantity, i.InventoryType.UnitsPerCase)))
.ForMember(d => d.EndingQuantity,
opt => opt.MapFrom(i =>
formatCases(i.EndingQuantity, i.InventoryType.UnitsPerCase)));
}
}
}
private sealed class MovementReportMap : CsvClassMap<MovementReportExportItem>
{
public MovementReportMap()
{
Map(m => m.Name).Name("Name of Commodity");
Map(m => m.UnitsPerCaseContainerType).Name("Pack Size / Units per Case");
Map(m => m.BeginningQuantity).Name("Beginning Inventory");
Map(m => m.AddedQuantity).Name("Units Rec'd");
Map(m => m.TotalAvailableQuantity).Name("Total Units Available");
Map(m => m.AdjustmentQuantity).Name("Adjustments (show + or -)");
Map(m => m.DistributedQuantity).Name("Units Distributed");
Map(m => m.EndingQuantity).Name("Ending Inventory");
}
}
private readonly IMapper _mapper;
public MovementReportWriter(IMapper mapper)
{
_mapper = mapper;
}
public byte[] Write(MovementReport report)
{
using (var stream = new MemoryStream())
{
WriteStream(report, stream);
return stream.ToArray();
}
}
public void WriteStream(MovementReport report, Stream stream)
{
using (var workbook = new XLWorkbook(XLEventTracking.Disabled))
{
var worksheet = workbook.AddWorksheet("Monthly Inventory Report");
using (var writer = new CsvWriter(new ExcelSerializer(worksheet)))
{
writer.Configuration.RegisterClassMap(new MovementReportMap());
writer.WriteField("Monthly Inventory Report");
writer.NextRecord();
writer.WriteField<string>($"Month: {report.Month:MMMM yyyy}");
writer.NextRecord();
var items =
_mapper.Map<IEnumerable<MovementReportItem>, IEnumerable<MovementReportExportItem>>
(report.Items)
.OrderBy(i => i.Name);
writer.WriteRecords(items);
workbook.SaveAs(stream);
}
}
}
}
}
@@ -4,12 +4,13 @@
<div ng-controller="InventoryListController as vm">
<h1 class="page-header">
<i class="fa fa-cubes"></i> Inventory
<i class="fa fa-cubes"></i> @ViewBag.Title
</h1>
<h4>Current inventory</h4>
<div class="pull-left">
<a class="btn btn-default" href="" ng-click="vm.add()"><i class="fa fa-plus-circle"></i> Arrival</a>
<a class="btn btn-default" href="" ng-click="vm.distribute()"><i class="fa fa-share-square"></i> Distribute</a>
<a class="btn btn-default" href="" ng-click="vm.export()"><i class="fa fa-file-excel-o"></i> Export</a>
</div>
<div class="pull-right">
<a class="btn btn-default" href="/InventoryType"><i class="fa fa-cube"></i> Commodity Types</a>
@@ -1,16 +1,17 @@
@model dynamic
@{
ViewBag.Title = "Inventory";
ViewBag.Title = "Commodity Types";
}
<div ng-controller="InventoryTypeController as vm">
<h1 class="page-header">
<i class="fa fa-cube"></i> Commodity Types
<i class="fa fa-cube"></i> @ViewBag.Title
</h1>
<div class="pull-left">
<a class="btn btn-default" href="" ng-click="vm.add()"><i class="fa fa-plus-circle"></i> Add</a>
</div>
<a class="btn btn-default" href="" ng-click="vm.export()"><i class="fa fa-file-excel-o"></i> Export</a>
</div>
<inventory-type-list inventory-types="vm.inventoryTypes"></inventory-type-list>
</div>
+7 -44
View File
@@ -1,50 +1,13 @@
@using InventoryTraker.Web.Helpers
@model InventoryTraker.Web.Models.ProfileForm
@model InventoryTraker.Web.Models.ProfileForm
@{
ViewBag.Title = "Your Profile";
}
<h1 class="page-header">Update Your Profile</h1>
<form novalidate
name="vm.form"
ng-controller="EditProfileController as vm"
ng-submit="vm.form.$valid && vm.save()"
style="max-width: 500px;">
<fieldset ng-disabled="vm.saving">
<h1 class="page-header">Update @ViewBag.Title</h1>
<div class="alert alert-info" ng-show="vm.errorMessage == null && !vm.saving && !vm.success">
Make changes below.
</div>
<div class="alert alert-info" ng-show="vm.saving">
Saving changes...
</div>
<div class="alert alert-success" ng-show="vm.success">
<span class="fa fa-check"></span>
Changes saved!
</div>
<div class="alert alert-danger" ng-show="vm.errorMessage != null">
{{vm.errorMessage}}
</div>
@Html.Angular().FormForModel("vm.profile")
<div class="form-group">
<button class="btn btn-success">Save Changes</button>
<a class="btn btn-warning" href="/">Cancel</a>
</div>
</fieldset>
</form>
@section Scripts
{
<script>
var url = '@(Html.BuildUrlFromExpression<ProfileController>(c => c.Update(null)))';
window.app.constant('editProfileConfig', {
saveUrl: url
});
window.app.constant('model', @Html.JsonFor(Model));
</script>
}
<div class="row" ng-controller="ProfileController as vm">
<div class="panel panel-default col-md-6">
<profile-edit profile="vm.profile"></profile-edit>
</div>
</div>
@@ -5,7 +5,11 @@
<div ng-controller="DistributionReportController as vm">
<h1 class="page-header">
<i class="fa fa-file-o"></i> @ViewBag.Title
<span class="fa-stack" style="font-size: 50%">
<i class="fa fa-file-o fa-stack-2x"></i>
<i class="fa fa-share-square fa-stack-1x"></i>
</span>
@ViewBag.Title
</h1>
<div class="row hidden-print">
<div class="col-md-9">
@@ -13,6 +17,9 @@
<div class="panel-body">
<date-range-query query-fn="vm.loadData"></date-range-query>
</div>
<div class="panel-footer" ng-show="vm.distributionData.length">
<button ng-click="vm.export(vm.query)"><i class="fa fa-file-excel-o" aria-hidden="true"></i> Export</button>
</div>
</div>
</div>
</div>
@@ -1,25 +0,0 @@
@using Microsoft.Web.Mvc.Html
@{
ViewBag.Title = "Monthly Inventory Report";
}
<div ng-controller="MonthlyInventoryReportController as vm">
<h1 class="page-header">
<i class="fa fa-file-o"></i> @ViewBag.Title
</h1>
<div class="row hidden-print">
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-body">
<month-query query-fn="vm.loadData"></month-query>
</div>
</div>
</div>
</div>
<div class="row" ng-show="vm.monthlyInventoryData.items.length">
<div class="col-md-12">
<h3>{{vm.monthlyInventoryData.month | date:'MMMM yyyy'}}</h3>
<monthly-inventory-report monthly-inventory-data="vm.monthlyInventoryData"></monthly-inventory-report>
</div>
</div>
</div>
@@ -0,0 +1,32 @@
@using Microsoft.Web.Mvc.Html
@{
ViewBag.Title = "Monthly Inventory Report";
}
<div ng-controller="MovementReportController as vm">
<h1 class="page-header">
<span class="fa-stack" style="font-size: 50%">
<i class="fa fa-file-o fa-stack-2x"></i>
<i class="fa fa-cubes fa-stack-1x"></i>
</span>
@ViewBag.Title
</h1>
<div class="row hidden-print">
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-body">
<month-query query-fn="vm.loadData"></month-query>
</div>
<div class="panel-footer" ng-show="vm.movementData.items.length">
<button ng-click="vm.export(vm.movementData.month)"><i class="fa fa-file-excel-o" aria-hidden="true"></i> Export</button>
</div>
</div>
</div>
</div>
<div class="row" ng-show="vm.movementData.items.length">
<div class="col-md-12">
<h3>{{vm.movementData.month | date:'MMMM yyyy'}}</h3>
<movement-report movement-data="vm.movementData"></movement-report>
</div>
</div>
</div>
+30 -22
View File
@@ -2,32 +2,40 @@
<!DOCTYPE html>
<html lang="en" ng-app="InventoryTraker">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@ViewBag.Title - InventoryTraker</title>
@Styles.Render("~/Content/all-styles")
@RenderSection("Styles", required: false)
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@ViewBag.Title - Inventory Traker</title>
@Styles.Render("~/Content/all-styles")
@RenderSection("Styles", false)
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper" ng-cloak>
@(Request.IsAuthenticated ? Html.Partial("_Navigation") : Html.Partial("_NavigationNoAuth"))
<div id="page-wrapper">
<div class="container-fluid">
@RenderBody()
</div>
<div id="wrapper" ng-cloak>
@(Request.IsAuthenticated ? Html.Partial("_Navigation") : Html.Partial("_NavigationNoAuth"))
<div id="page-wrapper">
<div class="container-fluid">
@RenderBody()
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
@Scripts.Render("~/js/all-javascript")
@RenderSection("Scripts", required: false)
@if (Request.IsAuthenticated)
{
<footer class="footer hidden-print">
<div class="container">
<p>Inventory Traker &copy; ETHRA, 2016 Kolpack Software Consulting LLC</p>
</div>
</footer>
}
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
@Scripts.Render("~/js/all-javascript")
@RenderSection("Scripts", false)
</body>
</html>
@@ -1,4 +1,5 @@
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
@using InventoryTraker.Web.Identity
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
@@ -7,22 +8,28 @@
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="~/">Inventory Traker</a>
<a class="navbar-brand" href="~/"><i class="fa fa-fw fa-cubes"></i> Inventory Traker</a>
</div>
<!-- Top Menu Items -->
<ul class="nav navbar-right top-nav">
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> @User.Identity.Name <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<a href="@(Html.BuildUrlFromExpression<ProfileController>(c => c.Index()))"><i class="fa fa-fw fa-user"></i> Profile</a>
</li>
<li>
<a href="@(Html.BuildUrlFromExpression<AuthenticationController>(c => c.Logout()))"><i class="fa fa-fw fa-power-off"></i> Log Out</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-right top-nav">
@if (User.IsInRole(ApplicationRoleManager.AdminRoleName))
{
<li>
<a href="@(Html.BuildUrlFromExpression<UserController>(c => c.Index()))"><i class="fa fa-fw fa-users"></i> Users</a>
</li>
}
<li class="dropdown">
<a href="" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> @User.Identity.Name <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<a href="@(Html.BuildUrlFromExpression<ProfileController>(c => c.Index()))"><i class="fa fa-fw fa-user"></i> Profile</a>
</li>
<li>
<a href="@(Html.BuildUrlFromExpression<AuthenticationController>(c => c.Logout()))"><i class="fa fa-fw fa-power-off"></i> Log Out</a>
</li>
</ul>
</li>
</ul>
<!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
@@ -33,13 +40,13 @@
<a href="@(Html.BuildUrlFromExpression<TransactionController>(c => c.Index()))"><i class="fa fa-fw fa-list"></i> Transaction History</a>
</li>
<li>
<a href="#"><i class="fa fa-file-o"></i> Reports</a>
<a href="#"><i class="fa fa-fw fa-file-o"></i> Reports</a>
<ul>
<li>
<a href="@(Html.BuildUrlFromExpression<ReportController>(c => c.Distribution()))"><i class="fa fa-file-o"></i> Distribution</a>
<a href="@(Html.BuildUrlFromExpression<ReportController>(c => c.Distribution()))"><i class="fa fa-fw fa-file-o"></i> Distribution</a>
</li>
<li>
<a href="@(Html.BuildUrlFromExpression<ReportController>(c => c.MonthlyInventory()))"><i class="fa fa-file-o"></i> Monthly Inventory</a>
<a href="@(Html.BuildUrlFromExpression<ReportController>(c => c.Movement()))"><i class="fa fa-fw fa-file-o"></i> Monthly Inventory</a>
</li>
</ul>
</li>
@@ -1,6 +1,6 @@
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<a class="navbar-brand" href="~/">Inventory Traker</a>
<a class="navbar-brand" href="~/"><i class="fa fa-fw fa-cubes"></i> Inventory Traker</a>
</div>
</nav>
@@ -1,6 +1,4 @@
@using InventoryTraker.Web.Helpers
@using InventoryTraker.Web.Models
@model dynamic
@model dynamic
@{
ViewBag.Title = "Inventory";
@@ -8,7 +6,7 @@
<div ng-controller="TransactionController as vm">
<h1 class="page-header">
Transaction History
<i class="fa fa-fw fa-list"></i> Transaction History
</h1>
<div class="pull-right">
</div>
@@ -0,0 +1,16 @@
@model dynamic
@{
ViewBag.Title = "Users";
}
<div ng-controller="UserController as vm">
<h1 class="page-header">
<i class="fa fa-users"></i> @ViewBag.Title
</h1>
<div class="pull-left">
<a class="btn btn-default" href="" ng-click="vm.create()"><i class="fa fa-plus-circle"></i> Create</a>
</div>
<user-list users="vm.users"></user-list>
</div>
+7 -1
View File
@@ -82,6 +82,10 @@
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="AutoMapper" publicKeyToken="be96cd2c38ef1005" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.1.1.0" newVersion="5.1.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
@@ -102,5 +106,7 @@
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<!-- http://stackoverflow.com/a/4029197/99492 -->
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
</configuration>
+22
View File
@@ -10,9 +10,31 @@ body {
margin-top: 0;
}
.footer {
color: #aaa;
text-align: center;
width: 100%;
/* Set the fixed height of the footer here */
height: 60px;
}
#page-wrapper {
padding-top: 50px;
min-height: 100%;
padding-bottom: 60px;
margin-bottom: -60px;
}
.navbar-brand i {
color:palegreen
}
.navbar-brand:link,
.navbar-brand:visited,
.navbar-brand:hover,
.navbar-brand:active {
font-weight: bolder;
color: #92B9BD;
}
.navbar.navbar-fixed-top {
@@ -1,30 +1,31 @@
(function () {
'use strict';
(function() {
"use strict";
window.app.controller('LoginController', LoginController);
LoginController.$inject = ['$window', '$http'];
function LoginController($window, $http) {
var vm = this;
vm.errorMessage = null;
vm.loggingIn = false;
vm.login = login;
function login() {
vm.loggingIn = true;
window.app.controller("LoginController",
[
"$window", "$http",
function($window, $http) {
var vm = this;
vm.errorMessage = null;
vm.loggingIn = false;
vm.login = login;
$http.post("/Authentication/Login", { emailAddress: vm.emailAddress, password: vm.password })
.success(function() {
$window.location.href = "/";
})
.error(function(data) {
vm.errorMessage = "There was a problem logging in: " + data;
})
.finally(function() {
vm.loggingIn = false;
});
function login() {
vm.loggingIn = true;
vm.errorMessage = null;
$http.post("/Authentication/Login", { emailAddress: vm.emailAddress, password: vm.password })
.success(function() {
$window.location.href = "/";
})
.error(function(data) {
vm.errorMessage = "There was a problem logging in: " + data;
})
.finally(function() {
vm.loggingIn = false;
});
}
}
}
]);
})();
@@ -1,18 +1,16 @@
(function() {
"use strict";
window.app.directive('inventoryAdd', inventoryAdd);
function inventoryAdd() {
return {
templateUrl: '/inventory/template/inventoryAdd.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('inventoryAdd',
function() {
return {
templateUrl: '/inventory/template/inventoryAdd.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', 'inventorySvc', 'inventoryTypeSvc'];
function controller($scope, inventorySvc, inventoryTypeSvc) {
var vm = this;
@@ -1,15 +1,14 @@
(function() {
"use strict";
window.app.directive('inventoryDistribute', inventoryDistribute);
function inventoryDistribute() {
return {
templateUrl: '/inventory/template/inventoryDistribute.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('inventoryDistribute',
function() {
return {
templateUrl: '/inventory/template/inventoryDistribute.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', 'inventorySvc'];
function controller($scope, inventorySvc) {
@@ -1,18 +1,17 @@
(function() {
"use strict";
window.app.directive('editInventory', editInventory);
function editInventory() {
return {
scope: {
inventory: "="
},
templateUrl: '/inventory/template/inventoryEdit.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('editInventory',
function() {
return {
scope: {
inventory: "="
},
templateUrl: '/inventory/template/inventoryEdit.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', '$uibModal', 'inventorySvc', 'transactionSvc'];
function controller($scope, $uibModal, inventorySvc, transactionSvc) {
@@ -1,28 +1,32 @@
(function() {
'use strict';
"use strict";
window.app.controller('InventoryListController', InventoryListController);
window.app.controller("InventoryListController",
[
"$uibModal", "inventorySvc", "downloadSvc",
function($uibModal, inventorySvc, downloadSvc) {
var vm = this;
InventoryListController.$inject = ['$uibModal', 'inventorySvc'];
function InventoryListController($uibModal, inventorySvc) {
var vm = this;
vm.inventories = inventorySvc.inventories;
vm.add = add;
vm.distribute = distribute;
vm.inventories = inventorySvc.inventories;
vm.add = function() {
$uibModal.open({
template: "<inventory-add />",
backdrop: "static"
});
};
function add() {
$uibModal.open({
template: '<inventory-add />',
backdrop: 'static'
});
vm.distribute = function() {
$uibModal.open({
template: "<inventory-distribute />",
backdrop: "static"
});
};
vm.export = function() {
inventorySvc.exportInventory()
.success(downloadSvc.success);
};
}
function distribute() {
$uibModal.open({
template: '<inventory-distribute />',
backdrop: 'static'
});
}
}
]);
})();
@@ -1,15 +1,15 @@
(function() {
'use strict';
window.app.directive('inventoryList', inventoryList);
function inventoryList() {
return {
scope: {"inventories" : "="},
templateUrl: '/inventory/template/inventoryList.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('inventoryList',
function () {
return {
scope: {"inventories" : "="},
templateUrl: '/inventory/template/inventoryList.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', '$uibModal'];
function controller($scope, $uibModal) {
@@ -1,16 +1,15 @@
(function() {
"use strict";
window.app.directive('inventoryInfo', inventoryInfo);
function inventoryInfo() {
return {
scope: { "inventory": "=" },
templateUrl: '/inventory/template/inventoryInfo.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('inventoryInfo',
function() {
return {
scope: { "inventory": "=" },
templateUrl: '/inventory/template/inventoryInfo.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope'];
function controller($scope) {
@@ -1,16 +1,15 @@
(function() {
"use strict";
window.app.directive('inventoryRemove', inventoryRemove);
function inventoryRemove() {
return {
scope: { "inventory": "=" },
templateUrl: '/inventory/template/inventoryRemove.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('inventoryRemove',
function() {
return {
scope: { "inventory": "=" },
templateUrl: '/inventory/template/inventoryRemove.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', 'inventorySvc'];
function controller($scope, inventorySvc) {
@@ -1,82 +1,89 @@
(function() {
window.app.factory('inventorySvc', inventorySvc);
window.app.factory("inventorySvc",
[
"$http", "$filter",
function($http, $filter) {
var inventories = [];
inventorySvc.$inject = ['$http', '$filter'];
function inventorySvc($http, $filter) {
var inventories = [];
loadInventories();
loadInventories();
var svc = {
add: add,
distribute: distribute,
update: update,
remove: remove,
inventories: inventories,
get: get,
refresh: refresh,
find: find,
exportInventory: exportInventory
};
var svc = {
add: add,
distribute: distribute,
update: update,
remove: remove,
inventories: inventories,
get: get,
refresh: refresh,
find: find
};
return svc;
return svc;
function loadInventories() {
$http.post('/Inventory/All')
.success(function(data) {
angular.copy(data, inventories);
});
}
function add(inventory) {
return $http.post('/Inventory/Add', inventory)
.success(function(inventory) {
inventories.unshift(inventory);
});
}
function distribute(distribution) {
return $http.post('/Inventory/Distribute', distribution)
.success(function (data) {
angular.copy(data, inventories);
});
}
function update(existingInventory, updatedInventory) {
return $http.post('/Inventory/Update', updatedInventory)
.success(function(inventory) {
angular.extend(existingInventory, inventory);
});
}
// remove quantity from this inventory
function remove(removeForm) {
var existingInventory = get(removeForm.inventoryId);
return $http.post('/Inventory/Remove', removeForm)
.success(function(data) {
angular.copy(data, existingInventory);
});
}
function get(id) {
var results = $filter('filter')(inventories, { id: id });
if (results.length > 0)
return results[0];
return null;
}
// refresh this inventory from the server
function refresh(id) {
var existingInventory = get(id);
if (existingInventory) {
find(id)
.success(function(inventory) {
angular.copy(inventory, existingInventory);
function loadInventories() {
$http.post("/Inventory/All")
.success(function(data) {
angular.copy(data, inventories);
});
}
}
function find(id) {
return $http.post('/Inventory/Find', { id: id });
function exportInventory() {
return $http.post("/Inventory/Export", {}, { responseType: "arraybuffer" });
}
function add(inventory) {
return $http.post("/Inventory/Add", inventory)
.success(function(inventory) {
inventories.unshift(inventory);
});
}
function distribute(distribution) {
return $http.post("/Inventory/Distribute", distribution)
.success(function(data) {
angular.copy(data, inventories);
});
}
function update(existingInventory, updatedInventory) {
return $http.post("/Inventory/Update", updatedInventory)
.success(function(inventory) {
//angular.extend(existingInventory, inventory);
});
}
// remove quantity from this inventory
function remove(removeForm) {
var existingInventory = get(removeForm.inventoryId);
return $http.post("/Inventory/Remove", removeForm)
.success(function(data) {
angular.copy(data, existingInventory);
});
}
function get(id) {
var results = $filter("filter")(inventories, { id: id });
if (results.length > 0)
return results[0];
return null;
}
// refresh this inventory from the server
function refresh(id) {
var existingInventory = get(id);
if (existingInventory) {
find(id)
.success(function(inventory) {
angular.copy(inventory, existingInventory);
});
}
}
function find(id) {
return $http.post("/Inventory/Find", { id: id });
}
}
}
]);
})();
@@ -85,7 +85,7 @@
</div>
<div class="modal-footer">
<button class="btn btn-success">Add</button>
<button class="btn btn-success" ng-disabled="vm.form.$invalid || vm.form.$pristine">Add</button>
<button type="button" class="btn" ng-click="$dismiss()">Cancel</button>
</div>
@@ -25,37 +25,49 @@
<table class="table table-condensed" ng-class="vm.getValidationClass()">
<thead>
<tr>
<th>Name<br/>Units per Case</th>
<th>Expiration Date</th>
<th>Available Case Qty</th>
<th>Distribute Case Qty</th>
</tr>
<tr>
<th>Name<br/>Units per Case</th>
<th>Expiration Date</th>
<th>Available Case Qty</th>
<th>Distribute Case Qty</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="inventory in vm.quantities" inventory="inventory">
<td>
{{inventory.name}}<br/>
{{inventory.unitsPerCase}} / {{inventory.containerType}}<br/>
</td>
<td ng-class="{ danger: inventory.isExpired }">{{inventory.expirationDate | date:'shortDate'}}</td>
<td>{{inventory.quantity}}</td>
<td>
<div class="form-group col-sm-9" form-group-validation="DistributeQuantity{{inventory.name}}">
<input name="DistributeQuantity{{inventory.name}}" type="number"
class="form-control"
ng-model="inventory.distributeQuantity"
ng-max="{{inventory.quantity}}"
ng-min="0" />
</div>
</td>
</tr>
<tr ng-repeat="inventory in vm.quantities" inventory="inventory">
<td>
{{inventory.name}}<br/>
{{inventory.unitsPerCase}} / {{inventory.containerType}}<br/>
</td>
<td ng-class="{ danger: inventory.isExpired }">{{inventory.expirationDate | date:'shortDate'}}</td>
<td>{{inventory.quantity}}</td>
<td>
<div class="form-group col-sm-9" form-group-validation="DistributeQuantity{{inventory.name}}">
<input name="DistributeQuantity{{inventory.name}}" type="number"
class="form-control"
ng-model="inventory.distributeQuantity"
ng-max="{{inventory.quantity}}"
ng-min="0"/>
</div>
</td>
</tr>
</tbody>
</table>
<error-list errors="vm.errorMessages"></error-list>
</div>
@*<div>
<ul>
<li ng-repeat="(key, errors) in vm.form.$error track by $index">
<strong>{{ key }}</strong> errors
<ul>
<li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>
</ul>
</li>
</ul>
</div>*@
<div class="modal-footer">
<button class="btn btn-success">Save</button>
<button class="btn btn-success" @*ng-disabled="vm.form.$invalid || vm.form.$pristine"*@>Save</button>
<button type="button" class="btn" ng-click="$dismiss()">Cancel</button>
</div>
@@ -15,8 +15,8 @@
<inventory-info inventory="inventory"></inventory-info>
<div class="modal-footer">
<button ng-click="vm.removeInventory()" class="btn btn-sm pull-left"><i class="fa fa-minus-circle"></i> Remove Inventory</button>
<button class="btn btn-success">Save</button>
<button type="button" class="btn" ng-click="$parent.$dismiss()">Cancel</button>
<button class="btn btn-success" ng-disabled="vm.form.$invalid || vm.form.$pristine">Save</button>
<button type="button" class="btn" ng-click="$parent.$dismiss()">Close</button>
</div>
<hr />
@@ -18,7 +18,7 @@
</tr>
</thead>
<tbody>
<tr ng-repeat="inventory in vm.inventories">
<tr ng-repeat="inventory in vm.inventories | filter:{name: ''}">
<td>
<a href="" ng-click="vm.edit(inventory)" title="Details"><i class="fa fa-edit"></i></a>
</td>
@@ -47,7 +47,7 @@
</div>
<div class="modal-footer">
<button class="btn btn-success">Remove</button>
<button class="btn btn-success" ng-disabled="vm.form.$invalid || vm.form.$pristine">Remove</button>
<button type="button" class="btn" ng-click="$parent.$dismiss()">Cancel</button>
</div>
@@ -1,15 +1,14 @@
(function() {
"use strict";
window.app.directive('inventoryTypeAdd', inventoryTypeAdd);
function inventoryTypeAdd() {
return {
templateUrl: '/inventoryType/template/inventoryTypeAdd.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive("inventoryTypeAdd",
function() {
return {
templateUrl: "/inventoryType/template/inventoryTypeAdd.tmpl.cshtml",
controller: controller,
controllerAs: "vm"
};
});
controller.$inject = ['$scope', 'inventoryTypeSvc'];
function controller($scope, inventoryTypeSvc){
@@ -1,28 +1,24 @@
(function() {
'use strict';
"use strict";
window.app.controller('InventoryTypeController', InventoryTypeController);
window.app.controller("InventoryTypeController",
[
"$uibModal", "inventoryTypeSvc", "downloadSvc",
function($uibModal, inventoryTypeSvc, downloadSvc) {
var vm = this;
InventoryTypeController.$inject = ['$uibModal', 'inventoryTypeSvc'];
function InventoryTypeController($uibModal, inventoryTypeSvc) {
var vm = this;
vm.inventoryTypes = inventoryTypeSvc.inventoryTypes;
vm.add = add;
vm.edit = edit;
vm.inventoryTypes = inventoryTypeSvc.inventoryTypes;
function add() {
$uibModal.open({
template: '<inventory-type-add />',
backdrop: 'static'
});
vm.add = function() {
$uibModal.open({
template: "<inventory-type-add />",
backdrop: "static"
});
};
vm.export = function() {
inventoryTypeSvc.exportInventoryTypes()
.success(downloadSvc.success);
};
}
function edit() {
$uibModal.open({
template: '<inventory-type-edit />',
backdrop: 'static'
});
}
}
]);
})();
@@ -1,18 +1,17 @@
(function() {
"use strict";
window.app.directive('editInventoryType', editInventory);
function editInventory() {
return {
scope: {
inventoryType: "="
},
templateUrl: '/inventoryType/template/inventoryTypeEdit.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('editInventoryType',
function() {
return {
scope: {
inventoryType: "="
},
templateUrl: '/inventoryType/template/inventoryTypeEdit.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', 'inventoryTypeSvc'];
function controller($scope, inventoryTypeSvc) {
@@ -1,28 +1,27 @@
(function() {
'use strict';
window.app.directive('inventoryTypeList', inventoryTypeList);
function inventoryTypeList() {
return {
scope: { "inventoryTypes": "=" },
templateUrl: '/inventoryType/template/inventoryTypeList.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('inventoryTypeList',
function() {
return {
scope: { "inventoryTypes": "=" },
templateUrl: '/inventoryType/template/inventoryTypeList.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', '$uibModal'];
function controller($scope, $uibModal) {
var vm = this;
vm.inventoryTypes = $scope.inventoryTypes;
vm.edit = edit;
function edit(inventoryType) {
vm.edit = function(inventoryType) {
$uibModal.open({
template: '<edit-inventory-type inventory-type="inventoryType" />',
scope: angular.extend($scope.$new(true), { inventoryType: inventoryType })
});
}
};
}
})();
@@ -1,39 +1,45 @@
(function () {
window.app.factory('inventoryTypeSvc', inventoryTypeSvc);
(function() {
window.app.factory("inventoryTypeSvc",
[
"$http",
function($http) {
var inventoryTypes = [];
inventoryTypeSvc.$inject = ['$http'];
function inventoryTypeSvc($http) {
var inventoryTypes = [];
loadInventoryTypes();
loadInventoryTypes();
var svc = {
add: add,
update: update,
inventoryTypes: inventoryTypes,
exportInventoryTypes: exportInventoryTypes
};
var svc = {
add: add,
update: update,
inventoryTypes: inventoryTypes
};
return svc;
return svc;
function loadInventoryTypes() {
$http.post("/InventoryType/All")
.success(function(data) {
inventoryTypes.addRange(data);
});
}
function loadInventoryTypes() {
$http.post('/InventoryType/All')
.success(function (data) {
inventoryTypes.addRange(data);
});
function exportInventoryTypes() {
return $http.post("/InventoryType/Export", {}, { responseType: "arraybuffer" });
}
function add(inventoryType) {
return $http.post("/InventoryType/Add", inventoryType)
.success(function(inventoryType) {
inventoryTypes.unshift(inventoryType);
});
}
function update(existingInventoryType, updatedInventoryType) {
return $http.post("/InventoryType/Update", updatedInventoryType)
.success(function(inventoryType) {
angular.extend(existingInventoryType, inventoryType);
});
}
}
function add(inventoryType) {
return $http.post('/InventoryType/Add', inventoryType)
.success(function (inventoryType) {
inventoryTypes.unshift(inventoryType);
});
}
function update(existingInventoryType, updatedInventoryType) {
return $http.post('/InventoryType/Update', updatedInventoryType)
.success(function (inventoryType) {
angular.extend(existingInventoryType, inventoryType);
});
}
}
]);
})();
@@ -19,7 +19,7 @@
</div>
<div class="modal-footer">
<button class="btn btn-success">Add</button>
<button class="btn btn-success" ng-disabled="vm.form.$invalid || vm.form.$pristine">Add</button>
<button type="button" class="btn" ng-click="$dismiss()">Cancel</button>
</div>
@@ -19,7 +19,7 @@
</div>
<div class="modal-footer">
<button class="btn btn-success">Save</button>
<button class="btn btn-success" ng-disabled="vm.form.$invalid || vm.form.$pristine">Save</button>
<button type="button" class="btn" ng-click="$parent.$dismiss()">Cancel</button>
</div>
@@ -1,30 +0,0 @@
(function() {
'use strict';
window.app.controller('EditProfileController', EditProfileController);
EditProfileController.$inject = ['$http', 'editProfileConfig', 'model'];
function EditProfileController($http, editProfileConfig, model) {
var vm = this;
vm.profile = model;
vm.save = save;
function save() {
vm.saving = true;
vm.errorMessage = null;
vm.success = false;
$http.post(editProfileConfig.saveUrl, vm.profile)
.success(function() {
vm.success = true;
})
.error(function(msg) {
vm.errorMessage = msg;
})
.finally(function() {
vm.saving = false;
});
}
}
})();
@@ -0,0 +1,13 @@
(function() {
"use strict";
window.app.controller("ProfileController",
[
'$scope', 'profileSvc',
function ($scope, profileSvc) {
var vm = this;
vm.profile = profileSvc.profile;
}
]);
})();
@@ -0,0 +1,43 @@
(function() {
"use strict";
window.app.directive('profileEdit', function (){
return {
scope: {
profile: "="
},
templateUrl: '/profile/template/profileEdit.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', 'profileSvc'];
function controller($scope, profileSvc) {
var vm = this;
vm.profile = $scope.profile;
vm.saving = false;
vm.success = false;
vm.errorMessages = [];
vm.save = save;
function save() {
vm.saving = true;
vm.success = false;
angular.copy([], vm.errorMessages);
profileSvc.update(vm.profile)
.success(function () {
vm.success = true;
vm.form.$setPristine();
})
.error(function (data) {
vm.errorMessages = angular.copy(data.errorMessages, vm.errorMessages);
})
.finally(function () {
vm.saving = false;
});
}
}
})();
@@ -0,0 +1,32 @@
(function() {
window.app.factory("profileSvc",
[
"$http",
function($http) {
var profile = {};
loadProfile();
var svc = {
update: update,
profile: profile
};
return svc;
function loadProfile() {
$http.post("/Profile/Get")
.success(function(data) {
angular.copy(data, profile);
});
}
function update(updatedProfile) {
return $http.post("/Profile/Update", updatedProfile)
.success(function(data) {
angular.copy(data, profile);
});
}
}
]);
})();
@@ -0,0 +1,28 @@
@using InventoryTraker.Web.Helpers
@model InventoryTraker.Web.Models.ProfileForm
<form novalidate
name="vm.form"
ng-submit="vm.form.$valid && vm.save()">
<fieldset ng-disabled="vm.saving">
<div class="panel">
<div class="panel-body">
<status-message message="vm.statusMessage"></status-message>
<error-list errors="vm.errorMessages"></error-list>
<div class="alert alert-success" ng-show="vm.success && vm.form.$pristine">
<span class="fa fa-check"></span>
Changes saved
</div>
@Html.Angular().FormForModel("vm.profile")
</div>
<div class="panel-footer">
<button class="btn btn-success" ng-disabled="vm.form.$invalid || vm.form.$pristine">Save</button>
<a class="btn btn-default" href="/">Cancel</a>
</div>
</div>
</fieldset>
</form>
@@ -1,12 +1,18 @@
(function () {
'use strict';
(function() {
"use strict";
window.app.controller('DistributionReportController', DistributionReportController);
DistributionReportController.$inject = ['$scope', 'reportSvc'];
function DistributionReportController($scope, reportSvc) {
var vm = this;
vm.loadData = reportSvc.loadDistributionReport;
vm.distributionData = reportSvc.distributionData;
}
window.app.controller("DistributionReportController",
[
"$scope", "reportSvc", "downloadSvc",
function($scope, reportSvc, downloadSvc) {
var vm = this;
vm.loadData = reportSvc.loadDistributionReport;
vm.query = reportSvc.distributionQuery;
vm.distributionData = reportSvc.distributionData;
vm.export = function(params) {
reportSvc.exportDistributionReport(params)
.success(downloadSvc.success);
};
}
]);
})();
@@ -1,15 +1,15 @@
(function() {
'use strict';
window.app.directive('distributionReport', distributionReport);
function distributionReport() {
return {
scope: {distributionData: "="},
templateUrl: '/report/template/distributionReport.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('distributionReport',
function () {
return {
scope: {distributionData: "="},
templateUrl: '/report/template/distributionReport.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope'];
function controller($scope) {
@@ -1,12 +0,0 @@
(function () {
'use strict';
window.app.controller('MonthlyInventoryReportController', MonthlyInventoryReportController);
MonthlyInventoryReportController.$inject = ['$scope', 'reportSvc'];
function MonthlyInventoryReportController($scope, reportSvc) {
var vm = this;
vm.loadData = reportSvc.loadMonthlyInventoryData;
vm.monthlyInventoryData = reportSvc.monthlyInventoryData;
}
})();
@@ -0,0 +1,17 @@
(function() {
"use strict";
window.app.controller("MovementReportController",
[
"$scope", "reportSvc", "downloadSvc",
function($scope, reportSvc, downloadSvc) {
var vm = this;
vm.loadData = reportSvc.loadMovementData;
vm.movementData = reportSvc.movementData;
vm.export = function(month) {
reportSvc.exportMovementData({ month: month })
.success(downloadSvc.success);
};
}
]);
})();
@@ -1,20 +1,20 @@
(function() {
'use strict';
window.app.directive('monthlyInventoryReport', monthlyInventoryReport);
function monthlyInventoryReport() {
return {
scope: { monthlyInventoryData: "=" },
templateUrl: '/report/template/monthlyInventoryReport.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
}
window.app.directive('movementReport',
function() {
return {
scope: { movementData: "=" },
templateUrl: '/report/template/movementReport.tmpl.cshtml',
controller: controller,
controllerAs: 'vm'
}
});
controller.$inject = ['$scope', '$uibModal', 'inventorySvc'];
function controller($scope, $uibModal, inventorySvc) {
var vm = this;
vm.monthlyInventoryData = $scope.monthlyInventoryData;
vm.movementData = $scope.movementData;
vm.editInventory = function (inventoryId) {
inventorySvc.find(inventoryId)
+40 -26
View File
@@ -1,32 +1,46 @@
(function () {
window.app.factory('reportSvc', reportSvc);
(function() {
window.app.factory("reportSvc",
[
"$http",
function($http) {
var distributionData = [];
var distributionQuery = {};
var movementData = {};
reportSvc.$inject = ['$http'];
function reportSvc($http) {
var distributionData = [];
var monthlyInventoryData = {};
var svc = {
distributionData: distributionData,
distributionQuery: distributionQuery,
loadDistributionReport: loadDistributionReport,
exportDistributionReport: exportDistributionReport,
movementData: movementData,
loadMovementData: loadMovementData,
exportMovementData: exportMovementData
};
var svc = {
distributionData: distributionData,
loadDistributionReport: loadDistributionReport,
monthlyInventoryData: monthlyInventoryData,
loadMonthlyInventoryData: loadMonthlyInventoryData
};
return svc;
return svc;
function loadDistributionReport(query) {
return $http.post("/Report/Distribution", query)
.success(function(data) {
distributionQuery = angular.copy(query, distributionQuery);
angular.copy(data, distributionData);
});
}
function loadDistributionReport(query) {
return $http.post('/Report/Distribution', query)
.success(function (data) {
angular.copy(data, distributionData);
});
function exportDistributionReport(query) {
return $http.post("/Report/DistributionExcel", query, { responseType: "arraybuffer" });
}
function loadMovementData(query) {
return $http.post("/Report/Movement", query)
.success(function(data) {
angular.copy(data, movementData);
});
}
function exportMovementData(query) {
return $http.post("/Report/MovementExcel", query, { responseType: "arraybuffer" });
}
}
function loadMonthlyInventoryData(query) {
return $http.post('/Report/MonthlyInventory', query)
.success(function (data) {
angular.copy(data, monthlyInventoryData);
});
}
}
]);
})();
@@ -4,8 +4,8 @@
<table class="table table-striped">
<thead>
<tr>
<th class="col-md-3">Name</th>
<th class="col-md-3">Units per Case</th>
<th class="col-md-3">Name of Commodity</th>
<th class="col-md-3">Units per Case / Container Type</th>
<th class="col-md-2">Exp. Date</th>
<th class="col-md-1">Case Qty</th>
<th class="col-md-1">Unit Qty</th>
@@ -19,7 +19,7 @@
<td>{{transaction.expirationDate | date:'shortDate'}}</td>
<td>{{transaction.removedQuantity}}</td>
<td>{{transaction.removedQuantity * transaction.unitsPerCase}}</td>
<td>{{transaction.weightPerCase * transaction.unitsPerCase | number:0 }} lbs</td>
<td>{{transaction.weightPerCase * transaction.removedQuantity | number:0 }} lbs</td>
</tr>
</tbody>
</table>
@@ -13,7 +13,7 @@
</tr>
</thead>
<tbody>
<tr ng-repeat="item in vm.monthlyInventoryData.items | orderBy:'inventoryType.name'">
<tr ng-repeat="item in vm.movementData.items | orderBy:'inventoryType.name'">
@*<td><a href="" ng-click="vm.editInventory(item.inventory.id)"><i class="fa fa-edit"></i></a> </td>*@
<td>{{item.inventoryType.name}}</td>
<td>{{item.inventoryType.unitsPerCase}} / {{item.inventoryType.containerType}}</td>
@@ -1,82 +1,84 @@
(function() {
'use strict';
"use strict";
window.app.controller('TransactionController', TransactionController);
window.app.controller("TransactionController",
[
"$scope", "$uibModal", "transactionSvc", "inventorySvc", "uiGridConstants",
function($scope, $uibModal, transactionSvc, inventorySvc, uiGridConstants) {
var vm = this;
TransactionController.$inject = ['$scope', '$uibModal', 'transactionSvc', 'inventorySvc', 'uiGridConstants'];
function TransactionController($scope, $uibModal, transactionSvc, inventorySvc, uiGridConstants) {
var vm = this;
var paginationOptions = {
pageNumber: 1,
pageSize: 20,
pageSizes: [20, 50, 100],
sort: null
};
var paginationOptions = {
pageNumber: 1,
pageSize: 20,
pageSizes: [20,50,100],
sort: null
};
vm.gridOptions = {
enablePaginationControls: true,
paginationPageSize: paginationOptions.pageSize,
paginationPageSizes: paginationOptions.pageSizes,
useExternalPagination: true,
enableSorting: false,
columnDefs: [
{
field: 'name',
cellTooltip: function(row) {
return row.entity.name + "\r" + row.entity.unitsPerCase + " / " + row.entity.containerType;
vm.gridOptions = {
enablePaginationControls: true,
paginationPageSize: paginationOptions.pageSize,
paginationPageSizes: paginationOptions.pageSizes,
useExternalPagination: true,
enableSorting: false,
columnDefs: [
{
field: "name",
cellTooltip: function(row) {
return row.entity.name + "\r" + row.entity.unitsPerCase + " / " + row.entity.containerType;
},
cellTemplate: '<div class="ui-grid-cell-contents" ' +
'title="{{row.entity.name}}' +
"\r{{row.entity.unitsPerCase}} / {{row.entity.containerType}}" +
"\rExp Date: {{row.entity.expirationDate | date:'shortDate'}}" +
'\rAdd Date: {{row.entity.addedDate | date:\'shortDate\'}}">' +
'<a href="" ng-click="grid.appScope.editInventory(row.entity.inventoryId)"><i class="fa fa-edit"></i></a> ' +
"{{row.entity.name}}</div>",
width: "20%"
},
cellTemplate: '<div class="ui-grid-cell-contents" ' +
'title="{{row.entity.name}}' +
'\r{{row.entity.unitsPerCase}} / {{row.entity.containerType}}' +
'\rExp Date: {{row.entity.expirationDate | date:\'shortDate\'}}' +
'\rAdd Date: {{row.entity.addedDate | date:\'shortDate\'}}">' +
'<a href="" ng-click="grid.appScope.editInventory(row.entity.inventoryId)"><i class="fa fa-edit"></i></a> ' +
'{{row.entity.name}}</div>',
width: "20%"
},
{ field: 'transactionType', name: 'Type', width: "10%" },
{ field: 'destination', cellTooltip: true, width: "10%" },
{ field: 'memo', cellTooltip: true, width: "15%" },
{ field: 'transactionDate', name: 'Transaction Date', cellFilter: "date:'shortDate'", width: "10%" },
{ field: 'previousQuantity', name: 'Prev Qty', width: "10%", enableSorting: false },
{ field: 'addedQuantity', name: 'Add Qty', width: "10%", enableSorting: false, cellFilter: "hideZero" },
{ field: 'removedQuantity', name: 'Remove Qty', width: "10%", enableSorting: false, cellFilter: "hideZero" },
{ field: 'currentQuantity', name: 'Current Qty', width: "10%", enableSorting: false }
],
onRegisterApi: function(gridApi) {
vm.gridApi = gridApi;
vm.gridApi.pagination
.on.paginationChanged($scope, function(pageNumber, pageSize) {
paginationOptions.pageNumber = pageNumber;
paginationOptions.pageSize = pageSize;
updateData();
{ field: "transactionType", name: "Type", width: "10%" },
{ field: "destination", cellTooltip: true, width: "10%" },
{ field: "memo", cellTooltip: true, width: "15%" },
{ field: "transactionDate", name: "Transaction Date", cellFilter: "date:'shortDate'", width: "10%" },
{ field: "previousQuantity", name: "Prev Qty", width: "10%", enableSorting: false },
{ field: "addedQuantity", name: "Add Qty", width: "10%", enableSorting: false, cellFilter: "hideZero" },
{ field: "removedQuantity", name: "Remove Qty", width: "10%", enableSorting: false, cellFilter: "hideZero" },
{ field: "currentQuantity", name: "Current Qty", width: "10%", enableSorting: false }
],
onRegisterApi: function(gridApi) {
vm.gridApi = gridApi;
vm.gridApi.pagination
.on.paginationChanged($scope,
function(pageNumber, pageSize) {
paginationOptions.pageNumber = pageNumber;
paginationOptions.pageSize = pageSize;
updateData();
});
}
};
function updateData() {
transactionSvc
.filterByPage(paginationOptions.pageNumber, paginationOptions.pageSize)
.success(function(data) {
vm.gridOptions.data = data.transactions;
vm.gridOptions.totalItems = data.totalItems;
});
}
};
function updateData() {
transactionSvc
.filterByPage(paginationOptions.pageNumber, paginationOptions.pageSize)
.success(function (data) {
vm.gridOptions.data = data.transactions;
vm.gridOptions.totalItems = data.totalItems;
});
updateData();
$scope.editInventory = function(inventoryId) {
inventorySvc.find(inventoryId)
.success(function(inventory) {
$uibModal.open({
template: '<edit-inventory inventory="inventory" />',
scope: angular.extend($scope.$new(true), { inventory: inventory })
})
.closed.then(function() {
updateData();
});
});
};
}
updateData();
$scope.editInventory = function (inventoryId) {
inventorySvc.find(inventoryId)
.success(function(inventory) {
$uibModal.open({
template: '<edit-inventory inventory="inventory" />',
scope: angular.extend($scope.$new(true), { inventory: inventory })
})
.closed.then(function() {
updateData();
});
});
}
}
]);
})();
@@ -1,37 +1,36 @@
(function() {
window.app.factory('transactionSvc', transactionSvc);
window.app.factory('transactionSvc', [
'$http', 'inventorySvc',
function($http, inventorySvc) {
transactionSvc.$inject = ['$http', 'inventorySvc'];
function transactionSvc($http, inventorySvc) {
var svc = {
filterByPage: filterByPage,
filterByInventoryId: filterByInventoryId,
deleteTransaction: deleteTransaction
};
var svc = {
filterByPage: filterByPage,
filterByInventoryId: filterByInventoryId,
deleteTransaction: deleteTransaction
};
return svc;
return svc;
function filterByPage(pageNumber, pageSize) {
return getTransactions({ pageNumber: pageNumber, pageSize: pageSize });
}
function filterByPage(pageNumber, pageSize) {
return getTransactions({ pageNumber: pageNumber, pageSize: pageSize });
}
function filterByInventoryId(inventoryId) {
return getTransactions({ inventoryId: inventoryId });
}
function filterByInventoryId(inventoryId) {
return getTransactions({ inventoryId: inventoryId });
}
function getTransactions(params) {
var url = '/Transaction/Get';
return $http.post(url, params)
.success(function (data) {
});
}
function getTransactions(params) {
var url = '/Transaction/Get';
return $http.post(url, params)
.success(function(data) {
});
}
function deleteTransaction(transactionId) {
return $http.post('/Transaction/Delete', { transactionId: transactionId })
.success(function (data) {
inventorySvc.refresh(data.inventoryId);
});
}
}
function deleteTransaction(transactionId) {
return $http.post('/Transaction/Delete', { transactionId: transactionId })
.success(function(data) {
inventorySvc.refresh(data.inventoryId);
});
}
}]);
})();

Some files were not shown because too many files have changed in this diff Show More