Files
2015-10-02 10:45:25 -04:00

103 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using MileageTraker.Web.DAL;
namespace MileageTraker.Web.Models
{
public class Log : IValidatableObject
{
[Key]
public int LogId { get; set; }
[Required]
public virtual Vehicle Vehicle { get; set; }
[Required]
[Range(1, 500000, ErrorMessage = "Between 1 and 500k")]
public int EndOdometer { get; set; }
[Required]
[Display(Name = "Type")]
public MileageLogTypeWrapper LogType { get; set; }
[Required]
public virtual User User { get; set; }
[Required]
[StringLength(64, MinimumLength = 3, ErrorMessage = "Minimum 3 characters")]
public string CityName { get; set; }
public virtual PurposeType Purpose { get; set; }
[StringLength(64, MinimumLength = 3, ErrorMessage = "Minimum 3 characters")]
public string Notes { get; set; }
[Range(0, 50)]
public double GasPurchased { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Display(Name = "Time Created")]
[DisplayFormat(DataFormatString = @"{0:MM/dd/yyyy h:mm tt}")]
[HiddenInput]
public DateTime Created { get; set; }
/// <summary>
/// url route that was used to create this instance, ie 'CreateLog\Confirm' or 'Logs\Create'
/// </summary>
public string Source { get; set; }
public string UserHostAddress { get; set; }
public string UserAgent { get; set; }
[HiddenInput(DisplayValue = false)]
public int? VehiclePreviousLogId { get; set; }
[HiddenInput(DisplayValue = false)]
public virtual Log VehiclePreviousLog { get; set; }
public virtual ICollection<FuelLog> FuelLogs { get; set; }
public Log()
{
LogType = new MileageLogTypeWrapper();
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (LogType == MileageLogType.GasPurchase && (GasPurchased.Equals(0)))
yield return new ValidationResult("Enter amount of gas purchased", new[] { "GasPurchased" });
if (LogType.Value == 0)
yield return new ValidationResult("Required", new[] { "LogType" });
using (var dataService = new DataService())
{
ValidationResult result = null;
try
{
dataService.ValidateOdometerChronology(Vehicle.VehicleId, EndOdometer, Date);
}
catch (ChronologicalOrderException ex)
{
result = new ValidationResult(ex.Message, new[] {"EndOdometer"});
}
if (result != null)
yield return result;
var inactiveDate = dataService.GetVehicle(Vehicle.VehicleId).InactiveDate;
if (inactiveDate.HasValue && Date.Date > inactiveDate)
{
yield return new ValidationResult(
string.Format("Vehicle was set inactive on {0:MM/dd/yyyy}", inactiveDate.Value),
new[] {"Date"});
}
}
}
}
}