-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathOperationData.cs
More file actions
850 lines (678 loc) · 28.7 KB
/
OperationData.cs
File metadata and controls
850 lines (678 loc) · 28.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
// Copyright (c) 2025, Phoenix Contact GmbH & Co. KG
// Licensed under the Apache License, Version 2.0
using Moryx.ControlSystem.Jobs;
using Moryx.AbstractionLayer.Products;
using Moryx.AbstractionLayer.Recipes;
using Moryx.Container;
using Moryx.Logging;
using Moryx.Notifications;
using Moryx.Orders.Management.Assignment;
using Moryx.Orders.Management.Model;
using Moryx.Orders.Management.Properties;
using Moryx.StateMachines;
using Moryx.Tools;
using Moryx.Users;
using Microsoft.Extensions.Logging;
namespace Moryx.Orders.Management
{
/// <summary>
/// Business object for operation data
/// </summary>
[Component(LifeCycle.Transient, typeof(IOperationData))]
internal class OperationData : IOperationData, IStateContext, ILoggingComponent, INotificationSender
{
private readonly object _stateLock = new();
private readonly List<OperationReport> _reports;
private readonly List<OperationAdvice> _advices;
private readonly List<Job> _jobs;
private DispatchHandler _dispatchHandler;
private OperationDataStateBase _state;
#region Dependencies
public IModuleLogger Logger { get; set; }
public IJobHandler JobHandler { get; set; }
public IOperationAssignment OperationAssignment { get; set; }
public ICountStrategy CountStrategy { get; set; }
public INotificationAdapter NotificationAdapter { get; set; }
public ModuleConfig ModuleConfig { get; set; }
#endregion
public OperationData()
{
Operation = new InternalOperation();
_reports = new List<OperationReport>();
_advices = new List<OperationAdvice>();
_jobs = new List<Job>();
}
void IStateContext.SetState(IState state)
{
// ReSharper disable InconsistentlySynchronizedField
_state = (OperationDataStateBase)state;
Operation.State = _state.GetFullClassification();
Operation.StateDisplayName = _state.GetType().GetDisplayName();
Updated?.Invoke(this, new OperationEventArgs(this));
}
/// <inheritdoc cref="IOperationData"/>
public InternalOperation Operation { get; }
string INotificationSender.Identifier => $"{OrderData.Number}-{Number}";
/// <inheritdoc cref="IOperationData"/>
public Guid Identifier => Operation.Identifier;
/// <inheritdoc cref="IOperationData"/>
public string Number => Operation.Number;
/// <inheritdoc cref="IOperationData"/>
public int TotalAmount => Operation.TotalAmount;
/// <inheritdoc cref="IOperationData"/>
public int TargetAmount => Operation.TargetAmount;
/// <inheritdoc cref="IOperationData"/>
public ProductType Product => Operation.Product;
private int _sortOrder;
/// <inheritdoc cref="IOperationData"/>
public int SortOrder
{
get => _sortOrder;
set
{
if (_sortOrder == value)
return;
_sortOrder = value;
Operation.SortOrder = value;
Updated?.Invoke(this, new OperationEventArgs(this));
}
}
public IOrderData OrderData { get; set; }
private OperationAssignState _assignState;
/// <inheritdoc />
public OperationAssignState AssignState
{
get => _assignState;
set
{
_assignState = value;
//Update the state of the internal operation
if (_state is not null)
Operation.State = _state.GetFullClassification();
}
}
/// <inheritdoc cref="IOperationData"/>
// ReSharper disable once InconsistentlySynchronizedField
public IOperationState State => _state;
/// <summary>
/// Flag if operation have reached the amount.
/// </summary>
internal bool AmountReached => CountStrategy.AmountReached(Operation);
/// <summary>
/// Flag if the operation can reach the amount with the current jobs
/// </summary>
internal bool CanReachAmount => CountStrategy.CanReachAmount(Operation);
/// <summary>
/// Sum of SuccessCount and RunningCount of jobs. All running will be classified as "success"
/// </summary>
internal int ReachableAmount => CountStrategy.ReachableAmount(Operation);
/// <inheritdoc />
public IOperationData Initialize(OperationCreationContext context, IOrderData orderData, IOperationSource source)
{
StateMachine.Initialize(this).With<OperationDataStateBase>();
_dispatchHandler = new DispatchHandler(this);
AssignState = OperationAssignState.Initial;
OrderData = orderData;
orderData.AddOperation(this);
Operation.Identifier = Guid.NewGuid();
Operation.CreationContext = context;
Operation.Source = source;
Operation.Name = context.Name;
Operation.Parts = context.Parts?.Select(p => new ProductPart
{
Name = p.Name,
Identity = new ProductIdentity(p.Number, 0),
Quantity = p.Quantity,
Unit = p.Unit,
StagingIndicator = p.StagingIndicator,
Classification = p.Classification
}).ToArray() ?? [];
Operation.Number = context.Number;
Operation.TotalAmount = context.TotalAmount;
Operation.PlannedStart = context.PlannedStart;
Operation.PlannedEnd = context.PlannedEnd;
Operation.TargetCycleTime = context.TargetCycleTime;
Operation.Unit = context.Unit;
Operation.TargetStock = context.TargetStock;
var overDeliveryAmount = context.OverDeliveryAmount;
if (overDeliveryAmount < context.TotalAmount)
overDeliveryAmount = context.TotalAmount;
Operation.OverDeliveryAmount = overDeliveryAmount;
var underDeliveryAmount = context.UnderDeliveryAmount;
if (underDeliveryAmount > context.TotalAmount)
underDeliveryAmount = context.TotalAmount;
Operation.UnderDeliveryAmount = underDeliveryAmount;
// Facade references
Operation.Product = new ProductReference(new ProductIdentity(context.ProductIdentifier, context.ProductRevision));
return this;
}
/// <inheritdoc />
public IOperationData Initialize(OperationEntity entity, IOrderData orderData)
{
_dispatchHandler = new DispatchHandler(this);
OrderData = orderData;
orderData.AddOperation(this);
OperationStorage.RestoreOperationData(this, entity);
StateMachine.Reload(this, entity.State).With<OperationDataStateBase>();
return this;
}
/// <summary>
/// Adds the given reports to the internal report list without locking or raising events
/// </summary>
public void RestoreReportsUnsynchronized(IReadOnlyList<OperationReport> reports)
{
// ReSharper disable once InconsistentlySynchronizedField
_reports.AddRange(reports);
Operation.Reports = reports.ToArray();
}
/// <summary>
/// Add the given advices to the internal advice list without locking or raising events
/// </summary>
public void RestoreAdvicesUnsynchronized(IReadOnlyList<OperationAdvice> advices)
{
// ReSharper disable once InconsistentlySynchronizedField
_advices.AddRange(advices);
Operation.Advices = advices.ToArray();
}
/// <summary>
/// Adds the given job to the internal job list, without locking and raising events
/// </summary>
public void RestoreJobsUnsynchronized(IReadOnlyList<Job> jobs)
{
// ReSharper disable once InconsistentlySynchronizedField
_jobs.AddRange(jobs);
Operation.Jobs = jobs.ToArray();
}
/// <inheritdoc cref="IOperationData"/>
public void AddJob(Job job)
{
Log(LogLevel.Information, "Job {0} was added", job.Id);
lock (_jobs)
{
_jobs.Add(job);
Operation.Jobs = _jobs.ToArray();
}
UpdateProgress();
Updated?.Invoke(this, new OperationEventArgs(this));
}
/// <inheritdoc cref="IOperationData"/>
public void Assign()
{
Log(LogLevel.Information, "Starting assignment");
lock (_stateLock)
_state.Assign();
}
/// <inheritdoc cref="IOperationData"/>
public void AssignCompleted(bool success)
{
if (success)
Operation.CreationContext = null;
lock (_stateLock)
_state.AssignCompleted(success);
}
internal void HandleAssignCompleted(bool success)
{
Log(success ? LogLevel.Information : LogLevel.Warning, "Assignment completed and was {0}",
success ? "successful" : "not successful");
AssignState = success ? OperationAssignState.Assigned : OperationAssignState.Failed;
Updated?.Invoke(this, new OperationEventArgs(this));
}
internal void HandleAssign()
{
OperationAssignment.Assign(this);
}
internal void HandleReassign()
{
OperationAssignment.Reassign(this);
}
/// <inheritdoc cref="IOperationData"/>
public void Abort()
{
Log(LogLevel.Information, "Aborting operation");
lock (_stateLock)
_state.Abort();
}
internal void HandleAbort()
{
Aborted?.Invoke(this, new OperationEventArgs(this));
}
/// <inheritdoc cref="IOperationData"/>
public async Task Restore()
{
var restorableJobs = StashRestorableJobs();
RestoreJobs(restorableJobs);
// Restore creation information
await OperationAssignment.Restore(this);
// Send update
UpdateProgress();
Updated?.Invoke(this, new OperationEventArgs(this));
}
private long[] StashRestorableJobs()
{
long[] restorableJobs;
lock (_jobs)
{
restorableJobs = _jobs.Select(j => j.Id).ToArray();
_jobs.Clear();
}
return restorableJobs;
}
private void RestoreJobs(long[] restorableJobs)
{
var restoredJobs = JobHandler.Restore(restorableJobs);
lock (_jobs)
{
_jobs.AddRange(restoredJobs);
Operation.Jobs = _jobs.ToArray();
}
var jobInformation = restorableJobs.Length != 0 ? $"Jobs {string.Join(", ", restorableJobs)}" : "No jobs";
Log(LogLevel.Information, "{jobInformation} were restored", jobInformation);
}
/// <inheritdoc cref="IOperationData"/>
public void Resume()
{
// Restore on state
lock (_stateLock)
_state.Resume();
}
/// <inheritdoc cref="IOperationData"/>
public BeginContext GetBeginContext()
{
var context = GetOperationInfo<BeginContext>();
// If there are not produced parts, the residual amount will be set
// If there are more produced parts as planned, the residual amount is 0
context.ResidualAmount = Operation.TotalAmount > Operation.TargetAmount ? Operation.TotalAmount - Operation.TargetAmount : 0;
context.PartialAmount = Operation.TargetAmount;
context.MinimalTargetAmount = Operation.TargetAmount;
context.CanReduce = _state.CanReduceAmount;
return context;
}
/// <inheritdoc cref="IOperationData"/>
public void Adjust(int amount, User user)
{
Log(LogLevel.Information, "The target amount of the operation will be adjusted by amount {amount} by user {user}",
amount, user.Identifier);
lock (_stateLock)
{
if (amount >= 0)
{
_state.IncreaseTargetBy(amount, user);
}
else
{
_state.DecreaseTargetBy(amount, user);
}
}
}
/// <summary>
/// Calculates the current amount and dispatches a job
/// </summary>
internal void HandleIncreaseTargetBy(int partialAmount)
{
// Save the first start time of the production
Operation.Start ??= DateTime.Now;
// partial amount can be 0 to restart an interrupting operation
// We do not have to increase the TargetAmount so far
if (partialAmount > 0)
{
Operation.TargetAmount += partialAmount;
Updated?.Invoke(this, new OperationEventArgs(this));
}
DispatchJob();
}
/// <summary>
/// Calculates the new target amount, completes the current jobs and
/// dispatches a job if necessary
/// </summary>
internal void HandleDecreaseTargetBy(int amount)
{
Operation.TargetAmount += amount;
JobHandler.Complete(this);
DispatchJob();
Updated?.Invoke(this, new OperationEventArgs(this));
}
/// <summary>
/// Raises the started event
/// </summary>
internal void HandleStarted(User user)
{
Started?.Invoke(this, new StartedEventArgs(this, user));
}
/// <param name="user"></param>
/// <inheritdoc cref="IOperationData"/>
public void Interrupt(User user)
{
Log(LogLevel.Debug, "Operation will be interrupted by user {0}",
user.Identifier);
lock (_stateLock)
_state.Interrupt(user);
}
/// <summary>
/// Will complete all jobs and executes a partial report
/// </summary>
internal void HandleManualInterrupting()
{
JobHandler.Complete(this);
}
/// <summary>
/// Will handle manual interrupts. The interrupt was triggered by the user.
/// Will throw the <see cref="Interrupted"/> event
/// </summary>
internal void HandleManualInterrupted()
{
Operation.TargetAmount = ReachableAmount;
Updated?.Invoke(this, new OperationEventArgs(this));
Interrupted?.Invoke(this, new OperationEventArgs(this));
}
/// <summary>
/// Will handle the interrupt if all jobs are completed
/// Will be called by the state machine
/// </summary>
internal void HandleInterrupted()
{
Operation.TargetAmount = ReachableAmount;
Updated?.Invoke(this, new OperationEventArgs(this));
Interrupted?.Invoke(this, new OperationEventArgs(this));
}
/// <inheritdoc cref="IOperationData"/>
public void Report(OperationReport report)
{
Log(LogLevel.Information, "Operation will be reported with SuccessCount {0} and FailureCount {1} by user {2}",
report.SuccessCount, report.FailureCount, report.User.Identifier);
if (report.SuccessCount < 0 || report.FailureCount < 0)
{
const string error = "Amounts less than zero cannot be reported!";
Log(LogLevel.Error, error);
throw new ArgumentException(error);
}
lock (_stateLock)
_state.Report(report);
}
/// <inheritdoc cref="IOperationData"/>
public AdviceContext GetAdviceContext()
{
AdviceContext adviceContext;
lock (_stateLock)
adviceContext = _state.GetAdviceContext();
return adviceContext;
}
internal AdviceContext HandleAdviceContext()
{
return new()
{
AdvicedAmount = Operation.Advices.OfType<OrderAdvice>().Sum(a => a.Amount)
};
}
/// <inheritdoc cref="IOperationData"/>
public void Advice(OperationAdvice advice)
{
Log(LogLevel.Information, "Operation will be adviced for ToteBoxNumber {0}", advice.ToteBoxNumber);
var orderAdvice = advice as OrderAdvice;
var pickPartAdvice = advice as PickPartAdvice;
void ThrowError(string error)
{
Log(LogLevel.Error, error);
throw new ArgumentException(error);
}
if (orderAdvice is { Amount: <= 0 })
ThrowError("Amount less then or equals zero cannot be adviced!");
if (pickPartAdvice != null && !Operation.Parts.Contains(pickPartAdvice.Part))
ThrowError("The part to advice is not part of the operation!");
if (orderAdvice == null && pickPartAdvice == null)
ThrowError("Advices of type " + advice.GetType().Name + " cannot be handled.");
lock (_stateLock)
_state.Advice(advice);
}
internal void HandleAdvice(OperationAdvice advice)
{
lock (_advices)
{
_advices.Add(advice);
Operation.Advices = _advices.ToArray();
}
Updated?.Invoke(this, new OperationEventArgs(this));
Adviced?.Invoke(this, new AdviceEventArgs(this, advice));
}
/// <summary>
/// Will throw the <see cref="Completed"/> event
/// </summary>
internal void HandleCompleted(OperationReport report)
{
Operation.End = DateTime.Now;
lock (_reports)
{
_reports.Add(report);
Operation.Reports = _reports.ToArray();
}
Updated?.Invoke(this, new OperationEventArgs(this));
Completed?.Invoke(this, new ReportEventArgs(this, report));
}
/// <summary>
/// Will throw the <see cref="PartialReport"/> event
/// </summary>
internal void HandlePartialReport(OperationReport report)
{
lock (_reports)
{
_reports.Add(report);
Operation.Reports = _reports.ToArray();
}
Updated?.Invoke(this, new OperationEventArgs(this));
PartialReport?.Invoke(this, new ReportEventArgs(this, report));
}
/// <inheritdoc cref="IOperationData"/>
public ReportContext GetReportContext()
{
ReportContext reportContext;
lock (_stateLock)
reportContext = _state.GetReportContext();
return reportContext;
}
internal ReportContext HandleReportContext()
{
var reportedSuccess = Operation.Reports.Sum(r => r.SuccessCount);
var reportedFailure = Operation.Reports.Sum(r => r.FailureCount);
var unreportedFailure = Operation.Progress.ScrapCount - reportedFailure;
if (unreportedFailure < 0)
unreportedFailure = 0;
var unreportedSuccess = Operation.Progress.SuccessCount - reportedSuccess;
if (unreportedSuccess < 0)
unreportedSuccess = 0;
var context = GetOperationInfo<ReportContext>();
context.UnreportedFailure = unreportedFailure;
context.UnreportedSuccess = unreportedSuccess;
context.ReportedSuccess = reportedSuccess;
context.ReportedFailure = reportedFailure;
return context;
}
/// <inheritdoc cref="IOperationData"/>
public void AssignProduct(ProductType productType)
{
Operation.Product = productType;
}
/// <inheritdoc cref="IOperationData"/>
public void AssignRecipes(IReadOnlyList<IProductRecipe> recipes)
{
// Replaces the recipes with the given new list
Operation.Recipes.Clear();
Operation.Recipes.AddRange(recipes);
Updated?.Invoke(this, new OperationEventArgs(this));
}
public void RecipeChanged(IProductRecipe productRecipe)
{
if (productRecipe.TemplateId == 0)
{
AssignState |= OperationAssignState.Changed;
Log(LogLevel.Debug, "Template changed. AssignState is now 'Changed'");
}
else
{
Log(LogLevel.Debug, "Recipe changed. Recipe instance will be updated");
// Only update a recipe if it is part of the current recipes
var affectedRecipe = Operation.Recipes.FirstOrDefault(r => r.Id == productRecipe.Id);
if (affectedRecipe == null)
return;
Operation.Recipes.Remove(affectedRecipe);
Operation.Recipes.Add(productRecipe);
Updated?.Invoke(this, new OperationEventArgs(this));
// Complete running jobs to stop the production of the outdated recipe
// New jobs will be dispatched automatically with the new recipes
JobHandler.Complete(this);
}
Updated?.Invoke(this, new OperationEventArgs(this));
}
/// <inheritdoc cref="IOperationData"/>
public void JobProgressChanged(Job job)
{
UpdateProgress();
lock (_stateLock)
_state.ProgressChanged(job);
ProgressChanged?.Invoke(this, new OperationEventArgs(this));
}
/// <inheritdoc cref="IOperationData"/>
public void JobStateChanged(JobStateChangedEventArgs args)
{
UpdateProgress();
lock (_stateLock)
_state.JobsUpdated(args);
}
internal void DispatchJob()
{
_dispatchHandler.TryDispatch();
}
/// <inheritdoc />
public void UpdateSource(IOperationSource source)
{
Operation.Source = source;
Updated?.Invoke(this, new OperationEventArgs(this));
}
private void UpdateProgress()
{
var relevantJobs = CountStrategy.RelevantJobs(Operation).ToArray();
var progress = Operation.Progress;
// Progress on relevant jobs
progress.RunningCount = relevantJobs.Sum(j => j.RunningProcesses.Count);
progress.SuccessCount = relevantJobs.Sum(j => j.SuccessCount);
progress.FailureCount = relevantJobs.Sum(j => j.FailureCount);
progress.ReworkedCount = relevantJobs.Sum(j => j.ReworkedCount);
progress.PendingCount = relevantJobs.Where(j => j.Classification <= JobClassification.Running)
.Sum(j => j.Amount - j.SuccessCount - j.RunningProcesses.Count - j.FailureCount);
var scrap = progress.FailureCount - progress.ReworkedCount;
progress.ScrapCount = scrap < 0 ? 0 : scrap;
// Progress on all jobs
var allJobs = Operation.Jobs; // use thread save list
progress.ProgressRunning = allJobs.Sum(j => j.RunningProcesses.Count);
progress.ProgressSuccess = allJobs.Sum(j => j.SuccessCount);
progress.ProgressScrap = allJobs.Sum(j => j.FailureCount - j.ReworkedCount) >= 0
? allJobs.Sum(j => j.FailureCount - j.ReworkedCount) : 0;
progress.ProgressPending =
allJobs.Where(j => j.Classification < JobClassification.Completed).Sum(j => j.Amount) +
allJobs.Where(j => j.Classification == JobClassification.Completed).Sum(j => j.SuccessCount) -
allJobs.Sum(j => j.SuccessCount + j.RunningProcesses.Count + j.FailureCount);
}
private void Log(LogLevel logLevel, string message, params object[] parameters) =>
Logger.Log(logLevel, $"{OrderData.Number}-{Operation.Number}: {message}", parameters);
private TInfo GetOperationInfo<TInfo>()
where TInfo : OperationInfo, new()
{
var info = new TInfo();
// do all in a single job lock
var successCount = Operation.Progress.SuccessCount;
var scrapCount = Operation.Progress.ScrapCount;
if (scrapCount < 0)
scrapCount = 0;
info.SuccessCount = successCount;
info.ScrapCount = scrapCount;
return info;
}
/// <inheritdoc cref="IOperationData.Updated"/>
public event EventHandler<OperationEventArgs> Updated;
/// <inheritdoc cref="IOperationData.Updated"/>
public event EventHandler<OperationEventArgs> Aborted;
/// <inheritdoc cref="IOperationData.Started"/>
public event EventHandler<StartedEventArgs> Started;
/// <inheritdoc cref="IOperationData.Interrupted"/>
public event EventHandler<OperationEventArgs> Interrupted;
/// <inheritdoc cref="IOperationData.Completed"/>
public event EventHandler<ReportEventArgs> Completed;
/// <inheritdoc cref="IOperationData.PartialReport"/>
public event EventHandler<ReportEventArgs> PartialReport;
/// <inheritdoc cref="IOperationData.Adviced"/>
public event EventHandler<AdviceEventArgs> Adviced;
/// <inheritdoc cref="IOperationData.ProgressChanged"/>
public event EventHandler<OperationEventArgs> ProgressChanged;
/// <summary>
/// Handler to ensure a save dispatching.
/// Sometimes it can happen that a job update trigger another dispatching while the dispatching isn't finally done
/// </summary>
private sealed class DispatchHandler
{
private readonly OperationData _operationData;
private readonly ICountStrategy _countStrategy;
private readonly IJobHandler _jobHandler;
private readonly object _dispatchLock = new();
private bool _isDispatching;
private bool _isDispatchingRequested;
public DispatchHandler(OperationData operationData)
{
_operationData = operationData;
_countStrategy = operationData.CountStrategy;
_jobHandler = operationData.JobHandler;
}
public void TryDispatch()
{
lock (_dispatchLock)
{
// If the operation is currently dispatching then remember that another dispatch is requested.
// Otherwise just remember that right now a dispatch will be started.
if (_isDispatching)
{
_isDispatchingRequested = true;
return;
}
_isDispatching = true;
}
var missingAmounts = _countStrategy.MissingAmounts(_operationData.Operation);
if (missingAmounts.Count == 0)
{
_operationData.Log(LogLevel.Error, "There is nothing to dispatch. Check the {0}.", _countStrategy.GetType().Name);
TryRequestedDispatches();
return;
}
_operationData.Log(LogLevel.Debug, "At least one job should be dispatched");
_jobHandler.Dispatch(_operationData, missingAmounts);
TryRequestedDispatches();
}
private void TryRequestedDispatches()
{
lock (_dispatchLock)
{
_isDispatching = false;
if (!_isDispatchingRequested)
return;
// Dispatch again if a dispatch was requested during the last dispatching
_isDispatchingRequested = false;
}
TryDispatch();
}
}
#region Notifications
void INotificationSender.Acknowledge(Notification notification, object tag)
{
NotificationAdapter.Acknowledge(this, notification);
}
internal void ShowAmountReachedNotification()
{
if (ModuleConfig.DisableAmountReachedNotification)
return;
NotificationAdapter.Publish(this, new Notification(Strings.OperationData_AmountReachedNotificationTitle,
string.Format(Strings.OperationData_AmountReachedNotificationMessage,
$"{OrderData.Number}-{Number}"), Severity.Info));
}
internal void AcknowledgeAmountReachedNotification()
{
NotificationAdapter.AcknowledgeAll(this);
}
#endregion
}
}