Skip to content

Commit

Permalink
Merge pull request #721 from hargata/Hargata/operationresponse.cleanup.1
Browse files Browse the repository at this point in the history
Clean up OperationResponse method Part 1
  • Loading branch information
hargata authored Nov 19, 2024
2 parents c5a5de5 + 25952cc commit f629834
Show file tree
Hide file tree
Showing 14 changed files with 99 additions and 80 deletions.
2 changes: 1 addition & 1 deletion Controllers/AdminController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public IActionResult GenerateNewToken(string emailAddress, bool autoNotify)
}
}
}
var successResponse = new OperationResponse { Success = true, Message = "Token Generated!" };
var successResponse = OperationResponse.Succeed("Token Generated!");
return Json(successResponse);
} else
{
Expand Down
4 changes: 2 additions & 2 deletions Controllers/FilesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public IActionResult HandleTranslationFileUpload(IFormFile file)
var originalFileName = Path.GetFileNameWithoutExtension(file.FileName);
if (originalFileName == "en_US")
{
return Json(new OperationResponse { Success = false, Message = "The translation file name en_US is reserved." });
return Json(OperationResponse.Failed("The translation file name en_US is reserved."));
}
var fileName = UploadFile(file);
//move file from temp to translation folder.
Expand All @@ -43,7 +43,7 @@ public IActionResult HandleTranslationFileUpload(IFormFile file)
var result = _fileHelper.RenameFile(uploadedFilePath, originalFileName);
return Json(new OperationResponse { Success = result, Message = string.Empty });
}
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}

[HttpPost]
Expand Down
8 changes: 4 additions & 4 deletions Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -280,12 +280,12 @@ public IActionResult UpdateUserAccount(LoginModel userAccount)
var result = _loginLogic.UpdateUserDetails(userId, userAccount);
return Json(result);
}
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
}
[HttpGet]
Expand Down Expand Up @@ -496,13 +496,13 @@ public async Task<IActionResult> DownloadAllTranslations()
return Json(new OperationResponse() { Success = true, Message = $"{translationsDownloaded} Translations Downloaded" });
} else
{
return Json(new OperationResponse() { Success = false, Message = "No Translations Downloaded" });
return Json(OperationResponse.Failed("No Translations Downloaded"));
}
}
catch (Exception ex)
{
_logger.LogError($"Unable to retrieve translations: {ex.Message}");
return Json(new OperationResponse() { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
}
public ActionResult GetVehicleSelector(int vehicleId)
Expand Down
10 changes: 5 additions & 5 deletions Controllers/MigrationController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public IActionResult Export()
{
if (string.IsNullOrWhiteSpace(_configHelper.GetServerPostgresConnection()))
{
return Json(new OperationResponse { Success = false, Message = "Postgres connection not set up" });
return Json(OperationResponse.Failed("Postgres connection not set up"));
}
var tempFolder = $"temp/{Guid.NewGuid()}";
var tempPath = $"{tempFolder}/cartracker.db";
Expand Down Expand Up @@ -424,19 +424,19 @@ public IActionResult Export()
catch (Exception ex)
{
_logger.LogError(ex.Message);
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
}
public IActionResult Import(string fileName)
{
if (string.IsNullOrWhiteSpace(_configHelper.GetServerPostgresConnection()))
{
return Json(new OperationResponse { Success = false, Message = "Postgres connection not set up" });
return Json(OperationResponse.Failed("Postgres connection not set up"));
}
var fullFileName = _fileHelper.GetFullFilePath(fileName);
if (string.IsNullOrWhiteSpace(fullFileName))
{
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
try
{
Expand Down Expand Up @@ -749,7 +749,7 @@ public IActionResult Import(string fileName)
catch (Exception ex)
{
_logger.LogError(ex.Message);
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
}
}
Expand Down
14 changes: 7 additions & 7 deletions Controllers/Vehicle/PlanController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public IActionResult SavePlanRecordTemplateToVehicleId(PlanRecordInput planRecor
var existingRecord = _planRecordTemplateDataAccess.GetPlanRecordTemplatesByVehicleId(planRecord.VehicleId).Where(x => x.Description == planRecord.Description).Any();
if (planRecord.Id == default && existingRecord)
{
return Json(new OperationResponse { Success = false, Message = "A template with that description already exists for this vehicle" });
return Json(OperationResponse.Failed("A template with that description already exists for this vehicle"));
}
planRecord.Files = planRecord.Files.Select(x => { return new UploadedFiles { Name = x.Name, Location = _fileHelper.MoveFileFromTemp(x.Location, "documents/") }; }).ToList();
var result = _planRecordTemplateDataAccess.SavePlanRecordTemplateToVehicle(planRecord);
Expand All @@ -72,7 +72,7 @@ public IActionResult OrderPlanSupplies(int planRecordTemplateId)
var existingRecord = _planRecordTemplateDataAccess.GetPlanRecordTemplateById(planRecordTemplateId);
if (existingRecord.Id == default)
{
return Json(new OperationResponse { Success = false, Message = "Unable to find template" });
return Json(OperationResponse.Failed("Unable to find template"));
}
if (existingRecord.Supplies.Any())
{
Expand All @@ -81,7 +81,7 @@ public IActionResult OrderPlanSupplies(int planRecordTemplateId)
}
else
{
return Json(new OperationResponse { Success = false, Message = "Template has No Supplies" });
return Json(OperationResponse.Failed("Template has No Supplies"));
}
}
[HttpPost]
Expand All @@ -90,19 +90,19 @@ public IActionResult ConvertPlanRecordTemplateToPlanRecord(int planRecordTemplat
var existingRecord = _planRecordTemplateDataAccess.GetPlanRecordTemplateById(planRecordTemplateId);
if (existingRecord.Id == default)
{
return Json(new OperationResponse { Success = false, Message = "Unable to find template" });
return Json(OperationResponse.Failed("Unable to find template"));
}
if (existingRecord.Supplies.Any())
{
//check if all supplies are available
var supplyAvailability = CheckSupplyRecordsAvailability(existingRecord.Supplies);
if (supplyAvailability.Any(x => x.Missing))
{
return Json(new OperationResponse { Success = false, Message = "Missing Supplies, Please Delete This Template and Recreate It." });
return Json(OperationResponse.Failed("Missing Supplies, Please Delete This Template and Recreate It."));
}
else if (supplyAvailability.Any(x => x.Insufficient))
{
return Json(new OperationResponse { Success = false, Message = "Insufficient Supplies" });
return Json(OperationResponse.Failed("Insufficient Supplies"));
}
}
if (existingRecord.ReminderRecordId != default)
Expand All @@ -111,7 +111,7 @@ public IActionResult ConvertPlanRecordTemplateToPlanRecord(int planRecordTemplat
var existingReminder = _reminderRecordDataAccess.GetReminderRecordById(existingRecord.ReminderRecordId);
if (existingReminder is null || existingReminder.Id == default || !existingReminder.IsRecurring)
{
return Json(new OperationResponse { Success = false, Message = "Missing or Non-recurring Reminder, Please Delete This Template and Recreate It." });
return Json(OperationResponse.Failed("Missing or Non-recurring Reminder, Please Delete This Template and Recreate It."));
}
}
//populate createdDate
Expand Down
4 changes: 2 additions & 2 deletions Controllers/Vehicle/ReportController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -311,13 +311,13 @@ public IActionResult GetVehicleAttachments(int vehicleId, List<ImportMode> expor
var result = _fileHelper.MakeAttachmentsExport(attachmentData);
if (string.IsNullOrWhiteSpace(result))
{
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
return Json(new OperationResponse { Success = true, Message = result });
}
else
{
return Json(new OperationResponse { Success = false, Message = "No Attachments Found" });
return Json(OperationResponse.Failed("No Attachments Found"));
}
}
public IActionResult GetReportParameters()
Expand Down
4 changes: 2 additions & 2 deletions Controllers/VehicleController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,15 +188,15 @@ public IActionResult DuplicateVehicleCollaborators(int sourceVehicleId, int dest
}
else
{
return Json(new OperationResponse { Success = false, Message = "Both vehicles already have identical collaborators" });
return Json(OperationResponse.Failed("Both vehicles already have identical collaborators"));
}
}
return Json(new OperationResponse { Success = true, Message = "Collaborators Copied" });
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return Json(new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage });
return Json(OperationResponse.Failed());
}
}

Expand Down
28 changes: 14 additions & 14 deletions Helper/MailHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ public OperationResponse NotifyUserForRegistration(string emailAddress, string t
{
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
{
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
return OperationResponse.Failed("SMTP Server Not Setup");
}
if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(token)) {
return new OperationResponse { Success = false, Message = "Email Address or Token is invalid" };
return OperationResponse.Failed("Email Address or Token is invalid");
}
string emailSubject = "Your Registration Token for LubeLogger";
string emailBody = $"A token has been generated on your behalf, please complete your registration for LubeLogger using the token: {token}";
Expand All @@ -44,18 +44,18 @@ public OperationResponse NotifyUserForRegistration(string emailAddress, string t
return new OperationResponse { Success = true, Message = "Email Sent!" };
} else
{
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
return OperationResponse.Failed();
}
}
public OperationResponse NotifyUserForPasswordReset(string emailAddress, string token)
{
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
{
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
return OperationResponse.Failed("SMTP Server Not Setup");
}
if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(token))
{
return new OperationResponse { Success = false, Message = "Email Address or Token is invalid" };
return OperationResponse.Failed("Email Address or Token is invalid");
}
string emailSubject = "Your Password Reset Token for LubeLogger";
string emailBody = $"A token has been generated on your behalf, please reset your password for LubeLogger using the token: {token}";
Expand All @@ -66,18 +66,18 @@ public OperationResponse NotifyUserForPasswordReset(string emailAddress, string
}
else
{
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
return OperationResponse.Failed();
}
}
public OperationResponse NotifyUserForAccountUpdate(string emailAddress, string token)
{
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
{
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
return OperationResponse.Failed("SMTP Server Not Setup");
}
if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(token))
{
return new OperationResponse { Success = false, Message = "Email Address or Token is invalid" };
return OperationResponse.Failed("Email Address or Token is invalid");
}
string emailSubject = "Your User Account Update Token for LubeLogger";
string emailBody = $"A token has been generated on your behalf, please update your account for LubeLogger using the token: {token}";
Expand All @@ -88,22 +88,22 @@ public OperationResponse NotifyUserForAccountUpdate(string emailAddress, string
}
else
{
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
return OperationResponse.Failed();
}
}
public OperationResponse NotifyUserForReminders(Vehicle vehicle, List<string> emailAddresses, List<ReminderRecordViewModel> reminders)
{
if (string.IsNullOrWhiteSpace(mailConfig.EmailServer))
{
return new OperationResponse { Success = false, Message = "SMTP Server Not Setup" };
return OperationResponse.Failed("SMTP Server Not Setup");
}
if (!emailAddresses.Any())
{
return new OperationResponse { Success = false, Message = "No recipients could be found" };
return OperationResponse.Failed("No recipients could be found");
}
if (!reminders.Any())
{
return new OperationResponse { Success = false, Message = "No reminders could be found" };
return OperationResponse.Failed("No reminders could be found");
}
//get email template, this file has to exist since it's a static file.
var emailTemplatePath = _fileHelper.GetFullFilePath(StaticHelper.ReminderEmailTemplate);
Expand All @@ -126,11 +126,11 @@ public OperationResponse NotifyUserForReminders(Vehicle vehicle, List<string> em
return new OperationResponse { Success = true, Message = "Email Sent!" };
} else
{
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
return OperationResponse.Failed();
}
} catch (Exception ex)
{
return new OperationResponse { Success = false, Message = ex.Message };
return OperationResponse.Failed(ex.Message);
}
}
private bool SendEmail(List<string> emailTo, string emailSubject, string emailBody) {
Expand Down
20 changes: 10 additions & 10 deletions Helper/StaticHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ namespace CarCareTracker.Helper
/// </summary>
public static class StaticHelper
{
public static string VersionNumber = "1.4.0";
public static string DbName = "data/cartracker.db";
public static string UserConfigPath = "config/userConfig.json";
public static string AdditionalWidgetsPath = "data/widgets.html";
public static string GenericErrorMessage = "An error occurred, please try again later";
public static string ReminderEmailTemplate = "defaults/reminderemailtemplate.txt";
public static string DefaultAllowedFileExtensions = ".png,.jpg,.jpeg,.pdf,.xls,.xlsx,.docx";
public static string SponsorsPath = "https://hargata.github.io/hargata/sponsors.json";
public static string TranslationPath = "https://hargata.github.io/lubelog_translations";
public static string TranslationDirectoryPath = $"{TranslationPath}/directory.json";
public const string VersionNumber = "1.4.0";
public const string DbName = "data/cartracker.db";
public const string UserConfigPath = "config/userConfig.json";
public const string AdditionalWidgetsPath = "data/widgets.html";
public const string GenericErrorMessage = "An error occurred, please try again later";
public const string ReminderEmailTemplate = "defaults/reminderemailtemplate.txt";
public const string DefaultAllowedFileExtensions = ".png,.jpg,.jpeg,.pdf,.xls,.xlsx,.docx";
public const string SponsorsPath = "https://hargata.github.io/hargata/sponsors.json";
public const string TranslationPath = "https://hargata.github.io/lubelog_translations";
public const string TranslationDirectoryPath = $"{TranslationPath}/directory.json";
public const string ReportNote = "Report generated by LubeLogger, a Free and Open Source Vehicle Maintenance Tracker - LubeLogger.com";
public static string GetTitleCaseReminderUrgency(ReminderUrgency input)
{
Expand Down
8 changes: 4 additions & 4 deletions Helper/TranslationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,15 @@ public OperationResponse SaveTranslation(string userLanguage, Dictionary<string,
bool isDefaultLanguage = userLanguage == "en_US";
if (isDefaultLanguage && !create)
{
return new OperationResponse { Success = false, Message = "The translation file name en_US is reserved." };
return OperationResponse.Failed("The translation file name en_US is reserved.");
}
if (string.IsNullOrWhiteSpace(userLanguage))
{
return new OperationResponse { Success = false, Message = "File name is not provided." };
return OperationResponse.Failed("File name is not provided.");
}
if (!translations.Any())
{
return new OperationResponse { Success = false, Message = "Translation has no data." };
return OperationResponse.Failed("Translation has no data.");
}
var translationFilePath = isDefaultLanguage ? _fileHelper.GetFullFilePath($"/defaults/en_US.json") : _fileHelper.GetFullFilePath($"/translations/{userLanguage}.json", false);
try
Expand All @@ -164,7 +164,7 @@ public OperationResponse SaveTranslation(string userLanguage, Dictionary<string,
catch (Exception ex)
{
_logger.LogError(ex.Message);
return new OperationResponse { Success = false, Message = StaticHelper.GenericErrorMessage };
return OperationResponse.Failed();
}
}
public string ExportTranslation(Dictionary<string, string> translations)
Expand Down
Loading

0 comments on commit f629834

Please sign in to comment.