using FoodsharingSiegen.Contracts; using FoodsharingSiegen.Contracts.Entity; using FoodsharingSiegen.Contracts.Enums; using FoodsharingSiegen.Server.Auth; using Microsoft.EntityFrameworkCore; namespace FoodsharingSiegen.Server.Data.Service { /// /// The audit service class (a. beging, 23.05.2022) /// /// public class AuditService : ServiceBase { #region Setup/Teardown /// /// Initializes a new instance of the class /// /// The context (ab) /// public AuditService(FsContext context, AuthService authService) : base(context, authService) { } #endregion #region Public Method Insert /// /// Inserts the type (a. beging, 23.05.2022) /// /// The type /// The data /// The data /// A task containing an operation result of audit public async Task> Insert(AuditType type, string? data1 = null, string? data2 = null) { try { var audit = new Audit { Created = DateTime.Now, Type = type, UserID = CurrentUser?.Id, Data1 = data1, Data2 = data2 }; Context.Audits?.Add(audit); var saveR = await Context.SaveChangesAsync(); if (saveR > 0) return new(audit); return new(new Exception("Couldn't add audit")); } catch (Exception e) { return new(e); } } #endregion #region Public Method GetCount /// /// Gets the total count (ab) /// /// The type /// A task containing an operation result of count public async Task> GetCount(AuditType? type = null) { try { var query = Context.Audits?.AsQueryable(); if (type != null) query = query?.Where(x => x.Type == type); if (query == null) return new(0); var count = await query.CountAsync(); return new(count); } catch (Exception e) { return new(e); } } #endregion #region Public Method LoadPage /// /// Loads the page of audits (ab) /// /// The skip count /// The take count /// The type /// A task containing an operation result of list audit public async Task>> LoadPage(int skip, int take, AuditType? type = null) { try { var query = Context.Audits?.Include(x => x.User).OrderByDescending(x => x.Created).AsQueryable(); if (type != null) query = query?.Where(x => x.Type == type); query = query?.Skip(skip).Take(take); var mat = await query!.ToListAsync(); if (mat != null) return new(mat); return new(new Exception("Couldn't load audits")); } catch (Exception e) { return new(e); } } #endregion } }