-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathEntryFillDialog.cs
More file actions
299 lines (282 loc) · 14.7 KB
/
EntryFillDialog.cs
File metadata and controls
299 lines (282 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Bot.Clockify.Client;
using Bot.Clockify.Models;
using Bot.Common;
using Bot.Common.ChannelData.Telegram;
using Bot.Common.Recognizer;
using Bot.Data;
using Bot.States;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Bot.Clockify.Fill
{
public class EntryFillDialog : ComponentDialog
{
private readonly ClockifyEntityRecognizer _clockifyWorkableRecognizer;
private readonly IClockifyService _clockifyService;
private readonly ITokenRepository _tokenRepository;
private readonly ITimeEntryStoreService _timeEntryStoreService;
private readonly WorthAskingForTaskService _worthAskingForTask;
private readonly UserState _userState;
private readonly IClockifyMessageSource _messageSource;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly ILogger<EntryFillDialog> _logger;
private const string TaskWaterfall = "TaskWaterfall";
private const string AskForTaskStep = "AskForTask";
private const string AskForNewTaskNameStep = "AskForNewTaskNameStep";
private const string No = "no";
private const string NewTask = "new task";
private const string Abort = "abort";
private const string Telegram = "telegram";
public EntryFillDialog(ClockifyEntityRecognizer clockifyWorkableRecognizer,
ITimeEntryStoreService timeEntryStoreService, WorthAskingForTaskService worthAskingForTask,
UserState userState, IClockifyService clockifyService, ITokenRepository tokenRepository,
IClockifyMessageSource messageSource, IDateTimeProvider dateTimeProvider, ILogger<EntryFillDialog> logger)
{
_clockifyWorkableRecognizer = clockifyWorkableRecognizer;
_timeEntryStoreService = timeEntryStoreService;
_worthAskingForTask = worthAskingForTask;
_userState = userState;
_clockifyService = clockifyService;
_tokenRepository = tokenRepository;
_messageSource = messageSource;
_dateTimeProvider = dateTimeProvider;
_logger = logger;
AddDialog(new WaterfallDialog(TaskWaterfall, new List<WaterfallStep>
{
PromptForTaskAsync,
CreateWithTaskOrAskForNewTaskAsync,
FeedbackAndExit
}));
AddDialog(new TextPrompt(AskForTaskStep, ClockifyTaskValidatorAsync));
AddDialog(new TextPrompt(AskForNewTaskNameStep));
Id = nameof(EntryFillDialog);
}
private async Task<DialogTurnResult> PromptForTaskAsync(WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
var userProfile =
await StaticUserProfileHelper.GetUserProfileAsync(_userState, stepContext.Context, cancellationToken);
var tokenData = await _tokenRepository.ReadAsync(userProfile.ClockifyTokenId!);
string clockifyToken = tokenData.Value;
stepContext.Values["ClockifyTokenId"] = userProfile.ClockifyTokenId;
var luisResult = (TimeSurveyBotLuis) stepContext.Options;
try
{
var recognizedProject =
await _clockifyWorkableRecognizer.RecognizeProject(luisResult.ProjectName(), clockifyToken);
stepContext.Values["Project"] = recognizedProject;
stepContext.Values["TimeZone"] = userProfile.TimeZone;
double minutes = luisResult.WorkedDurationInMinutes();
var (start, end) = luisResult.WorkedPeriod(_dateTimeProvider, minutes, userProfile.TimeZone);
stepContext.Values["Start"] = start;
stepContext.Values["End"] = end;
string fullEntity = recognizedProject.Name;
stepContext.Values["FullEntity"] = fullEntity;
if (await _worthAskingForTask.IsWorthAskingForTask(recognizedProject, userProfile))
{
var suggestedTasks =
await _clockifyService.GetTasksAsync(clockifyToken, recognizedProject.WorkspaceId,
recognizedProject.Id);
var suggestions = suggestedTasks
.Where(t => t.Status == TaskStatusDo.Active)
.Select(t => new CardAction
{
Title = t.Name, Type = ActionTypes.MessageBack, Value = t.Name, Text = t.Name,
DisplayText = t.Name
}).OrderBy(c => c.Title).ToList();
suggestions.Add(
new CardAction
{
Title = _messageSource.No, Type = ActionTypes.MessageBack, Text = No, Value = No,
DisplayText = _messageSource.No
});
suggestions.Add(
new CardAction
{
Title = _messageSource.NewTask, Type = ActionTypes.MessageBack, Text = NewTask,
Value = NewTask,
DisplayText = _messageSource.NewTask
});
var activity = MessageFactory.Text(_messageSource.TaskSelectionQuestion);
activity.SuggestedActions = new SuggestedActions {Actions = suggestions};
return await stepContext.PromptAsync(AskForTaskStep, new PromptOptions
{
Prompt = activity,
RetryPrompt = MessageFactory.Text(_messageSource.TaskUnrecognizedRetry),
Validations = new ClockifyTaskValidatorOptions(recognizedProject, clockifyToken)
}, cancellationToken);
}
return await AddEntryAndExit(stepContext, cancellationToken, clockifyToken,
recognizedProject, start, end, fullEntity, null);
}
catch (CannotRecognizeProjectException e)
{
_logger.LogError(e, "Cannot recognize project: {ExMessage}", e.Message);
await stepContext.Context.SendActivityAsync(MessageFactory.Text(
string.Format(_messageSource.ProjectUnrecognized, e.Unmatchable)), cancellationToken);
return await stepContext.EndDialogAsync(null, cancellationToken);
}
catch (AmbiguousRecognizableProjectException e)
{
_logger.LogError(e, "Cannot recognize project: {ExMessage}", e.Message);
await stepContext.Context.SendActivityAsync(
MessageFactory.Text(string.Format(_messageSource.AmbiguousProjectError, e.Option1.Name,
e.Option2.Name)), cancellationToken);
return await stepContext.EndDialogAsync(null, cancellationToken);
}
catch (Exception e) when (e is InvalidWorkedDurationException ||
e is InvalidWorkedEntityException)
{
_logger.LogError(e, "{ExMessage}", e.Message);
await stepContext.Context.SendActivityAsync(
MessageFactory.Text(_messageSource.EntryFillUnderstandingError),
cancellationToken);
return await stepContext.EndDialogAsync(null, cancellationToken);
}
}
private async Task<DialogTurnResult> CreateWithTaskOrAskForNewTaskAsync(WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
var clockifyTokenId = (string) stepContext.Values["ClockifyTokenId"];
var project = (ProjectDo) stepContext.Values["Project"];
var start = (DateTime) stepContext.Values["Start"];
var end = (DateTime) stepContext.Values["End"];
TaskDo? recognizedTask = null;
var requestedTask = stepContext.Result.ToString();
var fullEntity = (string) stepContext.Values["FullEntity"];
switch (requestedTask?.ToLower())
{
case NewTask:
return await stepContext.PromptAsync(AskForNewTaskNameStep, new PromptOptions
{
Prompt = MessageFactory.Text(_messageSource.TaskCreation)
}, cancellationToken);
case No:
{
var tokenData = await _tokenRepository.ReadAsync(clockifyTokenId);
string clockifyToken = tokenData.Value;
return await AddEntryAndExit(stepContext, cancellationToken, clockifyToken,
project, start, end, fullEntity, recognizedTask);
}
case Abort:
await stepContext.Context.SendActivityAsync(MessageFactory.Text(_messageSource.TaskAbort),
cancellationToken);
return await stepContext.EndDialogAsync(null, cancellationToken);
default:
{
var tokenData = await _tokenRepository.ReadAsync(clockifyTokenId);
string clockifyToken = tokenData.Value;
try
{
recognizedTask =
await _clockifyWorkableRecognizer.RecognizeTask(requestedTask, clockifyToken, project);
fullEntity += " - " + recognizedTask.Name;
}
catch (CannotRecognizeProjectException e)
{
_logger.LogError(e, "Cannot recognize task: {ExMessage}", e.Message);
await stepContext.Context.SendActivityAsync(
MessageFactory.Text(_messageSource.TaskUnrecognized), cancellationToken);
return await stepContext.EndDialogAsync(null, cancellationToken);
}
return await AddEntryAndExit(stepContext, cancellationToken, clockifyToken,
project, start, end, fullEntity, recognizedTask);
}
}
}
private async Task<DialogTurnResult> FeedbackAndExit(WaterfallStepContext stepContext,
CancellationToken cancellationToken)
{
var clockifyTokenId = (string) stepContext.Values["ClockifyTokenId"];
var project = (ProjectDo) stepContext.Values["Project"];
var start = (DateTime) stepContext.Values["Start"];
var end = (DateTime) stepContext.Values["End"]; var newTaskName = stepContext.Result.ToString();
var fullEntity = (string) stepContext.Values["FullEntity"];
var tokenData = await _tokenRepository.ReadAsync(clockifyTokenId);
string clockifyToken = tokenData.Value;
try
{
var createdTask = await _clockifyService.CreateTaskAsync(clockifyToken, new TaskReq(newTaskName!),
project.Id, project.WorkspaceId);
fullEntity += " - " + createdTask.Name;
return await AddEntryAndExit(stepContext, cancellationToken, clockifyToken, project, start, end,
fullEntity, createdTask);
}
catch (Exception)
{
// TODO Fallback to generic error.
await stepContext.Context.SendActivityAsync(
MessageFactory.Text(_messageSource.TaskCreationError), cancellationToken);
// TODO Maybe we should just return the error and end the dialog.
return await AddEntryAndExit(stepContext, cancellationToken, clockifyToken, project, start, end,
fullEntity, null);
}
}
private async Task<bool> ClockifyTaskValidatorAsync(PromptValidatorContext<string> promptContext,
CancellationToken cancellationToken)
{
string? requestedTask = promptContext.Recognized.Value;
var options = (ClockifyTaskValidatorOptions) promptContext.Options.Validations;
string[] specialAnswers = {No, NewTask, Abort};
if (specialAnswers.Contains(requestedTask?.ToLower())) return true;
try
{
await _clockifyWorkableRecognizer.RecognizeTask(requestedTask, options.Token, options.Project);
return true;
}
catch (CannotRecognizeProjectException)
{
return false;
}
}
private async Task<DialogTurnResult> AddEntryAndExit(WaterfallStepContext stepContext,
CancellationToken cancellationToken, string clockifyToken, ProjectDo recognizedProject,
DateTime start, DateTime end, string fullEntity, TaskDo? task)
{
var timeZone = (TimeZoneInfo) stepContext.Values["TimeZone"];
double current =
await _timeEntryStoreService.AddTimeEntries(clockifyToken, recognizedProject, task, start, end, timeZone);
string messageText =
string.Format(_messageSource.AddEntryFeedback, (end-start).TotalMinutes, fullEntity, current);
string platform = stepContext.Context.Activity.ChannelId;
var ma = GetExitMessageActivity(messageText, platform);
await stepContext.Context.SendActivityAsync(ma, cancellationToken);
return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
}
private static IMessageActivity GetExitMessageActivity(string messageText, string platform)
{
IMessageActivity ma;
switch (platform.ToLower())
{
case Telegram:
ma = Activity.CreateMessageActivity();
var sendMessageParams = new SendMessageParameters(messageText, new ReplyKeyboardRemove());
var channelData = new SendMessage(sendMessageParams);
ma.ChannelData = JsonConvert.SerializeObject(channelData);
return ma;
default:
ma = MessageFactory.Text(messageText);
ma.SuggestedActions = new SuggestedActions {Actions = new List<CardAction>()};
return ma;
};
}
}
internal class ClockifyTaskValidatorOptions
{
public ClockifyTaskValidatorOptions(ProjectDo project, string token)
{
Project = project;
Token = token;
}
public ProjectDo Project { get; }
public string Token { get; }
}
}