CHECKPOINT COMMIT - POST SERVICE BANK REMOVAL

Service bank feature removed from front, back and e2e testing
mostly commented out in case need to add back again but in some places such as db schema it had to be removed entirely
so refer here if adding back in again
This commit is contained in:
2021-06-04 22:23:21 +00:00
parent c936ff5e3e
commit 59fd41d8d0
27 changed files with 756 additions and 761 deletions

View File

@@ -384,7 +384,7 @@ namespace AyaNova.Api.Controllers
TranslationKeysToFetch.Add("NotifyEventQuoteStatusChange");
TranslationKeysToFetch.Add("NotifyEventQuoteStatusAge");
TranslationKeysToFetch.Add("NotifyEventObjectAge");
TranslationKeysToFetch.Add("NotifyEventServiceBankDepleted");
// TranslationKeysToFetch.Add("NotifyEventServiceBankDepleted");
TranslationKeysToFetch.Add("NotifyEventReminderImminent");
TranslationKeysToFetch.Add("NotifyEventScheduledOnWorkorder");
TranslationKeysToFetch.Add("NotifyEventScheduledOnWorkorderImminent");
@@ -419,7 +419,7 @@ namespace AyaNova.Api.Controllers
ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventQuoteStatusChange"], Id = (long)NotifyEventType.QuoteStatusChange });
ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventQuoteStatusAge"], Id = (long)NotifyEventType.QuoteStatusAge });
ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventObjectAge"], Id = (long)NotifyEventType.ObjectAge });
ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventServiceBankDepleted"], Id = (long)NotifyEventType.ServiceBankDepleted });
// ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventServiceBankDepleted"], Id = (long)NotifyEventType.ServiceBankDepleted });
ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventReminderImminent"], Id = (long)NotifyEventType.ReminderImminent });
ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventScheduledOnWorkorder"], Id = (long)NotifyEventType.ScheduledOnWorkorder });
ReturnList.Add(new NameIdItem() { Name = LT["NotifyEventScheduledOnWorkorderImminent"], Id = (long)NotifyEventType.ScheduledOnWorkorderImminent });

View File

@@ -1,116 +1,116 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using AyaNova.Models;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Biz;
// using System.Threading.Tasks;
// using Microsoft.AspNetCore.Http;
// using Microsoft.AspNetCore.Mvc;
// using Microsoft.AspNetCore.Routing;
// using Microsoft.AspNetCore.Authorization;
// using Microsoft.Extensions.Logging;
// using AyaNova.Models;
// using AyaNova.Api.ControllerHelpers;
// using AyaNova.Biz;
namespace AyaNova.Api.Controllers
{
[ApiController]
[ApiVersion("8.0")]
[Route("api/v{version:apiVersion}/service-bank")]
[Produces("application/json")]
[Authorize]
public class ServiceBankController : ControllerBase
{
private readonly AyContext ct;
private readonly ILogger<ServiceBankController> log;
private readonly ApiServerState serverState;
// namespace AyaNova.Api.Controllers
// {
// [ApiController]
// [ApiVersion("8.0")]
// [Route("api/v{version:apiVersion}/service-bank")]
// [Produces("application/json")]
// [Authorize]
// public class ServiceBankController : ControllerBase
// {
// private readonly AyContext ct;
// private readonly ILogger<ServiceBankController> log;
// private readonly ApiServerState serverState;
/// <summary>
/// ctor
/// </summary>
/// <param name="dbcontext"></param>
/// <param name="logger"></param>
/// <param name="apiServerState"></param>
public ServiceBankController(AyContext dbcontext, ILogger<ServiceBankController> logger, ApiServerState apiServerState)
{
ct = dbcontext;
log = logger;
serverState = apiServerState;
}
// /// <summary>
// /// ctor
// /// </summary>
// /// <param name="dbcontext"></param>
// /// <param name="logger"></param>
// /// <param name="apiServerState"></param>
// public ServiceBankController(AyContext dbcontext, ILogger<ServiceBankController> logger, ApiServerState apiServerState)
// {
// ct = dbcontext;
// log = logger;
// serverState = apiServerState;
// }
/// <summary>
/// Create ServiceBank
/// (This object is create / get only, there is no update or delete only adjustments through new entries)
/// </summary>
/// <param name="newObject"></param>
/// <param name="apiVersion">From route path</param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> PostServiceBank([FromBody] dtServiceBank newObject, ApiVersion apiVersion)
{
if (!serverState.IsOpen)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
ServiceBankBiz biz = ServiceBankBiz.GetBiz(ct, HttpContext);
if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType))
return StatusCode(403, new ApiNotAuthorizedResponse());
if (!ModelState.IsValid)
return BadRequest(new ApiErrorResponse(ModelState));
ServiceBank o = await biz.CreateAsync(newObject);
if (o == null)
return BadRequest(new ApiErrorResponse(biz.Errors));
else
return CreatedAtAction(nameof(ServiceBankController.GetServiceBank), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
}
// /// <summary>
// /// Create ServiceBank
// /// (This object is create / get only, there is no update or delete only adjustments through new entries)
// /// </summary>
// /// <param name="newObject"></param>
// /// <param name="apiVersion">From route path</param>
// /// <returns></returns>
// [HttpPost]
// public async Task<IActionResult> PostServiceBank([FromBody] dtServiceBank newObject, ApiVersion apiVersion)
// {
// if (!serverState.IsOpen)
// return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
// ServiceBankBiz biz = ServiceBankBiz.GetBiz(ct, HttpContext);
// if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType))
// return StatusCode(403, new ApiNotAuthorizedResponse());
// if (!ModelState.IsValid)
// return BadRequest(new ApiErrorResponse(ModelState));
// ServiceBank o = await biz.CreateAsync(newObject);
// if (o == null)
// return BadRequest(new ApiErrorResponse(biz.Errors));
// else
// return CreatedAtAction(nameof(ServiceBankController.GetServiceBank), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
// }
/// <summary>
/// Migrate ServiceBank
/// (for migration from v7 only, do not use)
/// </summary>
/// <param name="newObject"></param>
/// <param name="apiVersion">From route path</param>
/// <returns></returns>
[HttpPost("migrate")]
public async Task<IActionResult> MigrateServiceBank([FromBody] ServiceBank newObject, ApiVersion apiVersion)
{
if (!serverState.IsOpen)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
ServiceBankBiz biz = ServiceBankBiz.GetBiz(ct, HttpContext);
if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType))
return StatusCode(403, new ApiNotAuthorizedResponse());
if (!ModelState.IsValid)
return BadRequest(new ApiErrorResponse(ModelState));
ServiceBank o = await biz.CreateAsync(newObject);
if (o == null)
return BadRequest(new ApiErrorResponse(biz.Errors));
else
return CreatedAtAction(nameof(ServiceBankController.GetServiceBank), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
}
// /// <summary>
// /// Migrate ServiceBank
// /// (for migration from v7 only, do not use)
// /// </summary>
// /// <param name="newObject"></param>
// /// <param name="apiVersion">From route path</param>
// /// <returns></returns>
// [HttpPost("migrate")]
// public async Task<IActionResult> MigrateServiceBank([FromBody] ServiceBank newObject, ApiVersion apiVersion)
// {
// if (!serverState.IsOpen)
// return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
// ServiceBankBiz biz = ServiceBankBiz.GetBiz(ct, HttpContext);
// if (!Authorized.HasCreateRole(HttpContext.Items, biz.BizType))
// return StatusCode(403, new ApiNotAuthorizedResponse());
// if (!ModelState.IsValid)
// return BadRequest(new ApiErrorResponse(ModelState));
// ServiceBank o = await biz.CreateAsync(newObject);
// if (o == null)
// return BadRequest(new ApiErrorResponse(biz.Errors));
// else
// return CreatedAtAction(nameof(ServiceBankController.GetServiceBank), new { id = o.Id, version = apiVersion.ToString() }, new ApiCreatedResponse(o));
// }
/// <summary>
/// Get ServiceBank
/// (This object is create / get only, there is no update or delete. Only adjustments through new entries)
/// </summary>
/// <param name="id"></param>
/// <returns>ServiceBank</returns>
[HttpGet("{id}")]
public async Task<IActionResult> GetServiceBank([FromRoute] long id)
{
if (!serverState.IsOpen)
return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
ServiceBankBiz biz = ServiceBankBiz.GetBiz(ct, HttpContext);
if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType))
return StatusCode(403, new ApiNotAuthorizedResponse());
if (!ModelState.IsValid)
return BadRequest(new ApiErrorResponse(ModelState));
var o = await biz.GetAsync(id);
if (o == null) return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
return Ok(ApiOkResponse.Response(o));
}
// /// <summary>
// /// Get ServiceBank
// /// (This object is create / get only, there is no update or delete. Only adjustments through new entries)
// /// </summary>
// /// <param name="id"></param>
// /// <returns>ServiceBank</returns>
// [HttpGet("{id}")]
// public async Task<IActionResult> GetServiceBank([FromRoute] long id)
// {
// if (!serverState.IsOpen)
// return StatusCode(503, new ApiErrorResponse(serverState.ApiErrorCode, null, serverState.Reason));
// ServiceBankBiz biz = ServiceBankBiz.GetBiz(ct, HttpContext);
// if (!Authorized.HasReadFullRole(HttpContext.Items, biz.BizType))
// return StatusCode(403, new ApiNotAuthorizedResponse());
// if (!ModelState.IsValid)
// return BadRequest(new ApiErrorResponse(ModelState));
// var o = await biz.GetAsync(id);
// if (o == null) return NotFound(new ApiErrorResponse(ApiErrorCode.NOT_FOUND));
// return Ok(ApiOkResponse.Response(o));
// }
//------------
// //------------
}//eoc
}//eons
// }//eoc
// }//eons

View File

@@ -100,13 +100,13 @@ namespace AyaNova.DataList
SqlValueColumnName = "acustomer.accountnumber"
});
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "UsesBanking",
FieldKey = "customerusesbanking",
UiFieldDataType = (int)UiFieldDataType.Bool,
SqlValueColumnName = "acustomer.usesbanking"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "UsesBanking",
// FieldKey = "customerusesbanking",
// UiFieldDataType = (int)UiFieldDataType.Bool,
// SqlValueColumnName = "acustomer.usesbanking"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{

View File

@@ -67,13 +67,13 @@ namespace AyaNova.DataList
SqlValueColumnName = "aheadoffice.accountnumber"
});
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "UsesBanking",
FieldKey = "headofficeusesbanking",
UiFieldDataType = (int)UiFieldDataType.Bool,
SqlValueColumnName = "aheadoffice.usesbanking"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "UsesBanking",
// FieldKey = "headofficeusesbanking",
// UiFieldDataType = (int)UiFieldDataType.Bool,
// SqlValueColumnName = "aheadoffice.usesbanking"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{

View File

@@ -1,168 +1,168 @@
using System.Collections.Generic;
using AyaNova.Models;
using AyaNova.Biz;
using System.Linq;
namespace AyaNova.DataList
{
internal class ServiceBankDataList : DataListProcessingBase, IDataListInternalCriteria
{
public ServiceBankDataList()
{
// using System.Collections.Generic;
// using AyaNova.Models;
// using AyaNova.Biz;
// using System.Linq;
// namespace AyaNova.DataList
// {
// internal class ServiceBankDataList : DataListProcessingBase, IDataListInternalCriteria
// {
// public ServiceBankDataList()
// {
DefaultListAType = AyaType.ServiceBank;
SQLFrom = "from aservicebank";
var RoleSet = BizRoles.GetRoleSet(DefaultListAType);
AllowedRoles = RoleSet.ReadFullRecord | RoleSet.Change;
DefaultColumns = new List<string>() {
"ServiceBankCreated", "Object", "ServiceBankCurrency", "ServiceBankCurrencyBalance", "ServiceBankIncidents",
"ServiceBankIncidentsBalance", "ServiceBankHours", "ServiceBankHoursBalance", "ServiceBankDescription"
};
DefaultSortBy = new Dictionary<string, string>() { { "ServiceBankCreated", "-" } };
FieldDefinitions = new List<DataListFieldDefinition>();
// DefaultListAType = AyaType.ServiceBank;
// SQLFrom = "from aservicebank";
// var RoleSet = BizRoles.GetRoleSet(DefaultListAType);
// AllowedRoles = RoleSet.ReadFullRecord | RoleSet.Change;
// DefaultColumns = new List<string>() {
// "ServiceBankCreated", "Object", "ServiceBankCurrency", "ServiceBankCurrencyBalance", "ServiceBankIncidents",
// "ServiceBankIncidentsBalance", "ServiceBankHours", "ServiceBankHoursBalance", "ServiceBankDescription"
// };
// DefaultSortBy = new Dictionary<string, string>() { { "ServiceBankCreated", "-" } };
// FieldDefinitions = new List<DataListFieldDefinition>();
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankSourceRootAType",
FieldKey = "ServiceBankSourceRootAType",
UiFieldDataType = (int)UiFieldDataType.Text,
SqlIdColumnName = "aservicebank.sourceid",
SqlValueColumnName = "AYGETNAME(aservicebank.sourceid, aservicebank.sourcetype)",
SqlATypeColumnName = "aservicebank.sourcetype"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankSourceRootAType",
// FieldKey = "ServiceBankSourceRootAType",
// UiFieldDataType = (int)UiFieldDataType.Text,
// SqlIdColumnName = "aservicebank.sourceid",
// SqlValueColumnName = "AYGETNAME(aservicebank.sourceid, aservicebank.sourcetype)",
// SqlATypeColumnName = "aservicebank.sourcetype"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "Object",
FieldKey = "Object",
UiFieldDataType = (int)UiFieldDataType.Text,
SqlIdColumnName = "aservicebank.objectid",
SqlValueColumnName = "AYGETNAME(aservicebank.objectid, aservicebank.aType)",
SqlATypeColumnName = "aservicebank.aType"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "Object",
// FieldKey = "Object",
// UiFieldDataType = (int)UiFieldDataType.Text,
// SqlIdColumnName = "aservicebank.objectid",
// SqlValueColumnName = "AYGETNAME(aservicebank.objectid, aservicebank.aType)",
// SqlATypeColumnName = "aservicebank.aType"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "AyaType",
FieldKey = "AyaType",
UiFieldDataType = (int)UiFieldDataType.Enum,
EnumType = AyaNova.Util.StringUtil.TrimTypeName(typeof(AyaType).ToString()),
SqlValueColumnName = "aservicebank.aType"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "AyaType",
// FieldKey = "AyaType",
// UiFieldDataType = (int)UiFieldDataType.Enum,
// EnumType = AyaNova.Util.StringUtil.TrimTypeName(typeof(AyaType).ToString()),
// SqlValueColumnName = "aservicebank.aType"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankDescription",
FieldKey = "ServiceBankDescription",
AType = (int)AyaType.ServiceBank,
UiFieldDataType = (int)UiFieldDataType.Text,
SqlIdColumnName = "aservicebank.id",
SqlValueColumnName = "aservicebank.name",
IsRowId = true
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankDescription",
// FieldKey = "ServiceBankDescription",
// AType = (int)AyaType.ServiceBank,
// UiFieldDataType = (int)UiFieldDataType.Text,
// SqlIdColumnName = "aservicebank.id",
// SqlValueColumnName = "aservicebank.name",
// IsRowId = true
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankCreated",
FieldKey = "ServiceBankCreated",
UiFieldDataType = (int)UiFieldDataType.DateTime,
SqlValueColumnName = "aservicebank.entrydate"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankCreated",
// FieldKey = "ServiceBankCreated",
// UiFieldDataType = (int)UiFieldDataType.DateTime,
// SqlValueColumnName = "aservicebank.entrydate"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankCurrency",
FieldKey = "ServiceBankCurrency",
UiFieldDataType = (int)UiFieldDataType.Currency,
SqlValueColumnName = "aservicebank.currency"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankCurrency",
// FieldKey = "ServiceBankCurrency",
// UiFieldDataType = (int)UiFieldDataType.Currency,
// SqlValueColumnName = "aservicebank.currency"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankCurrencyBalance",
FieldKey = "ServiceBankCurrencyBalance",
UiFieldDataType = (int)UiFieldDataType.Currency,
SqlValueColumnName = "aservicebank.currencybalance"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankCurrencyBalance",
// FieldKey = "ServiceBankCurrencyBalance",
// UiFieldDataType = (int)UiFieldDataType.Currency,
// SqlValueColumnName = "aservicebank.currencybalance"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankIncidents",
FieldKey = "ServiceBankIncidents",
UiFieldDataType = (int)UiFieldDataType.Decimal,
SqlValueColumnName = "aservicebank.incidents"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankIncidents",
// FieldKey = "ServiceBankIncidents",
// UiFieldDataType = (int)UiFieldDataType.Decimal,
// SqlValueColumnName = "aservicebank.incidents"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankIncidentsBalance",
FieldKey = "ServiceBankIncidentsBalance",
UiFieldDataType = (int)UiFieldDataType.Decimal,
SqlValueColumnName = "aservicebank.incidentsbalance"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankIncidentsBalance",
// FieldKey = "ServiceBankIncidentsBalance",
// UiFieldDataType = (int)UiFieldDataType.Decimal,
// SqlValueColumnName = "aservicebank.incidentsbalance"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankHours",
FieldKey = "ServiceBankHours",
UiFieldDataType = (int)UiFieldDataType.Decimal,
SqlValueColumnName = "aservicebank.hours"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankHours",
// FieldKey = "ServiceBankHours",
// UiFieldDataType = (int)UiFieldDataType.Decimal,
// SqlValueColumnName = "aservicebank.hours"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "ServiceBankHoursBalance",
FieldKey = "ServiceBankHoursBalance",
UiFieldDataType = (int)UiFieldDataType.Decimal,
SqlValueColumnName = "aservicebank.hoursbalance"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "ServiceBankHoursBalance",
// FieldKey = "ServiceBankHoursBalance",
// UiFieldDataType = (int)UiFieldDataType.Decimal,
// SqlValueColumnName = "aservicebank.hoursbalance"
// });
//META
FieldDefinitions.Add(new DataListFieldDefinition
{
FieldKey = "metaobjectid",
UiFieldDataType = (int)UiFieldDataType.InternalId,
SqlIdColumnName = "aservicebank.objectid",
SqlValueColumnName = "aservicebank.objectid",
IsMeta = true
});
// //META
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// FieldKey = "metaobjectid",
// UiFieldDataType = (int)UiFieldDataType.InternalId,
// SqlIdColumnName = "aservicebank.objectid",
// SqlValueColumnName = "aservicebank.objectid",
// IsMeta = true
// });
FieldDefinitions.Add(new DataListFieldDefinition
{
// FieldDefinitions.Add(new DataListFieldDefinition
// {
FieldKey = "metaobjecttype",
UiFieldDataType = (int)UiFieldDataType.Enum,
EnumType = AyaNova.Util.StringUtil.TrimTypeName(typeof(AyaType).ToString()),
SqlValueColumnName = "aservicebank.aType",
IsMeta = true
});
}
// FieldKey = "metaobjecttype",
// UiFieldDataType = (int)UiFieldDataType.Enum,
// EnumType = AyaNova.Util.StringUtil.TrimTypeName(typeof(AyaType).ToString()),
// SqlValueColumnName = "aservicebank.aType",
// IsMeta = true
// });
// }
public List<DataListFilterOption> DataListInternalCriteria(long currentUserId, AuthorizationRoles userRoles, string clientCriteria)
{
List<DataListFilterOption> ret = new List<DataListFilterOption>();
// public List<DataListFilterOption> DataListInternalCriteria(long currentUserId, AuthorizationRoles userRoles, string clientCriteria)
// {
// List<DataListFilterOption> ret = new List<DataListFilterOption>();
//ClientCriteria format for this list is "OBJECTID,AYATYPE"
var crit = (clientCriteria ?? "").Split(',').Select(z => z.Trim()).ToArray();
if (crit.Length > 1)
{
//OBJECTID criteria
if (crit[0] != "0")
{
DataListFilterOption FilterOption = new DataListFilterOption() { Column = "metaobjectid" };
FilterOption.Items.Add(new DataListColumnFilter() { value = crit[0], op = DataListFilterComparisonOperator.Equality });
ret.Add(FilterOption);
}
// //ClientCriteria format for this list is "OBJECTID,AYATYPE"
// var crit = (clientCriteria ?? "").Split(',').Select(z => z.Trim()).ToArray();
// if (crit.Length > 1)
// {
// //OBJECTID criteria
// if (crit[0] != "0")
// {
// DataListFilterOption FilterOption = new DataListFilterOption() { Column = "metaobjectid" };
// FilterOption.Items.Add(new DataListColumnFilter() { value = crit[0], op = DataListFilterComparisonOperator.Equality });
// ret.Add(FilterOption);
// }
//AYATYPE criteria
if (!string.IsNullOrWhiteSpace(crit[1]))
{
DataListFilterOption FilterOption = new DataListFilterOption() { Column = "metaobjecttype" };
FilterOption.Items.Add(new DataListColumnFilter() { value = crit[1], op = DataListFilterComparisonOperator.Equality });
ret.Add(FilterOption);
}
}
return ret;
}
}//eoc
}//eons
// //AYATYPE criteria
// if (!string.IsNullOrWhiteSpace(crit[1]))
// {
// DataListFilterOption FilterOption = new DataListFilterOption() { Column = "metaobjecttype" };
// FilterOption.Items.Add(new DataListColumnFilter() { value = crit[1], op = DataListFilterComparisonOperator.Equality });
// ret.Add(FilterOption);
// }
// }
// return ret;
// }
// }//eoc
// }//eons

View File

@@ -196,13 +196,13 @@ namespace AyaNova.DataList
SqlValueColumnName = "amainunit.contractexpires"
});
FieldDefinitions.Add(new DataListFieldDefinition
{
TKey = "UsesBanking",
FieldKey = "UsesBanking",
UiFieldDataType = (int)UiFieldDataType.Bool,
SqlValueColumnName = "amainunit.usesbanking"
});
// FieldDefinitions.Add(new DataListFieldDefinition
// {
// TKey = "UsesBanking",
// FieldKey = "UsesBanking",
// UiFieldDataType = (int)UiFieldDataType.Bool,
// SqlValueColumnName = "amainunit.usesbanking"
// });
FieldDefinitions.Add(new DataListFieldDefinition
{

View File

@@ -113,7 +113,7 @@ namespace AyaNova.Biz
UnitMeterReading = 53,
[CoreBizObject]
CustomerServiceRequest = 54,
ServiceBank = 55,
// ServiceBank = 55,
OpsNotificationSettings = 56,
Report = 57,
DashboardView = 58,

View File

@@ -120,8 +120,8 @@ namespace AyaNova.Biz
return await ct.TravelRate.AnyAsync(z => z.Id == id);
case AyaType.TaxCode:
return await ct.TaxCode.AnyAsync(z => z.Id == id);
case AyaType.ServiceBank:
return await ct.ServiceBank.AnyAsync(z => z.Id == id);
// case AyaType.ServiceBank:
// return await ct.ServiceBank.AnyAsync(z => z.Id == id);
case AyaType.CustomerServiceRequest:
return await ct.CustomerServiceRequest.AnyAsync(z => z.Id == id);
default:

View File

@@ -107,8 +107,8 @@ namespace AyaNova.Biz
return new TravelRateBiz(ct, userId, translationId, roles);
case AyaType.TaxCode:
return new TaxCodeBiz(ct, userId, translationId, roles);
case AyaType.ServiceBank:
return new ServiceBankBiz(ct, userId, translationId, roles);
// case AyaType.ServiceBank:
// return new ServiceBankBiz(ct, userId, translationId, roles);
case AyaType.CustomerServiceRequest:
return new CustomerServiceRequestBiz(ct, userId, translationId, roles);
case AyaType.TaskGroup:

File diff suppressed because one or more lines are too long

View File

@@ -34,7 +34,7 @@ namespace AyaNova.Biz
}
//No type / not corebiz form keys:
_formFieldKeys.Add("Contact");
_formFieldKeys.Add(AyaType.ServiceBank.ToString());
//_formFieldKeys.Add(AyaType.ServiceBank.ToString());
_formFieldKeys.Add(AyaType.WorkOrderStatus.ToString());
_formFieldKeys.Add(AyaType.WorkOrderItemStatus.ToString());
_formFieldKeys.Add(AyaType.WorkOrderItemPriority.ToString());
@@ -168,7 +168,7 @@ namespace AyaNova.Biz
l.Add(new FormField { TKey = "HeadOffice", FieldKey = "HeadOfficeId" });
l.Add(new FormField { TKey = "Contract", FieldKey = "ContractId" });
l.Add(new FormField { TKey = "ContractExpires", FieldKey = "ContractExpires" });
l.Add(new FormField { TKey = "UsesBanking", FieldKey = "UsesBanking" });
//l.Add(new FormField { TKey = "UsesBanking", FieldKey = "UsesBanking" });
l.Add(new FormField { TKey = "CustomerNotes", FieldKey = "Notes" });
l.Add(new FormField { TKey = "CustomerTechNotes", FieldKey = "TechNotes" });
l.Add(new FormField { TKey = "AlertNotes", FieldKey = "PopUpNotes" });
@@ -220,7 +220,7 @@ namespace AyaNova.Biz
l.Add(new FormField { TKey = "HeadOfficePhone5", FieldKey = "Phone5" });
l.Add(new FormField { TKey = "Contract", FieldKey = "ContractId" });
l.Add(new FormField { TKey = "ContractExpires", FieldKey = "ContractExpires" });
l.Add(new FormField { TKey = "UsesBanking", FieldKey = "UsesBanking" });
//l.Add(new FormField { TKey = "UsesBanking", FieldKey = "UsesBanking" });
l.Add(new FormField { TKey = "HeadOfficeNotes", FieldKey = "Notes" });
l.Add(new FormField { TKey = "Tags", FieldKey = "Tags" });
l.Add(new FormField { TKey = "Wiki", FieldKey = "Wiki" });
@@ -693,15 +693,15 @@ namespace AyaNova.Biz
}
#endregion
#region ServiceBank
{
List<FormField> l = new List<FormField>();
l.Add(new FormField { TKey = "ServiceBankCurrency", FieldKey = "Currency" });
l.Add(new FormField { TKey = "ServiceBankHours", FieldKey = "Hours" });
l.Add(new FormField { TKey = "ServiceBankIncidents", FieldKey = "Incidents" });
_formFields.Add(AyaType.ServiceBank.ToString(), l);
}
#endregion
// #region ServiceBank
// {
// List<FormField> l = new List<FormField>();
// l.Add(new FormField { TKey = "ServiceBankCurrency", FieldKey = "Currency" });
// l.Add(new FormField { TKey = "ServiceBankHours", FieldKey = "Hours" });
// l.Add(new FormField { TKey = "ServiceBankIncidents", FieldKey = "Incidents" });
// _formFields.Add(AyaType.ServiceBank.ToString(), l);
// }
// #endregion
#region Unit
{
@@ -712,7 +712,7 @@ namespace AyaNova.Biz
l.Add(new FormField { TKey = "UnitParentUnitID", FieldKey = "ParentUnitId" });
l.Add(new FormField { TKey = "Contract", FieldKey = "ContractId" });
l.Add(new FormField { TKey = "ContractExpires", FieldKey = "ContractExpires" });
l.Add(new FormField { TKey = "UsesBanking", FieldKey = "UsesBanking" });
//l.Add(new FormField { TKey = "UsesBanking", FieldKey = "UsesBanking" });
l.Add(new FormField { TKey = "UnitMetered", FieldKey = "Metered" });
l.Add(new FormField { TKey = "UnitBoughtHere", FieldKey = "BoughtHere" });
l.Add(new FormField { TKey = "UnitPurchaseFromID", FieldKey = "PurchasedFromVendorId" });

View File

@@ -20,7 +20,7 @@ namespace AyaNova.Biz
CopyOfCustomerNotification = 8,//*User notification of what was sent to a Customer as a notification. In other words can subscribe to any customer notifications and be sent a copy of them. Tag filter is based on Customer's tags for this one so user can choose which customer group to subscribe to this or all.
QuoteStatusChange = 9,//* Quote object, any *change* of status including from no status (new) to a specific conditional status ID value
ObjectAge = 10,//* Any object, Age (conditional on AgeValue) after creation event of any object of conditional specific AyaType and optionally conditional tags
ServiceBankDepleted = 11,//*ServiceBank object, any change to balance triggers this check, conditional on decvalue as remaining balance left to trigger this notification
//ServiceBankDepleted = 11,//*ServiceBank object, any change to balance triggers this check, conditional on decvalue as remaining balance left to trigger this notification
ReminderImminent = 12,//*Reminder object, Advance notice setting tag conditional
ScheduledOnWorkorder = 13,//*Workorder / WorkorderItemScheduledUser object, instant notification when current user is scheduled on a service workorder
ScheduledOnWorkorderImminent = 14,//*Workorder / WorkorderItemScheduledUser object, advanced (settable) notification when current user's scheduled date/time is imminent

View File

@@ -220,7 +220,7 @@ namespace AyaNova.Biz
return;
}
//New entry must have *something* to bank
//New entry must have *something* that would affect quantities
if (proposedObj.Quantity == 0)
{
AddError(ApiErrorCode.VALIDATION_REQUIRED, "Quantity");

View File

@@ -1,369 +1,369 @@
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using AyaNova.Util;
using AyaNova.Api.ControllerHelpers;
using Microsoft.Extensions.Logging;
using AyaNova.Models;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
// using System;
// using System.Threading.Tasks;
// using Microsoft.EntityFrameworkCore;
// using System.Linq;
// using AyaNova.Util;
// using AyaNova.Api.ControllerHelpers;
// using Microsoft.Extensions.Logging;
// using AyaNova.Models;
// using Newtonsoft.Json.Linq;
// using System.Collections.Generic;
namespace AyaNova.Biz
{
internal class ServiceBankBiz : BizObject, ISearchAbleObject, IReportAbleObject, IExportAbleObject, INotifiableObject
{
internal ServiceBankBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles)
{
ct = dbcontext;
UserId = currentUserId;
UserTranslationId = userTranslationId;
CurrentUserRoles = UserRoles;
BizType = AyaType.ServiceBank;
}
// namespace AyaNova.Biz
// {
// internal class ServiceBankBiz : BizObject, ISearchAbleObject, IReportAbleObject, IExportAbleObject, INotifiableObject
// {
// internal ServiceBankBiz(AyContext dbcontext, long currentUserId, long userTranslationId, AuthorizationRoles UserRoles)
// {
// ct = dbcontext;
// UserId = currentUserId;
// UserTranslationId = userTranslationId;
// CurrentUserRoles = UserRoles;
// BizType = AyaType.ServiceBank;
// }
internal static ServiceBankBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null)
{
if (httpContext != null)
return new ServiceBankBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items));
else
return new ServiceBankBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdminFull);
}
// internal static ServiceBankBiz GetBiz(AyContext ct, Microsoft.AspNetCore.Http.HttpContext httpContext = null)
// {
// if (httpContext != null)
// return new ServiceBankBiz(ct, UserIdFromContext.Id(httpContext.Items), UserTranslationIdFromContext.Id(httpContext.Items), UserRolesFromContext.Roles(httpContext.Items));
// else
// return new ServiceBankBiz(ct, 1, ServerBootConfig.AYANOVA_DEFAULT_TRANSLATION_ID, AuthorizationRoles.BizAdminFull);
// }
////////////////////////////////////////////////////////////////////////////////////////////////
//EXISTS
internal async Task<bool> ExistsAsync(long id)
{
return await ct.ServiceBank.AnyAsync(z => z.Id == id);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////
// //EXISTS
// internal async Task<bool> ExistsAsync(long id)
// {
// return await ct.ServiceBank.AnyAsync(z => z.Id == id);
// }
////////////////////////////////////////////////////////////////////////////////////////////////
//CREATE
//
internal async Task<ServiceBank> CreateAsync(dtServiceBank newDtObject)
{
using (var transaction = await ct.Database.BeginTransactionAsync())
{
//get the last record
var LastEntry = await ct.ServiceBank.OrderByDescending(m => m.EntryDate).FirstOrDefaultAsync(m => m.ObjectId == newDtObject.ObjectId && m.AType == newDtObject.AType);
ServiceBank newObject = new ServiceBank();
newObject.Name = newDtObject.Name;
newObject.EntryDate = DateTime.UtcNow;
newObject.ObjectId = newDtObject.ObjectId;
newObject.AType = newDtObject.AType;
newObject.SourceId = newDtObject.SourceId;
newObject.SourceType = newDtObject.SourceType;
newObject.Incidents = newDtObject.Incidents;
newObject.Currency = newDtObject.Currency;
newObject.Hours = newDtObject.Hours;
// ////////////////////////////////////////////////////////////////////////////////////////////////
// //CREATE
// //
// internal async Task<ServiceBank> CreateAsync(dtServiceBank newDtObject)
// {
// using (var transaction = await ct.Database.BeginTransactionAsync())
// {
// //get the last record
// var LastEntry = await ct.ServiceBank.OrderByDescending(m => m.EntryDate).FirstOrDefaultAsync(m => m.ObjectId == newDtObject.ObjectId && m.AType == newDtObject.AType);
// ServiceBank newObject = new ServiceBank();
// newObject.Name = newDtObject.Name;
// newObject.EntryDate = DateTime.UtcNow;
// newObject.ObjectId = newDtObject.ObjectId;
// newObject.AType = newDtObject.AType;
// newObject.SourceId = newDtObject.SourceId;
// newObject.SourceType = newDtObject.SourceType;
// newObject.Incidents = newDtObject.Incidents;
// newObject.Currency = newDtObject.Currency;
// newObject.Hours = newDtObject.Hours;
if (LastEntry != null)
{
newObject.LastEntryDate = LastEntry.EntryDate;
newObject.LastCurrencyBalance = LastEntry.CurrencyBalance;
newObject.LastHoursBalance = LastEntry.HoursBalance;
newObject.LastIncidentsBalance = LastEntry.IncidentsBalance;
newObject.HoursBalance = LastEntry.HoursBalance + newObject.Hours;
newObject.IncidentsBalance = LastEntry.IncidentsBalance + newObject.Incidents;
newObject.CurrencyBalance = LastEntry.CurrencyBalance + newObject.Currency;
}
else
{
newObject.HoursBalance = newObject.Hours;
newObject.IncidentsBalance = newObject.Incidents;
newObject.CurrencyBalance = newObject.Currency;
}
// if (LastEntry != null)
// {
// newObject.LastEntryDate = LastEntry.EntryDate;
// newObject.LastCurrencyBalance = LastEntry.CurrencyBalance;
// newObject.LastHoursBalance = LastEntry.HoursBalance;
// newObject.LastIncidentsBalance = LastEntry.IncidentsBalance;
// newObject.HoursBalance = LastEntry.HoursBalance + newObject.Hours;
// newObject.IncidentsBalance = LastEntry.IncidentsBalance + newObject.Incidents;
// newObject.CurrencyBalance = LastEntry.CurrencyBalance + newObject.Currency;
// }
// else
// {
// newObject.HoursBalance = newObject.Hours;
// newObject.IncidentsBalance = newObject.Incidents;
// newObject.CurrencyBalance = newObject.Currency;
// }
await ValidateAsync(newObject);
if (HasErrors)
return null;
else
{
await ct.ServiceBank.AddAsync(newObject);
await ct.SaveChangesAsync();
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
await SearchIndexAsync(newObject, true);
await transaction.CommitAsync();
await HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
return newObject;
}
}
}
// await ValidateAsync(newObject);
// if (HasErrors)
// return null;
// else
// {
// await ct.ServiceBank.AddAsync(newObject);
// await ct.SaveChangesAsync();
// await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
// await SearchIndexAsync(newObject, true);
// await transaction.CommitAsync();
// await HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
// return newObject;
// }
// }
// }
//version for v8 migration purposes only
internal async Task<ServiceBank> CreateAsync(ServiceBank newObject)
{
using (var transaction = await ct.Database.BeginTransactionAsync())
{
await ValidateAsync(newObject);
if (HasErrors)
return null;
else
{
await ct.ServiceBank.AddAsync(newObject);
await ct.SaveChangesAsync();
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
await SearchIndexAsync(newObject, true);
await transaction.CommitAsync();
await HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
return newObject;
}
}
}
// //version for v8 migration purposes only
// internal async Task<ServiceBank> CreateAsync(ServiceBank newObject)
// {
// using (var transaction = await ct.Database.BeginTransactionAsync())
// {
// await ValidateAsync(newObject);
// if (HasErrors)
// return null;
// else
// {
// await ct.ServiceBank.AddAsync(newObject);
// await ct.SaveChangesAsync();
// await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, newObject.Id, BizType, AyaEvent.Created), ct);
// await SearchIndexAsync(newObject, true);
// await transaction.CommitAsync();
// await HandlePotentialNotificationEvent(AyaEvent.Created, newObject);
// return newObject;
// }
// }
// }
////////////////////////////////////////////////////////////////////////////////////////////////
//GET
//
internal async Task<ServiceBank> GetAsync(long id, bool logTheGetEvent = true)
{
var ret = await ct.ServiceBank.AsNoTracking().SingleOrDefaultAsync(m => m.Id == id);
if (logTheGetEvent && ret != null)
await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, AyaEvent.Retrieved), ct);
return ret;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////
// //GET
// //
// internal async Task<ServiceBank> GetAsync(long id, bool logTheGetEvent = true)
// {
// var ret = await ct.ServiceBank.AsNoTracking().SingleOrDefaultAsync(m => m.Id == id);
// if (logTheGetEvent && ret != null)
// await EventLogProcessor.LogEventToDatabaseAsync(new Event(UserId, id, BizType, AyaEvent.Retrieved), ct);
// return ret;
// }
// ////////////////////////////////////////////////////////////////////////////////////////////////
// //GET LAST
// //
// internal async Task<ServiceBank> GetLastForObjectAsync(AyaType aType, long objectId)
// {
// // ////////////////////////////////////////////////////////////////////////////////////////////////
// // //GET LAST
// // //
// // internal async Task<ServiceBank> GetLastForObjectAsync(AyaType aType, long objectId)
// // {
// var ret = await ct.ServiceBank.OrderByDescending(m => m.EntryDate).SingleOrDefaultAsync(m => m.ObjectId == objectId && m.AType == aType);
// // var ret = await ct.ServiceBank.OrderByDescending(m => m.EntryDate).SingleOrDefaultAsync(m => m.ObjectId == objectId && m.AType == aType);
// return ret;
// }
// // return ret;
// // }
////////////////////////////////////////////////////////////////////////////////////////////////
//SEARCH
//
private async Task SearchIndexAsync(ServiceBank obj, bool isNew)
{
var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType);
DigestSearchText(obj, SearchParams);
if (isNew)
await Search.ProcessNewObjectKeywordsAsync(SearchParams);
else
await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////
// //SEARCH
// //
// private async Task SearchIndexAsync(ServiceBank obj, bool isNew)
// {
// var SearchParams = new Search.SearchIndexProcessObjectParameters(UserTranslationId, obj.Id, BizType);
// DigestSearchText(obj, SearchParams);
// if (isNew)
// await Search.ProcessNewObjectKeywordsAsync(SearchParams);
// else
// await Search.ProcessUpdatedObjectKeywordsAsync(SearchParams);
// }
public async Task<Search.SearchIndexProcessObjectParameters> GetSearchResultSummary(long id)
{
var obj = await GetAsync(id,false);
var SearchParams = new Search.SearchIndexProcessObjectParameters();
DigestSearchText(obj, SearchParams);
return SearchParams;
}
// public async Task<Search.SearchIndexProcessObjectParameters> GetSearchResultSummary(long id)
// {
// var obj = await GetAsync(id,false);
// var SearchParams = new Search.SearchIndexProcessObjectParameters();
// DigestSearchText(obj, SearchParams);
// return SearchParams;
// }
public void DigestSearchText(ServiceBank obj, Search.SearchIndexProcessObjectParameters searchParams)
{
if (obj != null)
searchParams.AddText(obj.Name);
}
// public void DigestSearchText(ServiceBank obj, Search.SearchIndexProcessObjectParameters searchParams)
// {
// if (obj != null)
// searchParams.AddText(obj.Name);
// }
////////////////////////////////////////////////////////////////////////////////////////////////
//VALIDATION
//
// ////////////////////////////////////////////////////////////////////////////////////////////////
// //VALIDATION
// //
private async Task ValidateAsync(ServiceBank proposedObj)
{
// private async Task ValidateAsync(ServiceBank proposedObj)
// {
//Name required
if (string.IsNullOrWhiteSpace(proposedObj.Name))
{
AddError(ApiErrorCode.VALIDATION_REQUIRED, "Name");
return;
}
// //Name required
// if (string.IsNullOrWhiteSpace(proposedObj.Name))
// {
// AddError(ApiErrorCode.VALIDATION_REQUIRED, "Name");
// return;
// }
//Object exists?
if (!await BizObjectExistsInDatabase.ExistsAsync(proposedObj.AType, proposedObj.ObjectId, ct))
{
AddError(ApiErrorCode.NOT_FOUND, "generalerror", $"Bankable source object specified doesn't exist [type:{proposedObj.AType}, id:{proposedObj.ObjectId}]");
return;
}
/*
"CONSTRAINT UNQ_ServiceBank UNIQUE (entrydate, objectid, aType, incidentsbalance, hoursbalance, currencybalance), " +
"CONSTRAINT UNQ_ServiceBank_Previous_values UNIQUE (lastentrydate, objectid, aType, lastincidentsbalance, lasthoursbalance, lastcurrencybalance), " +
"CONSTRAINT fk_ServiceBank_self FOREIGN KEY (lastentrydate, objectid, aType, lastincidentsbalance, lasthoursbalance, lastcurrencybalance) references aservicebank(entrydate, objectid, aType, incidentsbalance, hoursbalance, currencybalance), " +
"CONSTRAINT CHK_Servicebank_Valid_IncidentBalance CHECK(incidentsbalance = COALESCE(lastincidentsbalance, 0) + incidents), " +
"CONSTRAINT CHK_Servicebank_Valid_CurrencyBalance CHECK(currencybalance = COALESCE(lastcurrencybalance, 0) + currency), " +
"CONSTRAINT CHK_Servicebank_Valid_HoursBalance CHECK(hoursbalance = COALESCE(lasthoursbalance, 0) + hours), " +
"CONSTRAINT CHK_ServiceBank_Valid_Dates_Sequence CHECK(lastentrydate < entrydate), " +
"CONSTRAINT CHK_ServiceBank_Valid_Previous_Columns CHECK((lastentrydate IS NULL AND lastincidentsbalance IS NULL AND lastcurrencybalance IS NULL AND lasthoursbalance IS NULL) OR (lastentrydate IS NOT NULL AND lastincidentsbalance IS NOT NULL AND lastcurrencybalance IS NOT NULL AND lasthoursbalance IS NOT NULL)) "+
*/
// //Object exists?
// if (!await BizObjectExistsInDatabase.ExistsAsync(proposedObj.AType, proposedObj.ObjectId, ct))
// {
// AddError(ApiErrorCode.NOT_FOUND, "generalerror", $"Bankable source object specified doesn't exist [type:{proposedObj.AType}, id:{proposedObj.ObjectId}]");
// return;
// }
// /*
// "CONSTRAINT UNQ_ServiceBank UNIQUE (entrydate, objectid, aType, incidentsbalance, hoursbalance, currencybalance), " +
// "CONSTRAINT UNQ_ServiceBank_Previous_values UNIQUE (lastentrydate, objectid, aType, lastincidentsbalance, lasthoursbalance, lastcurrencybalance), " +
// "CONSTRAINT fk_ServiceBank_self FOREIGN KEY (lastentrydate, objectid, aType, lastincidentsbalance, lasthoursbalance, lastcurrencybalance) references aservicebank(entrydate, objectid, aType, incidentsbalance, hoursbalance, currencybalance), " +
// "CONSTRAINT CHK_Servicebank_Valid_IncidentBalance CHECK(incidentsbalance = COALESCE(lastincidentsbalance, 0) + incidents), " +
// "CONSTRAINT CHK_Servicebank_Valid_CurrencyBalance CHECK(currencybalance = COALESCE(lastcurrencybalance, 0) + currency), " +
// "CONSTRAINT CHK_Servicebank_Valid_HoursBalance CHECK(hoursbalance = COALESCE(lasthoursbalance, 0) + hours), " +
// "CONSTRAINT CHK_ServiceBank_Valid_Dates_Sequence CHECK(lastentrydate < entrydate), " +
// "CONSTRAINT CHK_ServiceBank_Valid_Previous_Columns CHECK((lastentrydate IS NULL AND lastincidentsbalance IS NULL AND lastcurrencybalance IS NULL AND lasthoursbalance IS NULL) OR (lastentrydate IS NOT NULL AND lastincidentsbalance IS NOT NULL AND lastcurrencybalance IS NOT NULL AND lasthoursbalance IS NOT NULL)) "+
// */
//New entry must have *something* to bank
if (proposedObj.Incidents == 0 && proposedObj.Hours == 0 && proposedObj.Currency == 0)
{
AddError(ApiErrorCode.INVALID_OPERATION, null, "Nothing to bank");
return;
}
// //New entry must have *something* to bank
// if (proposedObj.Incidents == 0 && proposedObj.Hours == 0 && proposedObj.Currency == 0)
// {
// AddError(ApiErrorCode.INVALID_OPERATION, null, "Nothing to bank");
// return;
// }
//values must add up
if (proposedObj.IncidentsBalance != (proposedObj.Incidents + (proposedObj.LastIncidentsBalance ?? 0)))
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", await Translate("ServiceBankIncidentsBalance"));
return;
}
if (proposedObj.CurrencyBalance != (proposedObj.Currency + (proposedObj.LastCurrencyBalance ?? 0)))
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", await Translate("ServiceBankCurrencyBalance"));
return;
}
if (proposedObj.HoursBalance != (proposedObj.Hours + (proposedObj.LastHoursBalance ?? 0)))
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", await Translate("ServiceBankHoursBalance"));
return;
}
// //values must add up
// if (proposedObj.IncidentsBalance != (proposedObj.Incidents + (proposedObj.LastIncidentsBalance ?? 0)))
// {
// AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", await Translate("ServiceBankIncidentsBalance"));
// return;
// }
// if (proposedObj.CurrencyBalance != (proposedObj.Currency + (proposedObj.LastCurrencyBalance ?? 0)))
// {
// AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", await Translate("ServiceBankCurrencyBalance"));
// return;
// }
// if (proposedObj.HoursBalance != (proposedObj.Hours + (proposedObj.LastHoursBalance ?? 0)))
// {
// AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", await Translate("ServiceBankHoursBalance"));
// return;
// }
//date is newer than last entry date?
if (proposedObj.LastEntryDate != null && proposedObj.LastEntryDate > proposedObj.EntryDate)
{
AddError(ApiErrorCode.VALIDATION_STARTDATE_AFTER_ENDDATE, "generalerror", "LastEntryDate is newer than EntryDate");
return;
}
// //date is newer than last entry date?
// if (proposedObj.LastEntryDate != null && proposedObj.LastEntryDate > proposedObj.EntryDate)
// {
// AddError(ApiErrorCode.VALIDATION_STARTDATE_AFTER_ENDDATE, "generalerror", "LastEntryDate is newer than EntryDate");
// return;
// }
//valid previous columns?
//either they're all null or none of them are null
// //valid previous columns?
// //either they're all null or none of them are null
//fix and re-test
if (!((proposedObj.LastEntryDate == null
&& proposedObj.LastCurrencyBalance == null
&& proposedObj.LastHoursBalance == null
&& proposedObj.LastIncidentsBalance == null) ||
(proposedObj.LastEntryDate != null
&& proposedObj.LastCurrencyBalance != null
&& proposedObj.LastHoursBalance != null
&& proposedObj.LastIncidentsBalance != null)
))
{
AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", "Last* entries must be all empty (opening entry) or none of them empty (any later entry)");
return;
}
// //fix and re-test
// if (!((proposedObj.LastEntryDate == null
// && proposedObj.LastCurrencyBalance == null
// && proposedObj.LastHoursBalance == null
// && proposedObj.LastIncidentsBalance == null) ||
// (proposedObj.LastEntryDate != null
// && proposedObj.LastCurrencyBalance != null
// && proposedObj.LastHoursBalance != null
// && proposedObj.LastIncidentsBalance != null)
// ))
// {
// AddError(ApiErrorCode.VALIDATION_INVALID_VALUE, "generalerror", "Last* entries must be all empty (opening entry) or none of them empty (any later entry)");
// return;
// }
//Any form customizations to validate?
var FormCustomization = await ct.FormCustom.AsNoTracking().SingleOrDefaultAsync(x => x.FormKey == AyaType.ServiceBank.ToString());
if (FormCustomization != null)
{
//Yeppers, do the validation, there are two, the custom fields and the regular fields that might be set to required
// //Any form customizations to validate?
// var FormCustomization = await ct.FormCustom.AsNoTracking().SingleOrDefaultAsync(x => x.FormKey == AyaType.ServiceBank.ToString());
// if (FormCustomization != null)
// {
// //Yeppers, do the validation, there are two, the custom fields and the regular fields that might be set to required
//validate users choices for required non custom fields
RequiredFieldsValidator.Validate(this, FormCustomization, proposedObj);
// //validate users choices for required non custom fields
// RequiredFieldsValidator.Validate(this, FormCustomization, proposedObj);
}
// }
}
// }
////////////////////////////////////////////////////////////////////////////////////////////////
//REPORTING
//
public async Task<JArray> GetReportData(long[] idList)
{
JArray ReportData = new JArray();
while (idList.Any())
{
var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE);
idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray();
//query for this batch, comes back in db natural order unfortunately
var batchResults = await ct.ServiceBank.Where(z => batch.Contains(z.Id)).ToArrayAsync();
//order the results back into original
var orderedList = from id in batch join z in batchResults on id equals z.Id select z;
foreach (ServiceBank w in orderedList)
{
var jo = JObject.FromObject(w);
if (!JsonUtil.JTokenIsNullOrEmpty(jo["CustomFields"]))
jo["CustomFields"] = JObject.Parse((string)jo["CustomFields"]);
ReportData.Add(jo);
}
}
return ReportData;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////
// //REPORTING
// //
// public async Task<JArray> GetReportData(long[] idList)
// {
// JArray ReportData = new JArray();
// while (idList.Any())
// {
// var batch = idList.Take(IReportAbleObject.REPORT_DATA_BATCH_SIZE);
// idList = idList.Skip(IReportAbleObject.REPORT_DATA_BATCH_SIZE).ToArray();
// //query for this batch, comes back in db natural order unfortunately
// var batchResults = await ct.ServiceBank.Where(z => batch.Contains(z.Id)).ToArrayAsync();
// //order the results back into original
// var orderedList = from id in batch join z in batchResults on id equals z.Id select z;
// foreach (ServiceBank w in orderedList)
// {
// var jo = JObject.FromObject(w);
// if (!JsonUtil.JTokenIsNullOrEmpty(jo["CustomFields"]))
// jo["CustomFields"] = JObject.Parse((string)jo["CustomFields"]);
// ReportData.Add(jo);
// }
// }
// return ReportData;
// }
////////////////////////////////////////////////////////////////////////////////////////////////
// IMPORT EXPORT
//
// ////////////////////////////////////////////////////////////////////////////////////////////////
// // IMPORT EXPORT
// //
public async Task<JArray> GetExportData(long[] idList)
{
//for now just re-use the report data code
//this may turn out to be the pattern for most biz object types but keeping it seperate allows for custom usage from time to time
return await GetReportData(idList);
}
// public async Task<JArray> GetExportData(long[] idList)
// {
// //for now just re-use the report data code
// //this may turn out to be the pattern for most biz object types but keeping it seperate allows for custom usage from time to time
// return await GetReportData(idList);
// }
////////////////////////////////////////////////////////////////////////////////////////////////
// NOTIFICATION PROCESSING
//
public async Task HandlePotentialNotificationEvent(AyaEvent ayaEvent, ICoreBizObjectModel proposedObj, ICoreBizObjectModel currentObj = null)
{
ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger<ServiceBankBiz>();
if (ServerBootConfig.SEEDING) return;
log.LogDebug($"HandlePotentialNotificationEvent processing: [AyaType:{this.BizType}, AyaEvent:{ayaEvent}]");
// ////////////////////////////////////////////////////////////////////////////////////////////////
// // NOTIFICATION PROCESSING
// //
// public async Task HandlePotentialNotificationEvent(AyaEvent ayaEvent, ICoreBizObjectModel proposedObj, ICoreBizObjectModel currentObj = null)
// {
// ILogger log = AyaNova.Util.ApplicationLogging.CreateLogger<ServiceBankBiz>();
// if (ServerBootConfig.SEEDING) return;
// log.LogDebug($"HandlePotentialNotificationEvent processing: [AyaType:{this.BizType}, AyaEvent:{ayaEvent}]");
bool isNew = currentObj == null;
// bool isNew = currentObj == null;
//STANDARD EVENTS FOR ALL OBJECTS
await NotifyEventHelper.ProcessStandardObjectEvents(ayaEvent, proposedObj, ct);
// //STANDARD EVENTS FOR ALL OBJECTS
// await NotifyEventHelper.ProcessStandardObjectEvents(ayaEvent, proposedObj, ct);
//SPECIFIC EVENTS FOR THIS OBJECT
var o = (ServiceBank)proposedObj;
// //SPECIFIC EVENTS FOR THIS OBJECT
// var o = (ServiceBank)proposedObj;
//SERVICE BANK DEPLETED
{
var subs = await ct.NotifySubscription.Where(z => z.EventType == NotifyEventType.ServiceBankDepleted).ToListAsync();
string SourceName = string.Empty;
if (subs.Count > 0)
SourceName = BizObjectNameFetcherDirect.Name(o.AType, o.ObjectId, ct);
// //SERVICE BANK DEPLETED
// {
// var subs = await ct.NotifySubscription.Where(z => z.EventType == NotifyEventType.ServiceBankDepleted).ToListAsync();
// string SourceName = string.Empty;
// if (subs.Count > 0)
// SourceName = BizObjectNameFetcherDirect.Name(o.AType, o.ObjectId, ct);
foreach (var sub in subs)
{
//not for inactive users
if (!await UserBiz.UserIsActive(sub.UserId)) continue;
// foreach (var sub in subs)
// {
// //not for inactive users
// if (!await UserBiz.UserIsActive(sub.UserId)) continue;
//Has any of the balances changed and is that changed balance within this users selected threshold?
//decvalue here refers to the balance left
if (
(o.LastCurrencyBalance != null && o.CurrencyBalance != o.LastCurrencyBalance && o.CurrencyBalance <= sub.DecValue)
|| (o.LastHoursBalance != null && o.HoursBalance != o.LastHoursBalance && o.HoursBalance <= sub.DecValue)
|| (o.LastIncidentsBalance != null && o.IncidentsBalance != o.LastIncidentsBalance && o.IncidentsBalance <= sub.DecValue)
)
{
// //Has any of the balances changed and is that changed balance within this users selected threshold?
// //decvalue here refers to the balance left
// if (
// (o.LastCurrencyBalance != null && o.CurrencyBalance != o.LastCurrencyBalance && o.CurrencyBalance <= sub.DecValue)
// || (o.LastHoursBalance != null && o.HoursBalance != o.LastHoursBalance && o.HoursBalance <= sub.DecValue)
// || (o.LastIncidentsBalance != null && o.IncidentsBalance != o.LastIncidentsBalance && o.IncidentsBalance <= sub.DecValue)
// )
// {
NotifyEvent n = new NotifyEvent()
{
EventType = NotifyEventType.ServiceBankDepleted,
UserId = sub.UserId,
AyaType = o.AType,
ObjectId = o.ObjectId,
NotifySubscriptionId = sub.Id,
Name = SourceName
};
await ct.NotifyEvent.AddAsync(n);
log.LogDebug($"Adding NotifyEvent: [{n.ToString()}]");
await ct.SaveChangesAsync();
}
}
}
// NotifyEvent n = new NotifyEvent()
// {
// EventType = NotifyEventType.ServiceBankDepleted,
// UserId = sub.UserId,
// AyaType = o.AType,
// ObjectId = o.ObjectId,
// NotifySubscriptionId = sub.Id,
// Name = SourceName
// };
// await ct.NotifyEvent.AddAsync(n);
// log.LogDebug($"Adding NotifyEvent: [{n.ToString()}]");
// await ct.SaveChangesAsync();
// }
// }
// }
}//end of process notifications
// }//end of process notifications
/////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////
}//eoc
// }//eoc
}//eons
// }//eons

View File

@@ -99,7 +99,7 @@ namespace AyaNova.Models
public virtual DbSet<Logo> Logo { get; set; }
public virtual DbSet<Report> Report { get; set; }
public virtual DbSet<DashboardView> DashboardView { get; set; }
public virtual DbSet<ServiceBank> ServiceBank { get; set; }
// public virtual DbSet<ServiceBank> ServiceBank { get; set; }
public virtual DbSet<ViewRestockRequired> ViewRestockRequired { get; set; }

View File

@@ -34,7 +34,7 @@ namespace AyaNova.Models
public string HeadOfficeViz { get; set; }
public string TechNotes { get; set; }
public string AccountNumber { get; set; }
public bool UsesBanking { get; set; }
//public bool UsesBanking { get; set; }
public long? ContractId { get; set; }
[NotMapped]
public string ContractViz { get; set; }
@@ -67,7 +67,7 @@ namespace AyaNova.Models
{
Tags = new List<string>();
BillHeadOffice = false;
UsesBanking = false;
//UsesBanking = false;
}
[NotMapped, JsonIgnore]

View File

@@ -27,7 +27,7 @@ namespace AyaNova.Models
public string WebAddress { get; set; }
public string AccountNumber { get; set; }
public bool UsesBanking { get; set; }
//public bool UsesBanking { get; set; }
public long? ContractId { get; set; }
[NotMapped]
public string ContractViz { get; set; }
@@ -58,7 +58,7 @@ namespace AyaNova.Models
public HeadOffice()
{
Tags = new List<string>();
UsesBanking = false;
//UsesBanking = false;
}
[NotMapped, JsonIgnore]

View File

@@ -1,109 +1,109 @@
using System;
using AyaNova.Biz;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;
// using System;
// using AyaNova.Biz;
// using System.ComponentModel.DataAnnotations;
// using System.ComponentModel.DataAnnotations.Schema;
// using Newtonsoft.Json;
namespace AyaNova.Models
{
//SERVICEBANK LEDGER
// namespace AyaNova.Models
// {
// //SERVICEBANK LEDGER
//NOTE: following pattern outlined here:
//https://dba.stackexchange.com/a/19368
// //NOTE: following pattern outlined here:
// //https://dba.stackexchange.com/a/19368
public class ServiceBank : ICoreBizObjectModel
{
public long Id { get; set; }
public uint Concurrency { get; set; }
// public class ServiceBank : ICoreBizObjectModel
// {
// public long Id { get; set; }
// public uint Concurrency { get; set; }
[Required]
public string Name { get; set; }
[Required]
public DateTime EntryDate { get; set; }
public DateTime? LastEntryDate { get; set; }
[Required]
public long ObjectId { get; set; }
[Required]
public AyaType AType { get; set; }
[Required]
public long SourceId { get; set; }
[Required]
public AyaType SourceType { get; set; }
[Required]
public decimal Incidents { get; set; }
[Required]
public decimal IncidentsBalance { get; set; }
public decimal? LastIncidentsBalance { get; set; }
[Required]
public decimal Currency { get; set; }
[Required]
public decimal CurrencyBalance { get; set; }
public decimal? LastCurrencyBalance { get; set; }
[Required]
public decimal Hours { get; set; }
[Required]
public decimal HoursBalance { get; set; }
public decimal? LastHoursBalance { get; set; }
// [Required]
// public string Name { get; set; }
// [Required]
// public DateTime EntryDate { get; set; }
// public DateTime? LastEntryDate { get; set; }
// [Required]
// public long ObjectId { get; set; }
// [Required]
// public AyaType AType { get; set; }
// [Required]
// public long SourceId { get; set; }
// [Required]
// public AyaType SourceType { get; set; }
// [Required]
// public decimal Incidents { get; set; }
// [Required]
// public decimal IncidentsBalance { get; set; }
// public decimal? LastIncidentsBalance { get; set; }
// [Required]
// public decimal Currency { get; set; }
// [Required]
// public decimal CurrencyBalance { get; set; }
// public decimal? LastCurrencyBalance { get; set; }
// [Required]
// public decimal Hours { get; set; }
// [Required]
// public decimal HoursBalance { get; set; }
// public decimal? LastHoursBalance { get; set; }
public ServiceBank()
{
EntryDate = DateTime.UtcNow;
}
// public ServiceBank()
// {
// EntryDate = DateTime.UtcNow;
// }
[NotMapped, JsonIgnore]
public AyaType AyaType { get => AyaType.ServiceBank; }
// [NotMapped, JsonIgnore]
// public AyaType AyaType { get => AyaType.ServiceBank; }
}//eoc
// }//eoc
//Data transfer version used by UI to make new entry or consume banked time
//this way the client doesn't need to bother with balances or last entries and such
public class dtServiceBank
{
public long Id { get; set; }
public uint Concurrency { get; set; }
// //Data transfer version used by UI to make new entry or consume banked time
// //this way the client doesn't need to bother with balances or last entries and such
// public class dtServiceBank
// {
// public long Id { get; set; }
// public uint Concurrency { get; set; }
[Required]
public string Name { get; set; }
[Required]
public long ObjectId { get; set; }
[Required]
public AyaType AType { get; set; }
[Required]
public long SourceId { get; set; }
[Required]
public AyaType SourceType { get; set; }
[Required]
public decimal Incidents { get; set; }
[Required]
public decimal Currency { get; set; }
[Required]
public decimal Hours { get; set; }
// [Required]
// public string Name { get; set; }
// [Required]
// public long ObjectId { get; set; }
// [Required]
// public AyaType AType { get; set; }
// [Required]
// public long SourceId { get; set; }
// [Required]
// public AyaType SourceType { get; set; }
// [Required]
// public decimal Incidents { get; set; }
// [Required]
// public decimal Currency { get; set; }
// [Required]
// public decimal Hours { get; set; }
}//eoc
// }//eoc
}//eons
/*
CREATE TABLE [dbo].[ASERVICEBANK](
[AID] [uniqueidentifier] NOT NULL,
[ACREATED] [datetime] NOT NULL,//displays as "Entered" in v7 ui
[ACREATOR] [uniqueidentifier] NOT NULL,
[ADESCRIPTION] [nvarchar](255) NULL,
[ASOURCEROOTOBJECTTYPE] [smallint] NOT NULL,
[AEFFECTIVEDATE] [datetime] NULL,//docs for v7 say for what have you purposes, not relevant, for v8 IMPORT AS transactiondat
[AINCIDENTS] [decimal](19, 5) NULL,
[AINCIDENTSBALANCE] [decimal](19, 5) NULL,
[ACURRENCY] [decimal](19, 5) NULL,
[ACURRENCYBALANCE] [decimal](19, 5) NULL,
[AHOURS] [decimal](19, 5) NULL,
[AHOURSBALANCE] [decimal](19, 5) NULL,
[AAPPLIESTOROOTOBJECTID] [uniqueidentifier] NOT NULL,
[AAPPLIESTOROOTOBJECTTYPE] [smallint] NOT NULL,
[ASOURCEROOTOBJECTID] [uniqueidentifier] NULL,
*/
// }//eons
// /*
// CREATE TABLE [dbo].[ASERVICEBANK](
// [AID] [uniqueidentifier] NOT NULL,
// [ACREATED] [datetime] NOT NULL,//displays as "Entered" in v7 ui
// [ACREATOR] [uniqueidentifier] NOT NULL,
// [ADESCRIPTION] [nvarchar](255) NULL,
// [ASOURCEROOTOBJECTTYPE] [smallint] NOT NULL,
// [AEFFECTIVEDATE] [datetime] NULL,//docs for v7 say for what have you purposes, not relevant, for v8 IMPORT AS transactiondat
// [AINCIDENTS] [decimal](19, 5) NULL,
// [AINCIDENTSBALANCE] [decimal](19, 5) NULL,
// [ACURRENCY] [decimal](19, 5) NULL,
// [ACURRENCYBALANCE] [decimal](19, 5) NULL,
// [AHOURS] [decimal](19, 5) NULL,
// [AHOURSBALANCE] [decimal](19, 5) NULL,
// [AAPPLIESTOROOTOBJECTID] [uniqueidentifier] NOT NULL,
// [AAPPLIESTOROOTOBJECTTYPE] [smallint] NOT NULL,
// [ASOURCEROOTOBJECTID] [uniqueidentifier] NULL,
// */

View File

@@ -47,7 +47,7 @@ namespace AyaNova.Models
public bool OverrideModelWarranty { get; set; }
public int? WarrantyLength { get; set; }
public string WarrantyTerms { get; set; }
public bool UsesBanking { get; set; }
// public bool UsesBanking { get; set; }
public long? ContractId { get; set; }
[NotMapped]
public string ContractViz { get; set; }

View File

@@ -23,7 +23,7 @@ namespace AyaNova.Models
public string ServiceDetails { get; set; }
public decimal ServiceRateQuantity { get; set; }
public decimal NoChargeQuantity { get; set; }
public long? ServiceBankId { get; set; }
//public long? ServiceBankId { get; set; }
public long? TaxCodeSaleId { get; set; }
[NotMapped]
public string TaxCodeSaleViz { get; set; }

View File

@@ -22,7 +22,7 @@ namespace AyaNova.Models
public string TravelDetails { get; set; }
public decimal TravelRateQuantity { get; set; }
public decimal NoChargeQuantity { get; set; }
public long? ServiceBankId { get; set; }
//public long? ServiceBankId { get; set; }
public long? TaxCodeSaleId { get; set; }
[NotMapped]
public string TaxCodeSaleViz { get; set; }

View File

@@ -22,16 +22,16 @@ namespace AyaNova.Util
//!!!!WARNING: BE SURE TO UPDATE THE DbUtil::EmptyBizDataFromDatabaseForSeedingOrImporting WHEN NEW TABLES ADDED!!!!
private const int DESIRED_SCHEMA_LEVEL = 1;
internal const long EXPECTED_COLUMN_COUNT = 947;
internal const long EXPECTED_INDEX_COUNT = 141;
internal const long EXPECTED_CHECK_CONSTRAINTS = 433;
internal const long EXPECTED_FOREIGN_KEY_CONSTRAINTS = 119;
internal const long EXPECTED_COLUMN_COUNT = 925;
internal const long EXPECTED_INDEX_COUNT = 137;
internal const long EXPECTED_CHECK_CONSTRAINTS = 415;
internal const long EXPECTED_FOREIGN_KEY_CONSTRAINTS = 116;
internal const long EXPECTED_VIEWS = 6;
internal const long EXPECTED_ROUTINES = 2;
//!!!!WARNING: BE SURE TO UPDATE THE DbUtil::EmptyBizDataFromDatabaseForSeedingOrImporting WHEN NEW TABLES ADDED!!!!
///////////////////////////////////////////////////////////////// C947:I141:CC433:FC119:V6:R2
///////////////////////////////////////////////////////////////// C925:I137:CC415:FC116:V6:R2
/*
@@ -406,7 +406,6 @@ BEGIN
when 52 then aytable = 'areminder';
when 53 then return 'LT:UnitMeterReading';
when 54 then aytable = 'acustomerservicerequest';
when 55 then aytable = 'aservicebank';
when 56 then return 'LT:OpsNotificationSettings';
when 57 then aytable = 'areport';
when 58 then return 'LT:DashBoardView';
@@ -541,23 +540,23 @@ $BODY$ LANGUAGE PLPGSQL STABLE");
await ExecQueryAsync("CREATE INDEX idx_areview_duedate ON areview (duedate);");
await ExecQueryAsync("CREATE INDEX idx_areview_completeddate ON areview (completeddate);");
//SERVICE BANK
//Note: I'm allowing negative balances so this code differs slightly from the example it was drawn from https://dba.stackexchange.com/a/19368
await ExecQueryAsync("CREATE TABLE aservicebank (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL, "
+ "entrydate TIMESTAMP NOT NULL, lastentrydate TIMESTAMP NULL, atype INTEGER NOT NULL, objectid BIGINT NOT NULL, sourcetype INTEGER NOT NULL, sourceid BIGINT NOT NULL, "
+ "incidents DECIMAL(19,5) NOT NULL, incidentsbalance DECIMAL(19,5) NOT NULL, lastincidentsbalance DECIMAL(19,5) NULL, "
+ "currency DECIMAL(38,18) NOT NULL, currencybalance DECIMAL(38,18) NOT NULL, lastcurrencybalance DECIMAL(38,18) NULL, "
+ "hours DECIMAL(19,5) NOT NULL, hoursbalance DECIMAL(19,5) NOT NULL, lasthoursbalance DECIMAL(19,5) NULL, "
+ "CONSTRAINT unq_servicebank UNIQUE (entrydate, objectid, atype, incidentsbalance, hoursbalance, currencybalance), "
+ "CONSTRAINT unq_servicebank_previous_values UNIQUE (lastentrydate, objectid, atype, lastincidentsbalance, lasthoursbalance, lastcurrencybalance), "
+ "CONSTRAINT fk_servicebank_self FOREIGN KEY (lastentrydate, objectid, atype, lastincidentsbalance, lasthoursbalance, lastcurrencybalance) REFERENCES aservicebank(entrydate, objectid, atype, incidentsbalance, hoursbalance, currencybalance), "
+ "CONSTRAINT chk_servicebank_valid_incidentbalance CHECK(incidentsbalance = COALESCE(lastincidentsbalance, 0) + incidents), "
+ "CONSTRAINT chk_servicebank_valid_currencybalance CHECK(currencybalance = COALESCE(lastcurrencybalance, 0) + currency), "
+ "CONSTRAINT chk_servicebank_valid_hoursbalance CHECK(hoursbalance = COALESCE(lasthoursbalance, 0) + hours), "
+ "CONSTRAINT chk_servicebank_valid_dates_sequence CHECK(lastentrydate < entrydate), "
+ "CONSTRAINT chk_servicebank_valid_previous_columns CHECK((lastentrydate IS NULL AND lastincidentsbalance IS NULL AND lastcurrencybalance IS NULL AND lasthoursbalance IS NULL) OR (lastentrydate IS NOT NULL AND lastincidentsbalance IS NOT NULL AND lastcurrencybalance IS NOT NULL AND lasthoursbalance IS NOT NULL)) "
+ " )");
await ExecQueryAsync("CREATE INDEX idx_aservicebank_objectid_atype ON aservicebank (objectid, atype );");
// //SERVICE BANK
// //Note: I'm allowing negative balances so this code differs slightly from the example it was drawn from https://dba.stackexchange.com/a/19368
// await ExecQueryAsync("CREATE TABLE aservicebank (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL, "
// + "entrydate TIMESTAMP NOT NULL, lastentrydate TIMESTAMP NULL, atype INTEGER NOT NULL, objectid BIGINT NOT NULL, sourcetype INTEGER NOT NULL, sourceid BIGINT NOT NULL, "
// + "incidents DECIMAL(19,5) NOT NULL, incidentsbalance DECIMAL(19,5) NOT NULL, lastincidentsbalance DECIMAL(19,5) NULL, "
// + "currency DECIMAL(38,18) NOT NULL, currencybalance DECIMAL(38,18) NOT NULL, lastcurrencybalance DECIMAL(38,18) NULL, "
// + "hours DECIMAL(19,5) NOT NULL, hoursbalance DECIMAL(19,5) NOT NULL, lasthoursbalance DECIMAL(19,5) NULL, "
// + "CONSTRAINT unq_servicebank UNIQUE (entrydate, objectid, atype, incidentsbalance, hoursbalance, currencybalance), "
// + "CONSTRAINT unq_servicebank_previous_values UNIQUE (lastentrydate, objectid, atype, lastincidentsbalance, lasthoursbalance, lastcurrencybalance), "
// + "CONSTRAINT fk_servicebank_self FOREIGN KEY (lastentrydate, objectid, atype, lastincidentsbalance, lasthoursbalance, lastcurrencybalance) REFERENCES aservicebank(entrydate, objectid, atype, incidentsbalance, hoursbalance, currencybalance), "
// + "CONSTRAINT chk_servicebank_valid_incidentbalance CHECK(incidentsbalance = COALESCE(lastincidentsbalance, 0) + incidents), "
// + "CONSTRAINT chk_servicebank_valid_currencybalance CHECK(currencybalance = COALESCE(lastcurrencybalance, 0) + currency), "
// + "CONSTRAINT chk_servicebank_valid_hoursbalance CHECK(hoursbalance = COALESCE(lasthoursbalance, 0) + hours), "
// + "CONSTRAINT chk_servicebank_valid_dates_sequence CHECK(lastentrydate < entrydate), "
// + "CONSTRAINT chk_servicebank_valid_previous_columns CHECK((lastentrydate IS NULL AND lastincidentsbalance IS NULL AND lastcurrencybalance IS NULL AND lasthoursbalance IS NULL) OR (lastentrydate IS NOT NULL AND lastincidentsbalance IS NOT NULL AND lastcurrencybalance IS NOT NULL AND lasthoursbalance IS NOT NULL)) "
// + " )");
// await ExecQueryAsync("CREATE INDEX idx_aservicebank_objectid_atype ON aservicebank (objectid, atype );");
//CONTRACT
await ExecQueryAsync("CREATE TABLE acontract (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL UNIQUE, active BOOL NOT NULL, "
@@ -570,7 +569,7 @@ $BODY$ LANGUAGE PLPGSQL STABLE");
//CUSTOMER
await ExecQueryAsync("CREATE TABLE acustomer (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL UNIQUE, active BOOL NOT NULL, "
+ "notes TEXT, wiki TEXT, customfields TEXT, tags VARCHAR(255) ARRAY, "
+ "webaddress TEXT, popupnotes TEXT, billheadoffice BOOL, technotes TEXT, accountnumber TEXT, usesbanking BOOL, contractexpires TIMESTAMP NULL, contractid BIGINT NULL REFERENCES acontract(id), "
+ "webaddress TEXT, popupnotes TEXT, billheadoffice BOOL, technotes TEXT, accountnumber TEXT, contractexpires TIMESTAMP NULL, contractid BIGINT NULL REFERENCES acontract(id), "
+ "phone1 TEXT, phone2 TEXT, phone3 TEXT, phone4 TEXT, phone5 TEXT, emailaddress TEXT, "
+ "postaddress TEXT, postcity TEXT, postregion TEXT, postcountry TEXT, postcode TEXT, address TEXT, city TEXT, region TEXT, country TEXT, latitude DECIMAL(9,6), longitude DECIMAL(9,6), "
+ "CONSTRAINT chk_contract_valid CHECK((contractid IS NULL) OR (contractid IS NOT NULL AND contractexpires IS NOT NULL)) "
@@ -607,7 +606,7 @@ $BODY$ LANGUAGE PLPGSQL STABLE");
//HEADOFFICE
await ExecQueryAsync("CREATE TABLE aheadoffice (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name TEXT NOT NULL UNIQUE, active BOOL NOT NULL, "
+ "notes TEXT, wiki TEXT, customfields TEXT, tags VARCHAR(255) ARRAY,"
+ "webaddress TEXT, accountnumber TEXT, usesbanking BOOL, contractexpires TIMESTAMP NULL, contractid BIGINT NULL REFERENCES acontract(id), "
+ "webaddress TEXT, accountnumber TEXT, contractexpires TIMESTAMP NULL, contractid BIGINT NULL REFERENCES acontract(id), "
+ "phone1 TEXT, phone2 TEXT, phone3 TEXT, phone4 TEXT, phone5 TEXT, emailaddress TEXT, "
+ "postaddress TEXT, postcity TEXT, postregion TEXT, postcountry TEXT, postcode TEXT, address TEXT, city TEXT, region TEXT, country TEXT, latitude DECIMAL(9,6), longitude DECIMAL(9,6), "
+ "CONSTRAINT chk_contract_valid CHECK((contractid IS NULL) OR (contractid IS NOT NULL AND contractexpires IS NOT NULL)) "
@@ -716,7 +715,7 @@ $BODY$ LANGUAGE PLPGSQL STABLE");
+ "unitmodelid BIGINT NULL REFERENCES aunitmodel(id), unithasownaddress BOOL, boughthere BOOL, purchasedfromvendorid BIGINT NULL REFERENCES avendor(id), "
+ "receipt TEXT NULL, purchaseddate TIMESTAMP NULL, description TEXT NULL, replacedbyunitid BIGINT NULL REFERENCES aunit(id), "
+ "overridemodelwarranty BOOL, warrantylength INTEGER NULL, warrantyterms TEXT NULL, contractid BIGINT NULL REFERENCES acontract, "
+ "contractexpires TIMESTAMP NULL, usesbanking BOOL, metered BOOL, lifetimewarranty BOOL, "
+ "contractexpires TIMESTAMP NULL, metered BOOL, lifetimewarranty BOOL, "
+ "text1 TEXT NULL, text2 TEXT NULL, text3 TEXT NULL, text4 TEXT NULL, address TEXT NULL, city TEXT NULL, region TEXT NULL, country TEXT NULL, latitude DECIMAL(9,6) NULL, longitude DECIMAL(9,6) NULL, "
+ "CONSTRAINT unq_unitserialmodelid UNIQUE (serial, unitmodelid), "
+ "CONSTRAINT chk_contract_valid CHECK((contractid IS NULL) OR (contractid IS NOT NULL AND contractexpires IS NOT NULL)) "
@@ -788,7 +787,7 @@ $BODY$ LANGUAGE PLPGSQL STABLE");
//WORKORDERITEM LABOR
await ExecQueryAsync("CREATE TABLE aworkorderitemlabor (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, workorderitemid BIGINT NOT NULL REFERENCES aworkorderitem (id), "
+ "userid BIGINT REFERENCES auser, servicestartdate TIMESTAMP, servicestopdate TIMESTAMP, servicerateid BIGINT REFERENCES aservicerate, servicedetails text, "
+ "serviceratequantity DECIMAL(19,5) NOT NULL default 0, nochargequantity DECIMAL(19,5) NOT NULL default 0, servicebankid BIGINT REFERENCES aservicebank, "
+ "serviceratequantity DECIMAL(19,5) NOT NULL default 0, nochargequantity DECIMAL(19,5) NOT NULL default 0, "
+ "taxcodesaleid BIGINT REFERENCES ataxcode, priceoverride DECIMAL(38,18) "
+ ")");
@@ -825,7 +824,7 @@ $BODY$ LANGUAGE PLPGSQL STABLE");
//WORKORDERITEM TRAVEL
await ExecQueryAsync("CREATE TABLE aworkorderitemtravel (id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, workorderitemid BIGINT NOT NULL REFERENCES aworkorderitem (id), "
+ "userid BIGINT REFERENCES auser, travelstartdate TIMESTAMP, travelstopdate TIMESTAMP, travelrateid BIGINT REFERENCES atravelrate, traveldetails text, "
+ "travelratequantity DECIMAL(19,5) NOT NULL default 0, nochargequantity DECIMAL(19,5) NOT NULL default 0, servicebankid BIGINT REFERENCES aservicebank, "
+ "travelratequantity DECIMAL(19,5) NOT NULL default 0, nochargequantity DECIMAL(19,5) NOT NULL default 0, "
+ "taxcodesaleid BIGINT REFERENCES ataxcode, distance DECIMAL(19,5) NOT NULL default 0, priceoverride DECIMAL(38,18) "
+ ")");

View File

@@ -422,7 +422,7 @@ namespace AyaNova.Util
await EraseTableAsync("aservicerate", conn);
await EraseTableAsync("atravelrate", conn);
await EraseTableAsync("ataxcode", conn);
await EraseTableAsync("aservicebank", conn);
//await EraseTableAsync("aservicebank", conn);
await EraseTableAsync("aworkorderstatus", conn);
await EraseTableAsync("aworkorderitemstatus", conn);

View File

@@ -2070,7 +2070,7 @@ namespace AyaNova.Util
}
//for now no banked units in seeds
o.UsesBanking = false;
//o.UsesBanking = false;
o.Metered = false;//for now no meters either
o.Text1 = null;
o.Text2 = null;