BotSharp/src/Infrastructure/BotSharp.Core/Agents/Services/AgentService.CreateAgent.cs

48 lines
1.5 KiB
C#
Raw Normal View History

2023-06-23 04:43:00 +00:00
using BotSharp.Abstraction.Agents.Models;
2023-08-26 04:41:01 +00:00
using BotSharp.Abstraction.Repositories;
using BotSharp.Abstraction.Repositories.Records;
2023-08-28 05:28:14 +00:00
using MongoDB.Bson;
2023-06-23 04:43:00 +00:00
namespace BotSharp.Core.Agents.Services;
public partial class AgentService
{
public async Task<Agent> CreateAgent(Agent agent)
{
2023-08-10 04:53:22 +00:00
var db = _services.GetRequiredService<IBotSharpRepository>();
2023-07-25 02:22:18 +00:00
var record = (from a in db.Agent
join ua in db.UserAgent on a.Id equals ua.AgentId
2023-08-10 04:53:22 +00:00
join u in db.User on ua.UserId equals u.Id
where (ua.UserId == _user.Id || u.ExternalId == _user.Id) && a.Name == agent.Name
2023-07-25 02:22:18 +00:00
select a).FirstOrDefault();
2023-06-23 04:43:00 +00:00
if (record != null)
{
return record.ToAgent();
}
record = AgentRecord.FromAgent(agent);
2023-08-28 05:28:14 +00:00
record.Id = ObjectId.GenerateNewId().ToString();
2023-08-26 04:41:01 +00:00
record.CreatedTime = DateTime.UtcNow;
record.UpdatedTime = DateTime.UtcNow;
2023-06-23 04:43:00 +00:00
2023-08-28 05:36:11 +00:00
var user = db.User.FirstOrDefault(x => x.ExternalId == _user.Id);
2023-07-25 02:22:18 +00:00
var userAgentRecord = new UserAgentRecord
{
2023-08-28 05:36:11 +00:00
UserId = user?.Id ?? ObjectId.GenerateNewId().ToString(),
2023-07-25 02:22:18 +00:00
AgentId = record.Id,
CreatedTime = DateTime.UtcNow,
UpdatedTime = DateTime.UtcNow
};
2023-07-21 21:56:14 +00:00
db.Transaction<IBotSharpTable>(delegate
2023-06-23 04:43:00 +00:00
{
2023-07-21 21:56:14 +00:00
db.Add<IBotSharpTable>(record);
2023-07-25 02:22:18 +00:00
db.Add<IBotSharpTable>(userAgentRecord);
2023-06-23 04:43:00 +00:00
});
return record.ToAgent();
}
}