diff --git a/APIHandler.cs b/APIHandler.cs index 3a03f72..bc68f22 100644 --- a/APIHandler.cs +++ b/APIHandler.cs @@ -9,24 +9,29 @@ public static partial class APIHandler { App //============MISC================= - .Map("/updatecache",cache=>{ - cache.Run(async runner=>{ + .Map("/updatecache", cache => + { + cache.Run(async runner => + { await UpdateCache(); - await runner.WriteJsonResponse(StatusCodes.Status200OK,"Cache Updated."); + await runner.WriteJsonResponse(StatusCodes.Status200OK, "Cache Updated."); }); }) //===========UNITS================= - .Map("/getunits", units =>{ - units.Run(async runner=> + .Map("/getunits", units => + { + units.Run(async runner => { if (!await runner.RequestValidated(2)) return; - await runner.WriteJsonResponse( StatusCodes.Status200OK, "Success", Deployments); + await runner.WriteJsonResponse(StatusCodes.Status200OK, "Success", Deployments); }); }) - .Map("/chunit", unit =>{ - unit.Run(async runner=>{ + .Map("/chunit", unit => + { + unit.Run(async runner => + { if (!await runner.RequestValidated(2, "POST", true)) return; - if(await runner.TryGetBodyJsonAsync(["deplid", "unitkerja"], CTS.Token) is Dictionary InElement) + if (await runner.TryGetBodyJsonAsync(["deplid", "unitkerja"], CTS.Token) is Dictionary InElement) { Deployment CorrectDeployment = new( InElement["deplid"].GetInt16(), @@ -37,25 +42,28 @@ public static partial class APIHandler await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string."); return; } - int i = Deployments.FindIndex(depl=>depl.DeplID == CorrectDeployment.DeplID); - if(i<0) + int i = Deployments.FindIndex(depl => depl.DeplID == CorrectDeployment.DeplID); + if (i < 0) { - await runner.WriteJsonResponse(StatusCodes.Status404NotFound,"Deployment ID not found."); - return; + await runner.WriteJsonResponse(StatusCodes.Status404NotFound, "Deployment ID not found."); + return; } - _ = await RunNonQueryAsync(CS,"UPDATE deployment SET unitkerja = @uk WHERE deplid = @id",Comm=>{ + _ = await RunNonQueryAsync(CS, "UPDATE deployment SET unitkerja = @uk WHERE deplid = @id", Comm => + { Comm.Parameters.AddWithValue("@id", CorrectDeployment.DeplID); Comm.Parameters.AddWithValue("@uk", CorrectDeployment.UnitKerja); - },CTS.Token); + }, CTS.Token); Deployments[i] = CorrectDeployment; - await runner.WriteJsonResponse(StatusCodes.Status202Accepted,"Data updated.",Deployments[i]); + await runner.WriteJsonResponse(StatusCodes.Status202Accepted, "Data updated.", Deployments[i]); } }); }) - .Map("/addunit", unit =>{ - unit.Run(async runner=>{ + .Map("/addunit", unit => + { + unit.Run(async runner => + { if (!await runner.RequestValidated(2, "POST", true)) return; - if(await runner.TryGetBodyJsonAsync(["unitkerja"], CTS.Token) is Dictionary InElement) + if (await runner.TryGetBodyJsonAsync(["unitkerja"], CTS.Token) is Dictionary InElement) { string UnitKerja = InElement["unitkerja"].GetString() ?? ""; if (UnitKerja.Length < 1) @@ -63,25 +71,30 @@ public static partial class APIHandler await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "Unit Kerja can't be empty string."); return; } - short DeplID = (short)await RunScalarAsync(CS,"INSERT INTO deployment OUTPUT INSERTED.deplid VALUES (@uk)",Comm=>{ + short DeplID = (short)await RunScalarAsync(CS, "INSERT INTO deployment OUTPUT INSERTED.deplid VALUES (@uk)", Comm => + { Comm.Parameters.AddWithValue("@uk", UnitKerja); - },CTS.Token); - Deployment Inserted = new(DeplID,UnitKerja); + }, CTS.Token); + Deployment Inserted = new(DeplID, UnitKerja); Deployments.Add(Inserted); // EventsMarker.CacheUpdates = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString("X"); - await runner.WriteJsonResponse(StatusCodes.Status201Created,"Data Created.",Inserted); + await runner.WriteJsonResponse(StatusCodes.Status201Created, "Data Created.", Inserted); } }); }) //============AGENTS============== - .Map("/getagents", agents=>{ - agents.Run(async runner=>{ + .Map("/getagents", agents => + { + agents.Run(async runner => + { if (!await runner.RequestValidated(2)) return; - await runner.WriteJsonResponse(StatusCodes.Status200OK,"Success",Agents); + await runner.WriteJsonResponse(StatusCodes.Status200OK, "Success", Agents); }); }) - .Map("/addagent", agent=>{ - agent.Run(async runner=>{ + .Map("/addagent", agent => + { + agent.Run(async runner => + { if (!await runner.RequestValidated(1, "POST", true)) return; if (await runner.TryGetBodyJsonAsync(["agentid", "name", "jabatan", "deplid", "skangkat", "tmt", "skper", "tgper", "vision", "mission", "photo", "createuser", "uname", "pass", "level"], CTS.Token) is Dictionary InElement) { @@ -105,7 +118,7 @@ public static partial class APIHandler if (AgentID.Equals(string.Empty) || Name.Equals(string.Empty) || Jabatan.Equals(string.Empty) || - DeploymentID.Equals(0) || + //DeploymentID.Equals(0) || SKAngkat.Equals(string.Empty) || TMT.Equals(DateOnly.Parse("1970-01-01")) || (!SKPer.Equals(string.Empty) && TGPer is null) || @@ -115,7 +128,7 @@ public static partial class APIHandler (!await runner.RequestValidated(Level, "POST")) ) { - await runner.WriteJsonResponse( StatusCodes.Status400BadRequest, "One or more input(s) are not acceptable, in an unsupported format, or an attempt to create user account of a higher level than the creator is made."); + await runner.WriteJsonResponse(StatusCodes.Status400BadRequest, "One or more input(s) are not acceptable, in an unsupported format, or an attempt to create user account of a higher level than the creator is made."); return; } if (!Photo.Equals(string.Empty)) @@ -166,11 +179,54 @@ public static partial class APIHandler }, CTS.Token ); string OutMessage = CreateUser ? "New Agent and respective User Account created" : "New Agent created. User account creation is possible."; - await runner.WriteJsonResponse(StatusCodes.Status201Created, OutMessage, CreateUser?new SafeUser(UName,AgentID,Level,true):NewAgent); - // await runner.WriteJsonResponse(200, "OK", NewAgent); + await runner.WriteJsonResponse(StatusCodes.Status201Created, OutMessage, CreateUser ? new SafeUser(UName, AgentID, Level, true) : NewAgent); } }); }) + .Map("/chagent", agent => + { + agent.Run(async runner => + { + if (!await runner.RequestValidated(0, "POST", true)) return; + if (await runner.TryGetBodyJsonAsync(["agentid", "updates"], CTS.Token) is Dictionary InElement) + { + if (InElement["updates"].ValueKind != JsonValueKind.Object) return; + string AgentID = InElement["agentid"].GetString() ?? string.Empty; + JsonElement UpdateFields = InElement["updates"]; + using SqlDataReader Updated = await RunReaderAsync(CS, "", Comm => + { + StringBuilder CommandBuilder = new(); + CommandBuilder.Append("UPDATE agents SET"); + foreach (JsonProperty Prop in UpdateFields.EnumerateObject()) + { + Comm.Parameters.AddWithValue($"@p{Prop.Name}", Prop.Value.ValueKind == JsonValueKind.String ? Prop.Value.GetString() == "DBNull" ? DBNull.Value : Prop.Value.GetString() : Prop.Value.GetInt16()); + CommandBuilder.Append($" [{Prop.Name}] = @p{Prop.Name},"); + } + Comm.Parameters.AddWithValue("@pagentid", AgentID); + CommandBuilder.Remove(CommandBuilder.Length - 1, 1); + CommandBuilder.Append(" OUTPUT INSERTED.* WHERE agentid = @pagentid"); + Comm.CommandText = CommandBuilder.ToString(); + }, CTS.Token); + Agent UpAgent = (await Updated.ToListAsync(a => new + ( + AgentID, + (string)a["name"], + (string)a["jabatan"], + (short)a["deplid"], + (string)a["skangkat"], + DateOnly.FromDateTime((DateTime)a["tmt"]), + a["skperubahan"] == DBNull.Value ? null : (string)a["skperubahan"], + a["tgperubahan"] == DBNull.Value ? null : DateOnly.FromDateTime((DateTime)a["tgperubahan"]), + a["vision"] == DBNull.Value ? null : (string)a["vision"], + a["mission"] == DBNull.Value ? null : (string)a["mission"], + a["photourl"] == DBNull.Value ? null : (string)a["photourl"] + ), CTS.Token))[0]; + await runner.WriteJsonResponse(StatusCodes.Status202Accepted, "Data updated.", UpAgent); + } + }); + }) + + //=========ACTIVITIES============= ; }