TimesheetTimberlinePoster.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. using Comal.Classes;
  2. using CsvHelper;
  3. using CsvHelper.Configuration.Attributes;
  4. using InABox.Core;
  5. using InABox.Core.Postable;
  6. using InABox.Poster.Timberline;
  7. using InABox.Scripting;
  8. using Microsoft.Win32;
  9. using PRS.Shared.TimeSheetTimberline;
  10. using System.ComponentModel;
  11. using System.Globalization;
  12. using System.IO;
  13. namespace PRS.Shared
  14. {
  15. namespace TimeSheetTimberline
  16. {
  17. /// <summary>
  18. /// Represents a block of time having an <see cref="Comal.Classes.Activity"/>. It will always be linked to a timesheet.
  19. /// </summary>
  20. /// <remarks>
  21. /// The primary reason we need a link to a time sheet is so that we can mark the given time sheet as posted if all its corresponding activity blocks
  22. /// are posted correctly.
  23. /// </remarks>
  24. public class ActivityBlock
  25. {
  26. public Guid Activity { get; set; }
  27. public TimeSpan Start { get; set; }
  28. public TimeSpan Finish { get; set; }
  29. public TimeSheet TimeSheet { get; set; }
  30. public TimeSpan Duration => Finish - Start;
  31. /// <summary>
  32. /// Create an <see cref="ActivityBlock"/> from an <see cref="Assignment"/>, taking the <see cref="Start"/> and <see cref="Finish"/> from
  33. /// <see cref="Assignment.EffectiveStartTime"/> and <see cref="Assignment.EffectiveFinishTime"/>.
  34. /// </summary>
  35. /// <remarks>
  36. /// The activity is sourced from the assignment, unless the assignment has no activity, in which case the activity on the timesheet is used.
  37. /// </remarks>
  38. public ActivityBlock(Assignment assignment, TimeSheet sheet)
  39. {
  40. Activity = assignment.ActivityLink.ID != Guid.Empty
  41. ? assignment.ActivityLink.ID
  42. : sheet.ActivityLink.ID;
  43. Start = assignment.EffectiveStartTime();
  44. Finish = assignment.EffectiveFinishTime();
  45. TimeSheet = sheet;
  46. }
  47. /// <summary>
  48. /// Creates an <see cref="ActivityBlock"/> from the timesheet, using the <see
  49. /// cref="TimeSheet.ApprovedStart"/> and <see cref="TimeSheet.ApprovedFinish"/>.
  50. /// </summary>
  51. public ActivityBlock(TimeSheet sheet)
  52. {
  53. Activity = sheet.ActivityLink.ID;
  54. Start = sheet.ApprovedStart;
  55. Finish = sheet.ApprovedFinish;
  56. TimeSheet = sheet;
  57. }
  58. /// <summary>
  59. /// Creates an <see cref="ActivityBlock"/> from the timesheet, but with a custom start and finish,
  60. /// for use with masking activities.
  61. /// </summary>
  62. public ActivityBlock(TimeSheet sheet, TimeSpan start, TimeSpan finish)
  63. {
  64. Activity = sheet.ActivityLink.ID;
  65. Start = start;
  66. Finish = finish;
  67. TimeSheet = sheet;
  68. }
  69. /// <summary>
  70. /// Ensure that this <see cref="ActivityBlock"/> fits within the bounds of the <see cref="TimeSheet"/>.
  71. /// </summary>
  72. /// <returns>Itself.</returns>
  73. public ActivityBlock Chop(TimeSheet sheet)
  74. {
  75. if (Start < sheet.ApprovedStart)
  76. {
  77. Start = sheet.ApprovedStart;
  78. }
  79. if (Finish > sheet.ApprovedFinish)
  80. {
  81. Finish = sheet.ApprovedFinish;
  82. }
  83. return this;
  84. }
  85. /// <summary>
  86. /// Check if this block is partially or fully within the given timesheet.
  87. /// </summary>
  88. public bool ContainedInTimeSheet(TimeSheet sheet) =>
  89. Start < sheet.ApprovedFinish && Finish > sheet.ApprovedStart;
  90. public bool IntersectsWith(ActivityBlock other)
  91. {
  92. return Start < other.Finish && Finish > other.Start;
  93. }
  94. }
  95. public interface IBlock
  96. {
  97. IJob Job { get; set; }
  98. string Extra { get; set; }
  99. string TaskID { get; set; }
  100. TimeSpan Duration { get; set; }
  101. string PayrollID { get; set; }
  102. TimeSheet TimeSheet { get; set; }
  103. }
  104. public class PaidWorkBlock(string taskID, TimeSpan duration, string payID, IJob job, TimeSheet timeSheet) : IBlock
  105. {
  106. public IJob Job { get; set; } = job;
  107. public string Extra { get; set; } = "";
  108. public string TaskID { get; set; } = taskID;
  109. public TimeSpan Duration { get; set; } = duration;
  110. public string PayrollID { get; set; } = payID;
  111. public TimeSheet TimeSheet { get; set; } = timeSheet;
  112. }
  113. public class LeaveBlock(string payrollID, TimeSpan duration, TimeSheet timeSheet) : IBlock
  114. {
  115. public IJob Job { get; set; } = new Job();
  116. public string Extra { get; set; } = "";
  117. public string TaskID { get; set; } = "";
  118. public TimeSpan Duration { get; set; } = duration;
  119. public string PayrollID { get; set; } = payrollID;
  120. public TimeSheet TimeSheet { get; set; } = timeSheet;
  121. }
  122. public class BaseArgs(IDataModel<TimeSheet> model, Guid employee, DateTime date) : CancelEventArgs
  123. {
  124. public IDataModel<TimeSheet> Model { get; set; } = model;
  125. public Guid Employee { get; set; } = employee;
  126. public DateTime Date { get; set; } = date;
  127. }
  128. public class ProcessRawDataArgs(
  129. IDataModel<TimeSheet> model, Guid employee, DateTime date,
  130. List<TimeSheet> timeSheets, List<Assignment> assignments) : BaseArgs(model, employee, date)
  131. {
  132. public List<TimeSheet> TimeSheets { get; set; } = timeSheets;
  133. public List<Assignment> Assignments { get; set; } = assignments;
  134. }
  135. public class ProcessActivityBlocksArgs(
  136. IDataModel<TimeSheet> model, Guid employee, DateTime date,
  137. List<ActivityBlock> activityBlocks) : BaseArgs(model, employee, date)
  138. {
  139. public List<ActivityBlock> ActivityBlocks { get; set; } = activityBlocks;
  140. }
  141. public class ProcessTimeBlocksArgs(
  142. IDataModel<TimeSheet> model, Guid employee, DateTime date,
  143. List<IBlock> blocks) : BaseArgs(model, employee, date)
  144. {
  145. public List<IBlock> Blocks { get; set; } = blocks;
  146. }
  147. public class ProcessItemArgs(
  148. IDataModel<TimeSheet> model, Guid employee, DateTime date,
  149. IJob job,
  150. TimesheetTimberlineItem item) : BaseArgs(model, employee, date)
  151. {
  152. public TimesheetTimberlineItem Item { get; set; } = item;
  153. public IJob Job { get; set; } = job;
  154. }
  155. }
  156. public class TimeSheetTimberlineResult : PostResult<TimeSheet>
  157. {
  158. private List<TimesheetTimberlineItem> items = new List<TimesheetTimberlineItem>();
  159. public IEnumerable<TimesheetTimberlineItem> Items => items;
  160. public void AddItem(TimesheetTimberlineItem item)
  161. {
  162. items.Add(item);
  163. }
  164. public void Sort()
  165. {
  166. items.Sort((a, b) =>
  167. {
  168. var sort = a.Employee.CompareTo(b.Employee);
  169. if (sort != 0) return sort;
  170. return a.InDate.CompareTo(b.InDate);
  171. });
  172. }
  173. }
  174. public class TimesheetTimberlineItem
  175. {
  176. [Index(0)]
  177. public string Employee { get; set; } = "";
  178. [Index(1)]
  179. [CsvHelper.Configuration.Attributes.TypeConverter(typeof(TimberlinePosterDateConverter))]
  180. public DateOnly InDate { get; set; }
  181. [Index(2)]
  182. public string Job { get; set; } = "";
  183. [Index(3)]
  184. public string Extra { get; set; } = "";
  185. [Index(4)]
  186. public string Task { get; set; } = "";
  187. [Index(5)]
  188. public double Hours { get; set; }
  189. [Index(6)]
  190. public string PayID { get; set; } = "";
  191. }
  192. public enum TimesheetTimberlineActivityCalculation
  193. {
  194. /// <summary>
  195. /// Assignments are completely ignored by the export, so that the activities and time is solely provided by the time sheet.
  196. /// </summary>
  197. TimesheetOnly,
  198. /// <summary>
  199. /// Timesheets with activities are processed like in <see cref="TimesheetOnly"/>, but for timesheets without activities, the
  200. /// assignments are used to generate time blocks, resorting to the timesheet where there is no assignment.
  201. /// </summary>
  202. TimesheetPriority,
  203. /// <summary>
  204. /// Leave timesheets are processed like <see cref="TimesheetOnly"/>, but all other timesheets use assignments to generate time blocks,
  205. /// resorting to the timesheet when there is no assignment for a block of time.
  206. /// </summary>
  207. AssignmentPriority
  208. }
  209. public class TimesheetTimberlineSettings : TimberlinePosterSettings<TimeSheet>
  210. {
  211. [EnumLookupEditor(typeof(TimesheetTimberlineActivityCalculation), LookupWidth = 200)]
  212. public TimesheetTimberlineActivityCalculation ActivityCalculation { get; set; }
  213. protected override string DefaultScript()
  214. {
  215. return
  216. @"using PRS.Shared;
  217. using PRS.Shared.TimeSheetTimberline;
  218. using InABox.Core;
  219. using System.Collections.Generic;
  220. public class Module
  221. {
  222. /* A number of classes are present under the PRS.Shared.TimeSheetTimberline namespace to represent the data:
  223. - ActivityBlock: a block of time with an activity, taken from a timesheet or an assignment.
  224. - IBlock: base interface for blocks of time used by 'ProcessTimeBlocks'; this is either a
  225. - PaidWorkBlock: representing time that the employee was working, or
  226. - LeaveBlock: representing time the employee was on leave.
  227. */
  228. public void BeforePost(IDataModel<TimeSheet> model)
  229. {
  230. // Perform pre-processing
  231. }
  232. public void ProcessRawData(ProcessRawDataArgs args)
  233. {
  234. // Before PRS calculates anything, you can edit the list of timesheets and assignments it is working with here.
  235. }
  236. public void ProcessActivityBlocks(ProcessActivityBlocksArgs args)
  237. {
  238. // Once PRS has aggregated the list of timesheets and assignments into a list of time blocks with given activities, you can edit these time blocks here.
  239. }
  240. public void ProcessTimeBlocks(ProcessTimeBlocksArgs args)
  241. {
  242. // This function is called after PRS has determined the length, duration and overtime rules for all the blocks of time. Here, you can edit
  243. // this data before it is collated into the export.
  244. }
  245. public void ProcessItem(ProcessItemArgs args)
  246. {
  247. // This is the final function before PRS exports each item. You can edit the data as you wish.
  248. }
  249. public void AfterPost(IDataModel<TimeSheet> model)
  250. {
  251. // Perform post-processing
  252. }
  253. }";
  254. }
  255. }
  256. public class TimesheetTimberlinePoster : ITimberlinePoster<TimeSheet, TimesheetTimberlineSettings>
  257. {
  258. public ScriptDocument? Script { get; set; }
  259. public TimesheetTimberlineSettings Settings { get; set; }
  260. private Dictionary<Guid, Activity> _activities = null!; // Initialised on DoProcess()
  261. private Dictionary<Guid, OvertimeInterval[]> _overtimeIntervals = null!; // Initialised on DoProcess()
  262. public bool BeforePost(IDataModel<TimeSheet> model)
  263. {
  264. model.RemoveTable<Document>("CompanyLogo");
  265. model.RemoveTable<CoreTable>("CompanyInformation");
  266. model.RemoveTable<Employee>();
  267. model.RemoveTable<User>();
  268. model.SetColumns<TimeSheet>(Columns.None<TimeSheet>().Add(x => x.ID)
  269. .Add(x => x.Approved)
  270. .Add(x => x.EmployeeLink.ID)
  271. .Add(x => x.EmployeeLink.Code)
  272. .Add(x => x.Date)
  273. .Add(x => x.ApprovedDuration)
  274. .Add(x => x.ApprovedStart)
  275. .Add(x => x.ApprovedFinish)
  276. .Add(x => x.ActivityLink.ID)
  277. .Add(x => x.JobLink.ID)
  278. .Add(x => x.JobLink.JobNumber));
  279. // Since the activities could come from the assignment or the time sheets, we'll just
  280. // load all the activities, rather than use subquery stuff or multiple tables.
  281. model.AddTable<Activity>(
  282. null,
  283. Columns.None<Activity>().Add(x => x.ID).Add(x => x.Code).Add(x => x.PayrollID).Add(x => x.IsLeave),
  284. null,
  285. isdefault: true);
  286. // Grab every employee on the listed timesheets, that have a PayrollID.
  287. model.AddLookupTable<TimeSheet, Employee>(x => x.EmployeeLink.ID, x => x.ID,
  288. Filter<Employee>.Where(x => x.PayrollID).IsNotEqualTo(""),
  289. Columns.None<Employee>()
  290. .Add(x => x.ID)
  291. .Add(x => x.Code)
  292. .Add(x => x.PayrollID)
  293. .Add(x => x.RosterStart),
  294. lookupalias: "Employees", isdefault: true);
  295. // We also need to load the rosters and all the overtime intervals on those rosters for
  296. // each employee.
  297. model.AddChildTable<Employee, EmployeeRosterItem>(x => x.ID, x => x.Employee.ID,
  298. columns: Columns.None<EmployeeRosterItem>()
  299. .Add(x => x.ID)
  300. .Add(x => x.Overtime.ID)
  301. .Add(x => x.Employee.ID),
  302. parentalias: "Employees", childalias: "Rosters", isdefault: true);
  303. // Note how we skip the actual Overtime class and just link on the shared link.
  304. model.AddChildTable<EmployeeRosterItem, OvertimeInterval>(x => x.Overtime.ID, x => x.Overtime.ID,
  305. null,
  306. Columns.None<OvertimeInterval>().Add(x => x.ID)
  307. .Add(x => x.Overtime.ID)
  308. .Add(x => x.Sequence)
  309. .Add(x => x.IntervalType)
  310. .Add(x => x.Interval)
  311. .Add(x => x.PayrollID)
  312. .Add(x => x.IsPaid),
  313. isdefault: true,
  314. parentalias: "Rosters");
  315. // Also need every assignment on the same date as the listed timesheets. This will load
  316. // more than necessary, since we only care about those for the right employees, but this
  317. // is simpler than having a complex sub-query. I guess our data model system doesn't
  318. // allow for multiple parent tables.
  319. model.AddLookupTable<TimeSheet, Assignment>(x => x.Date, x => x.Date, null,
  320. Columns.None<Assignment>().Add(x => x.ID)
  321. .Add(x => x.Date)
  322. .Add(x => x.EmployeeLink.ID)
  323. .Add(x => x.Actual.Start)
  324. .Add(x => x.Actual.Duration)
  325. .Add(x => x.Actual.Finish)
  326. .Add(x => x.Booked.Start)
  327. .Add(x => x.Booked.Duration)
  328. .Add(x => x.Booked.Finish)
  329. .Add(x => x.ActivityLink.ID),
  330. isdefault: true);
  331. Script?.Execute(methodname: "BeforePost", parameters: new object[] { model });
  332. return true;
  333. }
  334. private void ProcessRawData(ProcessRawDataArgs args)
  335. {
  336. Script?.Execute(methodname: "ProcessRawData", parameters: new object[] { args });
  337. }
  338. private void ProcessActivityBlocks(ProcessActivityBlocksArgs args)
  339. {
  340. Script?.Execute(methodname: "ProcessActivityBlocks", parameters: new object[] { args });
  341. }
  342. private void ProcessTimeBlocks(ProcessTimeBlocksArgs args)
  343. {
  344. Script?.Execute(methodname: "ProcessTimeBlocks", parameters: new object[] { args });
  345. }
  346. private void ProcessItem(ProcessItemArgs args)
  347. {
  348. Script?.Execute(methodname: "ProcessItem", parameters: new object[] { args });
  349. }
  350. /// <summary>
  351. /// Return a list of <see cref="ActivityBlock"/>s, where every assignment in the given list
  352. /// that occurs within the timesheet is given a block of time, and any remaining time is
  353. /// filled by the time sheet.
  354. /// </summary>
  355. /// <remarks>
  356. /// <list type="bullet">
  357. /// <item>
  358. /// If the time sheet is of type leave, it completely overrides the assignments.
  359. /// </item>
  360. /// <item>
  361. /// If there are any overlapping assignments, their total time is merged and then
  362. /// distributed proportionally to each of the overlapping assignments, outputted in
  363. /// order by start time.
  364. /// </item>
  365. /// </list>
  366. /// </remarks>
  367. /// <returns>
  368. /// A list of activity blocks, starting at the beginning of the time sheet and filling
  369. /// continuous time to the end of the time sheet.
  370. /// </returns>
  371. private IEnumerable<ActivityBlock> GetMaskedActivityBlocks(IEnumerable<Assignment> assignments, TimeSheet sheet)
  372. {
  373. // If the time sheet has an activity which is leave, it overrides any assignments.
  374. if (sheet.ActivityLink.ID != Guid.Empty
  375. && _activities.TryGetValue(sheet.ActivityLink.ID, out var activity)
  376. && activity.IsLeave)
  377. {
  378. yield return new ActivityBlock(sheet);
  379. yield break;
  380. }
  381. // Otherwise, we find every assignment that exists inside this time sheet, and truncate (or "chop") it to fit
  382. // inside the time sheet. We also want to order by time.
  383. var blocks = assignments.Select(x => new ActivityBlock(x, sheet))
  384. .Where(x => x.ContainedInTimeSheet(sheet)).Select(x => x.Chop(sheet))
  385. .OrderBy(x => x.Start).ToList();
  386. // Redistribute time of overlapping blocks.
  387. for(int i = 0; i < blocks.Count; ++i)
  388. {
  389. var block = blocks[i];
  390. // Total duration of all overlapping blocks.
  391. var totalTime = block.Duration;
  392. // End time of the block created by merging all overlapping blocks.
  393. var maxFinish = block.Finish;
  394. // Find all overlapping blocks; j represents the next non-overlapping block.
  395. int j = i + 1;
  396. for (; j < blocks.Count && block.IntersectsWith(blocks[j]); ++j)
  397. {
  398. totalTime += blocks[j].Duration;
  399. if (blocks[j].Finish > maxFinish)
  400. {
  401. maxFinish = blocks[j].Finish;
  402. }
  403. }
  404. // Total time of the block created by merging all overlapping blocks.
  405. var netTime = maxFinish - block.Start;
  406. var start = block.Start;
  407. for(int k = i; k < j; ++k)
  408. {
  409. var newBlock = blocks[k];
  410. var frac = newBlock.Duration.TotalHours / totalTime.TotalHours;
  411. var duration = netTime.Multiply(frac);
  412. newBlock.Start = start;
  413. newBlock.Finish = start + duration;
  414. start = newBlock.Finish;
  415. }
  416. // Note that we don't skip over the blocks that we have re-distributed time to, since any of the blocks after 'i'
  417. // may overlap with later blocks that don't overlap with blocks[i]. However, after redistributing, blocks[i] will only
  418. // get smaller, not bigger, so blocks[i] definitely won't overlap with later blocks, and so can now be safely skipped.
  419. }
  420. // Keep track of the current time, which is the end of the last block processed.
  421. var curTime = sheet.ApprovedStart;
  422. foreach(var block in blocks)
  423. {
  424. // If there is a gap between the last block and the current block, then we use the
  425. // time sheet to create a small activity block filling the gap.
  426. if (block.Start > curTime)
  427. {
  428. yield return new ActivityBlock(sheet, curTime, block.Start);
  429. }
  430. yield return block;
  431. curTime = block.Finish;
  432. }
  433. // If there is time at the end, also fill that extra time using the time sheet.
  434. if(curTime < sheet.ApprovedFinish)
  435. {
  436. yield return new ActivityBlock(sheet, curTime, sheet.ApprovedFinish);
  437. }
  438. }
  439. /// <summary>
  440. /// Based on <see cref="TimesheetTimberlineSettings.ActivityCalculation"/>, split each
  441. /// timesheet up into a number of activity blocks. Note that time is <b>only</b> allocated
  442. /// where a time sheet is, so that there will be no ActivityBlocks with time outside of the
  443. /// time represented by the list of time sheets.
  444. /// </summary>
  445. /// <remarks>
  446. /// The output will have continuous activity blocks filling all the time of each time sheet.
  447. /// <br/>
  448. /// Note that if the timesheets themselves overlap, no special functionality exists, and
  449. /// there will in this case be overlapping time blocks.
  450. /// </remarks>
  451. /// <param name="assignments">A list of assignments for this employee and date.</param>
  452. /// <param name="sheets">A list of timesheets for this employee and date.</param>
  453. /// <returns>A list of blocks of time that represent an activity the employee was doing.</returns>
  454. private List<ActivityBlock> GetActivityBlocks(IEnumerable<Assignment> assignments, IList<TimeSheet> sheets)
  455. {
  456. switch (Settings.ActivityCalculation)
  457. {
  458. case TimesheetTimberlineActivityCalculation.TimesheetOnly:
  459. // In this case, we ignore 'assignments' entirely and just the time sheet constructor for the blocks.
  460. return sheets.Select(x => new ActivityBlock(x)).OrderBy(x => x.Start).ToList();
  461. case TimesheetTimberlineActivityCalculation.TimesheetPriority:
  462. var sheetLookup = sheets.ToLookup(x => x.ActivityLink.ID == Guid.Empty);
  463. // Every timesheet that has an activity is a valid activity block. Then, for
  464. // each timesheet without an activity, we merge the assignments into the time sheet.
  465. return sheetLookup[false].Select(x => new ActivityBlock(x))
  466. .Concat(sheetLookup[true].SelectMany(x => GetMaskedActivityBlocks(assignments, x)))
  467. .OrderBy(x => x.Start)
  468. .ToList();
  469. case TimesheetTimberlineActivityCalculation.AssignmentPriority:
  470. // Every timesheet is masked, unless it is a leave timesheet.
  471. return sheets.SelectMany(x => GetMaskedActivityBlocks(assignments, x)).OrderBy(x => x.Start).ToList();
  472. default:
  473. throw new Exception($"Invalid Activity calculation {Settings.ActivityCalculation}");
  474. }
  475. }
  476. /// <summary>
  477. /// Take a list of paid work blocks, and create a new list of paid work blocks by assigning
  478. /// PayrollIDs based on the overtime intervals. If a given interval is unpaid, then no paid
  479. /// work blocks are created for that time.
  480. /// </summary>
  481. private List<IBlock> EvaluateOvertime(IEnumerable<IBlock> time, Guid overtimeID)
  482. {
  483. var overtimeIntervals = _overtimeIntervals.GetValueOrDefault(overtimeID)?.ToArray() ?? [];
  484. var newItems = new List<IBlock>();
  485. OvertimeUtils.EvaluateOvertime(time, overtimeIntervals, x => x.Duration, (block, interval, duration) =>
  486. {
  487. if(interval is null)
  488. {
  489. // Shouldn't ever occur, thanks to RemainingTime being required.
  490. if(block is PaidWorkBlock paid)
  491. {
  492. newItems.Add(new PaidWorkBlock(block.TaskID, duration, "", block.Job, block.TimeSheet));
  493. }
  494. else if(block is LeaveBlock leave)
  495. {
  496. newItems.Add(new LeaveBlock(leave.PayrollID, duration, leave.TimeSheet));
  497. }
  498. }
  499. else if (interval.IsPaid)
  500. {
  501. if (block is PaidWorkBlock paid)
  502. {
  503. newItems.Add(new PaidWorkBlock(block.TaskID, duration, interval.PayrollID, block.Job, block.TimeSheet));
  504. }
  505. else if (block is LeaveBlock leave)
  506. {
  507. newItems.Add(new LeaveBlock(leave.PayrollID, duration, leave.TimeSheet));
  508. }
  509. }
  510. });
  511. return newItems;
  512. }
  513. private TimeSheetTimberlineResult DoProcess(IDataModel<TimeSheet> model)
  514. {
  515. var items = new TimeSheetTimberlineResult();
  516. var timesheets = model.GetTable<TimeSheet>().ToObjects<TimeSheet>().ToList();
  517. if(timesheets.Any(x => x.Approved.IsEmpty()))
  518. {
  519. throw new Exception("Unapproved Timesheets detected");
  520. }
  521. else if (!timesheets.Any())
  522. {
  523. throw new Exception("No approved timesheets found");
  524. }
  525. _activities = model.GetTable<Activity>().ToObjects<Activity>().ToDictionary(x => x.ID, x => x);
  526. _overtimeIntervals = model.GetTable<OvertimeInterval>().ToObjects<OvertimeInterval>()
  527. .GroupBy(x => x.Overtime.ID)
  528. .ToDictionary(x => x.Key, x => x.OrderBy(x => x.Sequence).ToArray());
  529. var rosters = model.GetTable<EmployeeRosterItem>("Rosters").ToObjects<EmployeeRosterItem>()
  530. .GroupBy(x => x.Employee.ID).ToDictionary(x => x.Key, x => x.ToArray());
  531. var employees = model.GetTable<Employee>("Employees").ToObjects<Employee>()
  532. .ToDictionary(x => x.ID, x => x);
  533. // We run through by date and employee, grouping both assignments and time sheets.
  534. var assignments = model.GetTable<Assignment>().ToObjects<Assignment>()
  535. .GroupBy(x => new { x.Date, Employee = x.EmployeeLink.ID }).ToDictionary(x => x.Key, x => x.ToList());
  536. var daily = timesheets.GroupBy(x => new { x.Date, Employee = x.EmployeeLink.ID }).ToDictionary(x => x.Key, x => x.ToList());
  537. foreach(var (key, sheets) in daily)
  538. {
  539. var dateAssignments = assignments.GetValueOrDefault(new { key.Date, key.Employee }, new List<Assignment>());
  540. // Delegate to script to process raw data.
  541. var rawArgs = new ProcessRawDataArgs(model, key.Employee, key.Date, sheets, dateAssignments);
  542. ProcessRawData(rawArgs);
  543. if (rawArgs.Cancel)
  544. {
  545. foreach(var sheet in sheets)
  546. {
  547. items.AddFailed(sheet, "Post cancelled by script.");
  548. }
  549. continue;
  550. }
  551. // Split each timesheet into its activity blocks.
  552. var activityBlocks = GetActivityBlocks(rawArgs.Assignments, rawArgs.TimeSheets);
  553. // Process activity blocks with script.
  554. var activityArgs = new ProcessActivityBlocksArgs(model, key.Employee, key.Date, activityBlocks);
  555. ProcessActivityBlocks(activityArgs);
  556. if (activityArgs.Cancel)
  557. {
  558. foreach (var sheet in sheets)
  559. {
  560. items.AddFailed(sheet, "Post cancelled by script.");
  561. }
  562. continue;
  563. }
  564. // Add up all the time for the time sheets.
  565. var approvedDuration = rawArgs.TimeSheets.Aggregate(TimeSpan.Zero, (x, y) => x + y.ApprovedDuration);
  566. if(approvedDuration == TimeSpan.Zero)
  567. {
  568. foreach (var sheet in sheets)
  569. {
  570. items.AddFailed(sheet, "Zero Approved Duration");
  571. }
  572. continue;
  573. }
  574. // Convert the activity blocks into LeaveBlocks and PaidWorkBlocks, based on the activity on the block.
  575. var blocks = new List<IBlock>();
  576. foreach (var block in activityArgs.ActivityBlocks)
  577. {
  578. string taskID;
  579. bool isLeave;
  580. if (block.Activity == Guid.Empty
  581. || !_activities.TryGetValue(block.Activity, out var activity))
  582. {
  583. if(block.Activity != Guid.Empty)
  584. {
  585. Logger.Send(LogType.Error, "", $"Error in Timesheet Timberline export: Activity {block.Activity} does not exist!");
  586. }
  587. taskID = "";
  588. isLeave = false;
  589. }
  590. else
  591. {
  592. isLeave = activity.IsLeave;
  593. taskID = activity.PayrollID;
  594. }
  595. if (isLeave)
  596. {
  597. blocks.Add(new LeaveBlock(taskID, block.Finish - block.Start, block.TimeSheet));
  598. }
  599. else
  600. {
  601. // Leave PayID blank until we've worked out the rosters
  602. blocks.Add(new PaidWorkBlock(taskID, block.Finish - block.Start, "", block.TimeSheet.JobLink, block.TimeSheet));
  603. }
  604. }
  605. // Find the roster data.
  606. var employee = employees.GetValueOrDefault(key.Employee);
  607. var employeeRosters = rosters.GetValueOrDefault(employee != null ? employee.ID : Guid.Empty);
  608. var overtimeID = RosterUtils.GetRoster(employeeRosters, employee?.RosterStart, key.Date)?.Overtime.ID ?? Guid.Empty;
  609. // Split up the paid work blocks by the overtime and assign PayrollIDs.
  610. var blockItems = EvaluateOvertime(blocks, overtimeID);
  611. var blockArgs = new ProcessTimeBlocksArgs(model, key.Employee, key.Date, blockItems);
  612. ProcessTimeBlocks(blockArgs);
  613. if (blockArgs.Cancel)
  614. {
  615. foreach (var sheet in sheets)
  616. {
  617. items.AddFailed(sheet, "Post cancelled by script.");
  618. }
  619. continue;
  620. }
  621. // First presumptively succeed all sheets, and then fail them if any of their blocks are failed.
  622. foreach (var sheet in sheets)
  623. {
  624. items.AddSuccess(sheet);
  625. }
  626. var newItems = new List<Tuple<TimesheetTimberlineItem, List<TimeSheet>>>();
  627. // Group the blocks by job, TaskID (activity PayrollID) and PayrollID (from the overtime interval).
  628. foreach(var group in blockItems.GroupBy(x => new { x.Job.ID, x.TaskID, x.PayrollID }))
  629. {
  630. var block = group.ToArray();
  631. var first = block[0];
  632. var item = new TimesheetTimberlineItem
  633. {
  634. Employee = employee?.PayrollID ?? "",
  635. InDate = DateOnly.FromDateTime(key.Date),
  636. Job = first.Job.JobNumber,
  637. Extra = "",
  638. Task = group.Key.TaskID,
  639. Hours = Math.Round(group.Sum(x => x.Duration.TotalHours), 2),
  640. PayID = group.Key.PayrollID
  641. };
  642. var itemArgs = new ProcessItemArgs(model, key.Employee, key.Date, first.Job, item);
  643. ProcessItem(itemArgs);
  644. var blockTimeSheets = block.Select(x => x.TimeSheet).ToList();
  645. if (!itemArgs.Cancel)
  646. {
  647. newItems.Add(new(itemArgs.Item, blockTimeSheets));
  648. }
  649. else
  650. {
  651. foreach(var sheet in blockTimeSheets)
  652. {
  653. (sheet as IPostable).FailPost("Post cancelled by script.");
  654. }
  655. }
  656. }
  657. foreach(var item in newItems)
  658. {
  659. if(item.Item2.All(x => x.PostedStatus == PostedStatus.Posted))
  660. {
  661. items.AddItem(item.Item1);
  662. }
  663. }
  664. }
  665. items.Sort();
  666. return items;
  667. }
  668. public IPostResult<TimeSheet> Process(IDataModel<TimeSheet> model)
  669. {
  670. var items = DoProcess(model);
  671. var dlg = new SaveFileDialog()
  672. {
  673. Filter = "CSV Files (*.csv)|*.csv"
  674. };
  675. if (dlg.ShowDialog() == true)
  676. {
  677. using var writer = new StreamWriter(dlg.FileName);
  678. using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
  679. foreach (var item in items.Items)
  680. {
  681. csv.WriteRecord(item);
  682. csv.NextRecord();
  683. }
  684. return items;
  685. }
  686. else
  687. {
  688. throw new PostCancelledException();
  689. }
  690. }
  691. public void AfterPost(IDataModel<TimeSheet> model, IPostResult<TimeSheet> result)
  692. {
  693. Script?.Execute(methodname: "AfterPost", parameters: new object[] { model });
  694. }
  695. }
  696. public class TimesheetTimberlinePosterEngine<T> : TimberlinePosterEngine<TimeSheet, TimesheetTimberlineSettings>
  697. {
  698. }
  699. }