Repository navigation
Expand file tree
/
Copy pathAddOrUpdateEmployeeCommand.cs
More file actions
190 lines (161 loc) · 8.9 KB
/
Copy pathAddOrUpdateEmployeeCommand.cs
File metadata and controls
190 lines (161 loc) · 8.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// Copyright ©2021 Jacobs Data Solutions
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the
// License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
using JDS.OrgManager.Application.Abstractions.DbContexts;
using JDS.OrgManager.Application.Abstractions.DbFacades;
using JDS.OrgManager.Application.Abstractions.Mapping;
using JDS.OrgManager.Application.Common.Employees;
using JDS.OrgManager.Application.Common.TimeOff;
using JDS.OrgManager.Domain.Common.Addresses;
using JDS.OrgManager.Domain.HumanResources.Employees;
using JDS.OrgManager.Domain.HumanResources.TimeOff;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EmployeeException = JDS.OrgManager.Application.Common.Employees.EmployeeException;
namespace JDS.OrgManager.Application.HumanResources.Employees.Commands.AddOrUpdateEmployee
{
public class AddOrUpdateEmployeeCommand : IRequest<AddOrUpdateEmployeeViewModel>
{
public int AspNetUsersId { get; init; }
public AddOrUpdateEmployeeViewModel Employee { get; set; } = default!;
public class AddOrUpdateEmployeeCommandHandler : IRequestHandler<AddOrUpdateEmployeeCommand, AddOrUpdateEmployeeViewModel>
{
private readonly IApplicationWriteDbContext context;
private readonly IApplicationWriteDbFacade facade;
private readonly IModelMapper mapper;
public AddOrUpdateEmployeeCommandHandler(
IApplicationWriteDbContext context,
IApplicationWriteDbFacade facade,
IModelMapper mapper
)
{
this.context = context ?? throw new ArgumentNullException(nameof(context));
this.facade = facade ?? throw new ArgumentNullException(nameof(facade));
this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
public async Task<AddOrUpdateEmployeeViewModel> Handle(AddOrUpdateEmployeeCommand request, CancellationToken cancellationToken)
{
// APPLICATION LAYER
var employeeViewModel = request.Employee;
var tenantId = employeeViewModel.TenantId;
var isNewEmployee = employeeViewModel.Id == 0;
if (tenantId == 0)
{
throw new ApplicationLayerException("Invalid tenant ID.");
}
// PERISTENCE LAYER: Hydrate existing employee or get defaults for tenant.
EmployeeEntity? employeeEntity = null;
if (isNewEmployee)
{
// Even though this is a read operation, we are using the Write dapper facade because commands should only talk to the Write database (never
// assume the two databases/sides of the stack will be in sync).
var t = await facade.QueryFirstOrDefaultAsync<int?>("SELECT TOP 1 Id FROM Tenants WITH(NOLOCK) WHERE AssignmentKey = @AssignmentKey AND Id = @TenantId", employeeViewModel, null, cancellationToken);
if (t == null)
{
throw new AccessDeniedException($"Invalid assignment key specified: {employeeViewModel.AssignmentKey}.");
}
tenantId = (int)t;
employeeEntity = await facade.QueryFirstOrDefaultAsync<EmployeeEntity>(@"
SELECT TOP (1) [TenantId]
,[CurrencyCode]
,[EmployeeLevel]
,[PaidTimeOffPolicyId]
FROM [OrgManager].[dbo].[TenantDefaults] td WITH(NOLOCK)
WHERE TenantId = @TenantId", employeeViewModel, null, cancellationToken);
employeeEntity.PtoHoursRemaining = 0.0m;
employeeEntity.AspNetUsersId = request.AspNetUsersId;
employeeEntity.IsPending = true;
}
else
{
employeeEntity =
await context.Employees
.Include(e => e.Managers)
.Include(e => e.Subordinates)
.AsNoTracking()
.FirstOrDefaultAsync(e => e.Id == employeeViewModel.Id && e.TenantId == tenantId, cancellationToken);
}
// Perform updates against persistence entity.
mapper.MapViewModelToDbEntity(employeeViewModel, employeeEntity);
// Look up subordinates.
var subordinateIds = (from e in employeeEntity.Subordinates select e.EmployeeId).ToList();
var subordinateEntities = await (from e in context.Employees.AsNoTracking() where subordinateIds.Contains(e.Id) && e.TenantId == tenantId select e).ToListAsync();
// Get PTO policy for this employee.
var policyEntity = await context.PaidTimeOffPolicies.AsNoTracking().FirstOrDefaultAsync(p => p.Id == employeeEntity.PaidTimeOffPolicyId && p.TenantId == tenantId);
if (policyEntity == null)
{
throw new EmployeeException($"PTO policy not found.");
}
// Look up manager from DB.
EmployeeEntity? managerEntity = null;
if (employeeEntity.Managers.Any())
{
var managerId = employeeEntity.Managers.First().ManagerId;
managerEntity = await context.Employees.AsNoTracking().FirstOrDefaultAsync(e => e.Id == managerId && e.TenantId == tenantId);
if (managerEntity == null)
{
throw new EmployeeException($"Manager with ID {managerId} not found.");
}
}
// DOMAIN LAYER
var employee = mapper.MapDbEntityToDomainEntity<EmployeeEntity, Employee>(employeeEntity);
// Map manager to domain entity.
if (managerEntity != null)
{
employee = employee.WithManager(mapper.MapDbEntityToDomainEntity<EmployeeEntity, Employee>(managerEntity));
}
// Map subordinates to domain entities.
employee = employee.WithSubordinates(from e in subordinateEntities select mapper.MapDbEntityToDomainEntity<EmployeeEntity, Employee>(e));
// Map PTO policy to domain entity.
var policy = mapper.MapDbEntityToDomainEntity<PaidTimeOffPolicyEntity, PaidTimeOffPolicy>(policyEntity);
employee = employee.WithPaidTimeOffPolicy(policy);
// Check the validity of the employee's PTO hours and other business logic. All business rule validation is still happening within the Domain layer...
employee.ValidateAggregate();
employee.VerifyEmployeeManagerAndSubordinates();
if (isNewEmployee)
{
employee.VerifyStartingPtoHoursAreValid();
}
else
{
employee.VerifyPtoHoursAreValid();
}
// End business logic.
// PERSISTENCE LAYER Convert back to persistence entity.
mapper.MapDomainEntityToDbEntity(employee, employeeEntity);
var entry = await context.Employees.AddAsync(employeeEntity);
if (!isNewEmployee)
{
entry.State = EntityState.Modified;
}
// We are not updating employee/manager relationships at this time.
employeeEntity.Subordinates.Clear();
employeeEntity.Managers.Clear();
// Commit transaction to DB.
await context.SaveChangesAsync(cancellationToken);
// Set ID of domain entity.
employee.Id = employeeEntity.Id;
// Kick off domain events.
if (isNewEmployee)
{
employee.CreateEmployeeRegisteredEvent();
}
else
{
employee.CreateEmployeeUpdatedEvent();
}
await employee.DispatchDomainEventsAsync();
// Map from domain entity back to VM (command) and return that.
mapper.MapDomainEntityToViewModel(employee, employeeViewModel);
return employeeViewModel;
}
}
}
}